repo
stringclasses
1 value
instance_id
stringlengths
22
24
problem_statement
stringlengths
30
24.1k
patch
stringlengths
0
1.9M
test_patch
stringclasses
1 value
created_at
stringdate
2022-11-25 05:12:07
2025-06-13 10:24:29
hints_text
stringlengths
0
234k
base_commit
stringlengths
40
40
test_instructions
stringlengths
0
232k
filenames
listlengths
0
300
juspay/hyperswitch
juspay__hyperswitch-4997
Bug: [FEATURE] Use Ephemeral auth for Customer PM list and PM delete APIs ### Feature Description We want to enable Ephemeral auth for both customer's PM list and PM delete API for the SDK to be able to use these APIs in a non-payments context ### Possible Implementation Implementation would involve changing the Ephemeral auth types and auth process for the said APIs ### 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/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs index 65abb012b9a..264f205c907 100644 --- a/crates/router/src/compatibility/stripe/customers.rs +++ b/crates/router/src/compatibility/stripe/customers.rs @@ -195,6 +195,7 @@ pub async fn list_customer_payment_method_api( auth.key_store, Some(req), Some(&customer_id), + None, ) }, &auth::ApiKeyAuth, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 0641c842390..62a0b65e7cf 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -64,6 +64,7 @@ use crate::{ pii::prelude::*, routes::{ self, + app::SessionStateInfo, metrics::{self, request}, payment_methods::ParentPaymentMethodToken, }, @@ -3080,10 +3081,25 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed( key_store: domain::MerchantKeyStore, req: Option<api::PaymentMethodListRequest>, customer_id: Option<&id_type::CustomerId>, + ephemeral_api_key: Option<&str>, ) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> { let db = state.store.as_ref(); let limit = req.clone().and_then(|pml_req| pml_req.limit); + let auth_cust = if let Some(key) = ephemeral_api_key { + let key = state + .store() + .get_ephemeral_key(key) + .await + .change_context(errors::ApiErrorResponse::Unauthorized)?; + + Some(key.customer_id.clone()) + } else { + None + }; + + let customer_id = customer_id.or(auth_cust.as_ref()); + if let Some(customer_id) = customer_id { Box::pin(list_customer_payment_method( &state, diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index 87366cf5c6d..4684edbd18d 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -47,7 +47,7 @@ pub async fn customers_retrieve( let auth = if auth::is_jwt_auth(req.headers()) { Box::new(auth::JWTAuth(Permission::CustomerRead)) } else { - match auth::is_ephemeral_auth(req.headers(), &payload.customer_id) { + match auth::is_ephemeral_auth(req.headers()) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), } diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index e36a8fc3ea5..09b5c625711 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -139,7 +139,7 @@ pub async fn list_customer_payment_method_api( let payload = query_payload.into_inner(); let customer_id = customer_id.into_inner().0; - let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), &customer_id) { + let ephemeral_auth = match auth::is_ephemeral_auth(req.headers()) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; @@ -155,6 +155,7 @@ pub async fn list_customer_payment_method_api( auth.key_store, Some(req), Some(&customer_id), + None, ) }, &*ephemeral_auth, @@ -194,10 +195,12 @@ pub async fn list_customer_payment_method_api_client( ) -> HttpResponse { let flow = Flow::CustomerPaymentMethodsList; let payload = query_payload.into_inner(); - let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) { - Ok((auth, _auth_flow)) => (auth, _auth_flow), - Err(e) => return api::log_and_return_error_response(e), - }; + let api_key = auth::get_api_key(req.headers()).ok(); + let (auth, _, is_ephemeral_auth) = + match auth::get_ephemeral_or_other_auth(req.headers(), false, Some(&payload)).await { + Ok((auth, _auth_flow, is_ephemeral_auth)) => (auth, _auth_flow, is_ephemeral_auth), + Err(e) => return api::log_and_return_error_response(e), + }; Box::pin(api::server_wrap( flow, @@ -211,6 +214,7 @@ pub async fn list_customer_payment_method_api_client( auth.key_store, Some(req), None, + is_ephemeral_auth.then_some(api_key).flatten(), ) }, &*auth, @@ -291,6 +295,11 @@ pub async fn payment_method_delete_api( let pm = PaymentMethodId { payment_method_id: payment_method_id.into_inner().0, }; + let ephemeral_auth = match auth::is_ephemeral_auth(req.headers()) { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(err), + }; + Box::pin(api::server_wrap( flow, state, @@ -299,7 +308,7 @@ pub async fn payment_method_delete_api( |state, auth, req, _| { cards::delete_payment_method(state, auth.merchant_account, req, auth.key_store) }, - &auth::ApiKeyAuth, + &*ephemeral_auth, api_locking::LockAction::NotApplicable, )) .await @@ -345,7 +354,7 @@ pub async fn default_payment_method_set_api( let pc = payload.clone(); let customer_id = &pc.customer_id; - let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), customer_id) { + let ephemeral_auth = match auth::is_ephemeral_auth(req.headers()) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 72d0860eed9..e2224da29ea 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -5,7 +5,7 @@ use api_models::{ }; use async_trait::async_trait; use common_enums::TokenPurpose; -use common_utils::{date_time, id_type}; +use common_utils::date_time; use error_stack::{report, ResultExt}; use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; use masking::PeekInterface; @@ -440,7 +440,7 @@ where } #[derive(Debug)] -pub struct EphemeralKeyAuth(pub id_type::CustomerId); +pub struct EphemeralKeyAuth; #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for EphemeralKeyAuth @@ -460,9 +460,6 @@ where .await .change_context(errors::ApiErrorResponse::Unauthorized)?; - if ephemeral_key.customer_id.ne(&self.0) { - return Err(report!(errors::ApiErrorResponse::InvalidEphemeralKey)); - } MerchantIdAuth(ephemeral_key.merchant_id) .authenticate_and_fetch(request_headers, state) .await @@ -1046,16 +1043,43 @@ where Ok((Box::new(ApiKeyAuth), api::AuthFlow::Merchant)) } +pub async fn get_ephemeral_or_other_auth<T>( + headers: &HeaderMap, + is_merchant_flow: bool, + payload: Option<&impl ClientSecretFetch>, +) -> RouterResult<( + Box<dyn AuthenticateAndFetch<AuthenticationData, T>>, + api::AuthFlow, + bool, +)> +where + T: SessionStateInfo, + ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, + PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, + EphemeralKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, +{ + let api_key = get_api_key(headers)?; + + if api_key.starts_with("epk") { + Ok((Box::new(EphemeralKeyAuth), api::AuthFlow::Client, true)) + } else if is_merchant_flow { + Ok((Box::new(ApiKeyAuth), api::AuthFlow::Merchant, false)) + } else { + let payload = payload.get_required_value("ClientSecretFetch")?; + let (auth, auth_flow) = check_client_secret_and_get_auth(headers, payload)?; + Ok((auth, auth_flow, false)) + } +} + pub fn is_ephemeral_auth<A: SessionStateInfo + Sync>( headers: &HeaderMap, - customer_id: &id_type::CustomerId, ) -> RouterResult<Box<dyn AuthenticateAndFetch<AuthenticationData, A>>> { let api_key = get_api_key(headers)?; if !api_key.starts_with("epk") { Ok(Box::new(ApiKeyAuth)) } else { - Ok(Box::new(EphemeralKeyAuth(customer_id.to_owned()))) + Ok(Box::new(EphemeralKeyAuth)) } }
2024-06-13T10:38:24Z
## Description <!-- Describe your changes in detail --> This PR enables - - Ephemeral key auth for customer's pm list - Ephemeral key auth for delete payment method ### 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 for a customer 2. Create Ephemeral key for that customer ``` curl --location --request POST 'http://localhost:8080/ephemeral_keys' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' \ --data-raw '{ "customer_id": "cus_q1KVr57JhvRlVHToTKkY" }' ``` Response - ``` { "id": "eki_DuTISISBl1O0MAyczMQ8", "merchant_id": "sarthak1", "customer_id": "cus_grCxh6TyR6uepXyc6p7q", "created_at": 1718270809, "expires": 1718274409, "secret": "epk_67d4e3b46c49402badcbff4901cfef67" } ``` 3. Use the Ephemeral key secret to call customer's pm list ``` curl --location --request GET 'http://localhost:8080/customers/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: epk_be243219006647c69cdd7111d490d79a' ``` Response - ``` { "customer_payment_methods": [ { "payment_token": "token_9OtU08A46TOZcmfislqy", "payment_method_id": "pm_RPkRCYXKIWZFj0Qr36E9", "customer_id": "Some_cust1", "payment_method": "card", "payment_method_type": null, "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "10", "expiry_year": "2025", "card_token": null, "card_holder_name": "joseph Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "metadata": null, "created": "2024-06-13T09:59:16.717Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-06-13T09:59:16.717Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } } ], "is_guest_customer": null } ``` 4. Separate flow, Delete a PM using Ephemeral key ``` curl --location --request DELETE 'http://localhost:8080/payment_methods/pm_RPkRCYXKIWZFj0Qr36E9' \ --header 'Accept: application/json' \ --header 'api-key: epk_be243219006647c69cdd7111d490d79a' ``` Response - ``` { "payment_method_id": "pm_RPkRCYXKIWZFj0Qr36E9", "deleted": true } ```
0e059e7d847b0c15ed120c72bb4902ac60e6f955
1. Save a card for a customer 2. Create Ephemeral key for that customer ``` curl --location --request POST 'http://localhost:8080/ephemeral_keys' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' \ --data-raw '{ "customer_id": "cus_q1KVr57JhvRlVHToTKkY" }' ``` Response - ``` { "id": "eki_DuTISISBl1O0MAyczMQ8", "merchant_id": "sarthak1", "customer_id": "cus_grCxh6TyR6uepXyc6p7q", "created_at": 1718270809, "expires": 1718274409, "secret": "epk_67d4e3b46c49402badcbff4901cfef67" } ``` 3. Use the Ephemeral key secret to call customer's pm list ``` curl --location --request GET 'http://localhost:8080/customers/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: epk_be243219006647c69cdd7111d490d79a' ``` Response - ``` { "customer_payment_methods": [ { "payment_token": "token_9OtU08A46TOZcmfislqy", "payment_method_id": "pm_RPkRCYXKIWZFj0Qr36E9", "customer_id": "Some_cust1", "payment_method": "card", "payment_method_type": null, "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "10", "expiry_year": "2025", "card_token": null, "card_holder_name": "joseph Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "metadata": null, "created": "2024-06-13T09:59:16.717Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-06-13T09:59:16.717Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } } ], "is_guest_customer": null } ``` 4. Separate flow, Delete a PM using Ephemeral key ``` curl --location --request DELETE 'http://localhost:8080/payment_methods/pm_RPkRCYXKIWZFj0Qr36E9' \ --header 'Accept: application/json' \ --header 'api-key: epk_be243219006647c69cdd7111d490d79a' ``` Response - ``` { "payment_method_id": "pm_RPkRCYXKIWZFj0Qr36E9", "deleted": true } ```
[ "crates/router/src/compatibility/stripe/customers.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/routes/customers.rs", "crates/router/src/routes/payment_methods.rs", "crates/router/src/services/authentication.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4992
Bug: feat(users): Decision manager changes for SSO Flows Because SSO needs new flows and will affect other login flows and email flows like accept invite, we have to change some flows in Decision Manager for SSO flows.
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index decbf9fd12a..f6d47f9a638 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2758,6 +2758,10 @@ pub enum BankHolderType { #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum TokenPurpose { + AuthSelect, + #[serde(rename = "sso")] + #[strum(serialize = "sso")] + SSO, #[serde(rename = "totp")] #[strum(serialize = "totp")] TOTP, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 6803b79d6ce..505cee0c4ac 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1048,7 +1048,7 @@ pub async fn accept_invite_from_email_token_only_flow( .map_err(|e| logger::error!(?e)); let current_flow = domain::CurrentFlow::new( - user_token.origin, + user_token, domain::SPTFlow::AcceptInvitationFromEmail.into(), )?; let next_flow = current_flow.next(user_from_db.clone(), &state).await?; @@ -1502,8 +1502,7 @@ pub async fn verify_email_token_only_flow( .await .map_err(|e| logger::error!(?e)); - let current_flow = - domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::VerifyEmail.into())?; + let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::VerifyEmail.into())?; let next_flow = current_flow.next(user_from_db, &state).await?; let token = next_flow.get_token(&state).await?; @@ -1959,7 +1958,7 @@ pub async fn terminate_two_factor_auth( } } - let current_flow = domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::TOTP.into())?; + let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::TOTP.into())?; let next_flow = current_flow.next(user_from_db, &state).await?; let token = next_flow.get_token(&state).await?; diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index c4beb0fe9a4..9e7f676c095 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -288,7 +288,7 @@ pub async fn merchant_select_token_only_flow( .into(); let current_flow = - domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::MerchantSelect.into())?; + domain::CurrentFlow::new(user_token, domain::SPTFlow::MerchantSelect.into())?; let next_flow = current_flow.next(user_from_db.clone(), &state).await?; let token = next_flow diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index e2224da29ea..675b3951806 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -124,6 +124,7 @@ impl AuthenticationType { pub struct UserFromSinglePurposeToken { pub user_id: String, pub origin: domain::Origin, + pub path: Vec<TokenPurpose>, } #[cfg(feature = "olap")] @@ -132,6 +133,7 @@ pub struct SinglePurposeToken { pub user_id: String, pub purpose: TokenPurpose, pub origin: domain::Origin, + pub path: Vec<TokenPurpose>, pub exp: u64, } @@ -142,6 +144,7 @@ impl SinglePurposeToken { purpose: TokenPurpose, origin: domain::Origin, settings: &Settings, + path: Vec<TokenPurpose>, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::SINGLE_PURPOSE_TOKEN_TIME_IN_SECS); @@ -151,6 +154,7 @@ impl SinglePurposeToken { purpose, origin, exp, + path, }; jwt::generate_jwt(&token_payload, settings).await } @@ -356,6 +360,7 @@ where UserFromSinglePurposeToken { user_id: payload.user_id.clone(), origin: payload.origin.clone(), + path: payload.path, }, AuthenticationType::SinglePurposeJwt { user_id: payload.user_id, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 5ff79b7feee..4ad25f003d1 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -1107,6 +1107,7 @@ impl SignInWithMultipleRolesStrategy { TokenPurpose::AcceptInvite, Origin::SignIn, &state.conf, + vec![], ) .await? .into(), diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index 2ee9b389788..ef73b88015f 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -17,9 +17,14 @@ pub enum UserFlow { } impl UserFlow { - async fn is_required(&self, user: &UserFromStorage, state: &SessionState) -> UserResult<bool> { + async fn is_required( + &self, + user: &UserFromStorage, + path: &[TokenPurpose], + state: &SessionState, + ) -> UserResult<bool> { match self { - Self::SPTFlow(flow) => flow.is_required(user, state).await, + Self::SPTFlow(flow) => flow.is_required(user, path, state).await, Self::JWTFlow(flow) => flow.is_required(user, state).await, } } @@ -27,6 +32,8 @@ impl UserFlow { #[derive(Eq, PartialEq, Clone, Copy)] pub enum SPTFlow { + AuthSelect, + SSO, TOTP, VerifyEmail, AcceptInvitationFromEmail, @@ -36,15 +43,26 @@ pub enum SPTFlow { } impl SPTFlow { - async fn is_required(&self, user: &UserFromStorage, state: &SessionState) -> UserResult<bool> { + async fn is_required( + &self, + user: &UserFromStorage, + path: &[TokenPurpose], + state: &SessionState, + ) -> UserResult<bool> { match self { + // Auth + // AuthSelect and SSO flow are not enabled, once the terminate SSO API is ready, we can enable these flows + Self::AuthSelect => Ok(false), + Self::SSO => Ok(false), // TOTP - Self::TOTP => Ok(true), + Self::TOTP => Ok(!path.contains(&TokenPurpose::SSO)), // Main email APIs Self::AcceptInvitationFromEmail | Self::ResetPassword => Ok(true), Self::VerifyEmail => Ok(true), // Final Checks - Self::ForceSetPassword => user.is_password_rotate_required(state), + Self::ForceSetPassword => user + .is_password_rotate_required(state) + .map(|rotate_required| rotate_required && !path.contains(&TokenPurpose::SSO)), Self::MerchantSelect => user .get_roles_from_db(state) .await @@ -62,6 +80,7 @@ impl SPTFlow { self.into(), next_flow.origin.clone(), &state.conf, + next_flow.path.to_vec(), ) .await .map(|token| token.into()) @@ -103,6 +122,8 @@ impl JWTFlow { #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum Origin { + #[serde(rename = "sign_in_with_sso")] + SignInWithSSO, SignIn, SignUp, MagicLink, @@ -114,6 +135,7 @@ pub enum Origin { impl Origin { fn get_flows(&self) -> &'static [UserFlow] { match self { + Self::SignInWithSSO => &SIGNIN_WITH_SSO_FLOW, Self::SignIn => &SIGNIN_FLOW, Self::SignUp => &SIGNUP_FLOW, Self::VerifyEmail => &VERIFY_EMAIL_FLOW, @@ -124,6 +146,11 @@ impl Origin { } } +const SIGNIN_WITH_SSO_FLOW: [UserFlow; 2] = [ + UserFlow::SPTFlow(SPTFlow::MerchantSelect), + UserFlow::JWTFlow(JWTFlow::UserInfo), +]; + const SIGNIN_FLOW: [UserFlow; 4] = [ UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), @@ -154,7 +181,9 @@ const VERIFY_EMAIL_FLOW: [UserFlow; 5] = [ UserFlow::JWTFlow(JWTFlow::UserInfo), ]; -const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 4] = [ +const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 6] = [ + UserFlow::SPTFlow(SPTFlow::AuthSelect), + UserFlow::SPTFlow(SPTFlow::SSO), UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::AcceptInvitationFromEmail), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), @@ -169,31 +198,40 @@ const RESET_PASSWORD_FLOW: [UserFlow; 2] = [ pub struct CurrentFlow { origin: Origin, current_flow_index: usize, + path: Vec<TokenPurpose>, } impl CurrentFlow { - pub fn new(origin: Origin, current_flow: UserFlow) -> UserResult<Self> { - let flows = origin.get_flows(); + pub fn new( + token: auth::UserFromSinglePurposeToken, + current_flow: UserFlow, + ) -> UserResult<Self> { + let flows = token.origin.get_flows(); let index = flows .iter() .position(|flow| flow == &current_flow) .ok_or(UserErrors::InternalServerError)?; + let mut path = token.path; + path.push(current_flow.into()); Ok(Self { - origin, + origin: token.origin, current_flow_index: index, + path, }) } - pub async fn next(&self, user: UserFromStorage, state: &SessionState) -> UserResult<NextFlow> { + pub async fn next(self, user: UserFromStorage, state: &SessionState) -> UserResult<NextFlow> { let flows = self.origin.get_flows(); let remaining_flows = flows.iter().skip(self.current_flow_index + 1); + for flow in remaining_flows { - if flow.is_required(&user, state).await? { + if flow.is_required(&user, &self.path, state).await? { return Ok(NextFlow { origin: self.origin.clone(), next_flow: *flow, user, + path: self.path, }); } } @@ -205,6 +243,7 @@ pub struct NextFlow { origin: Origin, next_flow: UserFlow, user: UserFromStorage, + path: Vec<TokenPurpose>, } impl NextFlow { @@ -214,12 +253,14 @@ impl NextFlow { state: &SessionState, ) -> UserResult<Self> { let flows = origin.get_flows(); + let path = vec![]; for flow in flows { - if flow.is_required(&user, state).await? { + if flow.is_required(&user, &path, state).await? { return Ok(Self { origin, next_flow: *flow, user, + path, }); } } @@ -284,6 +325,8 @@ impl From<UserFlow> for TokenPurpose { impl From<SPTFlow> for TokenPurpose { fn from(value: SPTFlow) -> Self { match value { + SPTFlow::AuthSelect => Self::AuthSelect, + SPTFlow::SSO => Self::SSO, SPTFlow::TOTP => Self::TOTP, SPTFlow::VerifyEmail => Self::VerifyEmail, SPTFlow::AcceptInvitationFromEmail => Self::AcceptInvitationFromEmail,
2024-06-13T10:36:24Z
## Description <!-- Describe your changes in detail --> This PR adds SSO flows in login decision flows. Currently they are disabled as we have no APIs for SSO and will be enabled in upcoming PRs which adds SSO APIs. ### 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 #4992. ## 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)? --> - There should be no changes in any of the flows. - SPT changes can be tested as follows: 1. Generate SPT using any of the token only APIs (I am using Sign in) ```curl curl --location 'http://localhost:8080/user/v2/signin?token_only=true' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "password": "password" }' ``` ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZTY4YzFmZTQtODRiMC00Y2NjLWI4NGYtN2VjYmVkNjg5Y2Q5IiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwicGF0aCI6W10sImV4cCI6MTcxODg3MzYyN30.HK_0mcCyvbFwh-nma48Pbeh2kdkO7s3FsVOtIc6UF9w", "token_type": "totp" } ``` 2. Complete the next step ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: SPT with Purpose as `totp`' \ ``` ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMzBkOGVkYTEtOWM2ZC00MjgwLTg3MDgtN2MwMjBjY2U1ZmNkIiwicHVycG9zZSI6ImFjY2VwdF9pbnZpdGF0aW9uX2Zyb21fZW1haWwiLCJvcmlnaW4iOiJhY2NlcHRfaW52aXRhdGlvbl9mcm9tX2VtYWlsIiwicGF0aCI6WyJ0b3RwIl0sImV4cCI6MTcxODg3OTQ3OH0.tLsVZ-kYbaxaXaq3Jn4-kJ0ghswonTCjbclUrWZLeoc", "token_type": "accept_invitation_from_email" } ``` The above token when decoded (using [this](https://jwt.io/)), it should have the `path` field with the step that has been completed. And the SPT body will look something like this: ``` { "user_id": "30d8eda1-9c6d-4280-8708-7c020cce5fcd", "purpose": "accept_invitation_from_email", "origin": "accept_invitation_from_email", "path": [ "totp" ], "exp": 1718879478 } ```
e658899c1406225bb905ce4fb76e13fa3609666e
- There should be no changes in any of the flows. - SPT changes can be tested as follows: 1. Generate SPT using any of the token only APIs (I am using Sign in) ```curl curl --location 'http://localhost:8080/user/v2/signin?token_only=true' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "password": "password" }' ``` ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZTY4YzFmZTQtODRiMC00Y2NjLWI4NGYtN2VjYmVkNjg5Y2Q5IiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwicGF0aCI6W10sImV4cCI6MTcxODg3MzYyN30.HK_0mcCyvbFwh-nma48Pbeh2kdkO7s3FsVOtIc6UF9w", "token_type": "totp" } ``` 2. Complete the next step ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: SPT with Purpose as `totp`' \ ``` ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMzBkOGVkYTEtOWM2ZC00MjgwLTg3MDgtN2MwMjBjY2U1ZmNkIiwicHVycG9zZSI6ImFjY2VwdF9pbnZpdGF0aW9uX2Zyb21fZW1haWwiLCJvcmlnaW4iOiJhY2NlcHRfaW52aXRhdGlvbl9mcm9tX2VtYWlsIiwicGF0aCI6WyJ0b3RwIl0sImV4cCI6MTcxODg3OTQ3OH0.tLsVZ-kYbaxaXaq3Jn4-kJ0ghswonTCjbclUrWZLeoc", "token_type": "accept_invitation_from_email" } ``` The above token when decoded (using [this](https://jwt.io/)), it should have the `path` field with the step that has been completed. And the SPT body will look something like this: ``` { "user_id": "30d8eda1-9c6d-4280-8708-7c020cce5fcd", "purpose": "accept_invitation_from_email", "origin": "accept_invitation_from_email", "path": [ "totp" ], "exp": 1718879478 } ```
[ "crates/common_enums/src/enums.rs", "crates/router/src/core/user.rs", "crates/router/src/core/user_role.rs", "crates/router/src/services/authentication.rs", "crates/router/src/types/domain/user.rs", "crates/router/src/types/domain/user/decision_manager.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4970
Bug: bug(user): Magic link is not expiring after being used once When a verified user is using magic link, that magic link is not blacklisted after being used once. User is able to use the same magic link to login to dashboard multiple times.
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index c78f2c8080f..7e79e9e2e89 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -505,10 +505,8 @@ pub async fn reset_password_token_only_flow( let user = state .global_store - .update_user_by_email( - &email_token - .get_email() - .change_context(UserErrors::InternalServerError)?, + .update_user_by_user_id( + user_from_db.get_user_id(), storage_user::UserUpdate::PasswordUpdate { password: hash_password, }, @@ -516,6 +514,17 @@ pub async fn reset_password_token_only_flow( .await .change_context(UserErrors::InternalServerError)?; + if !user_from_db.is_verified() { + let _ = state + .global_store + .update_user_by_user_id( + user_from_db.get_user_id(), + storage_user::UserUpdate::VerifyUser, + ) + .await + .map_err(|e| logger::error!(?e)); + } + let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) .await .map_err(|e| logger::error!(?e)); @@ -1021,6 +1030,17 @@ pub async fn accept_invite_from_email_token_only_flow( .await .change_context(UserErrors::InternalServerError)?; + if !user_from_db.is_verified() { + let _ = state + .global_store + .update_user_by_user_id( + user_from_db.get_user_id(), + storage_user::UserUpdate::VerifyUser, + ) + .await + .map_err(|e| logger::error!(?e)); + } + let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) .await .map_err(|e| logger::error!(?e)); @@ -1476,13 +1496,9 @@ pub async fn verify_email_token_only_flow( .change_context(UserErrors::InternalServerError)? .into(); - if matches!(user_token.origin, domain::Origin::VerifyEmail) - || matches!(user_token.origin, domain::Origin::MagicLink) - { - let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) - .await - .map_err(|e| logger::error!(?e)); - } + let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) + .await + .map_err(|e| logger::error!(?e)); let current_flow = domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::VerifyEmail.into())?; diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 47f26ce04e5..5ff79b7feee 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -837,6 +837,10 @@ impl UserFromStorage { Ok(Some(days_left_for_verification.whole_days())) } + pub fn is_verified(&self) -> bool { + self.0.is_verified + } + pub fn is_password_rotate_required(&self, state: &SessionState) -> UserResult<bool> { let last_password_modified_at = if let Some(last_password_modified_at) = self.0.last_password_modified_at { diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index 41ae12350fb..2ee9b389788 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -42,7 +42,7 @@ impl SPTFlow { Self::TOTP => Ok(true), // Main email APIs Self::AcceptInvitationFromEmail | Self::ResetPassword => Ok(true), - Self::VerifyEmail => Ok(!user.0.is_verified), + Self::VerifyEmail => Ok(true), // Final Checks Self::ForceSetPassword => user.is_password_rotate_required(state), Self::MerchantSelect => user @@ -154,17 +154,15 @@ const VERIFY_EMAIL_FLOW: [UserFlow; 5] = [ UserFlow::JWTFlow(JWTFlow::UserInfo), ]; -const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 5] = [ +const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 4] = [ UserFlow::SPTFlow(SPTFlow::TOTP), - UserFlow::SPTFlow(SPTFlow::VerifyEmail), UserFlow::SPTFlow(SPTFlow::AcceptInvitationFromEmail), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), UserFlow::JWTFlow(JWTFlow::UserInfo), ]; -const RESET_PASSWORD_FLOW: [UserFlow; 3] = [ +const RESET_PASSWORD_FLOW: [UserFlow; 2] = [ UserFlow::SPTFlow(SPTFlow::TOTP), - UserFlow::SPTFlow(SPTFlow::VerifyEmail), UserFlow::SPTFlow(SPTFlow::ResetPassword), ];
2024-06-12T12:43:23Z
## Description <!-- Describe your changes in detail --> Currently verify email API will be picked by the decision manager only if the user is not verified. But this API should be called always in case of verify email and magic link flow. This PR fixes 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). --> Closes #4970. ## 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/connect_account' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "user email" }' ``` You will receive a magic link to the email provided. Once the link in the email is used to login to dashboard, the link should not work anymore.
4651584ecc25e40a285b3544315901145d8c6b4b
``` curl --location 'http://localhost:8080/user/connect_account' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "user email" }' ``` You will receive a magic link to the email provided. Once the link in the email is used to login to dashboard, the link should not work anymore.
[ "crates/router/src/core/user.rs", "crates/router/src/types/domain/user.rs", "crates/router/src/types/domain/user/decision_manager.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4905
Bug: fix(opensearch): handle index not present errors in search api Currently in the self deployment mode we rely on fluentd to automatically create the index, in this case when we spin up the local setup the msearch API errors out since the index is not present, with the following json response ```json { "took": 17, "responses": [ { "took": 15, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 0, "relation": "eq" }, "max_score": null, "hits": [] }, "status": 200 }, { "took": 12, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 0, "relation": "eq" }, "max_score": null, "hits": [] }, "status": 200 }, { "error": { "root_cause": [ { "type": "index_not_found_exception", "reason": "no such index [hyperswitch-refund-events]", "index": "hyperswitch-refund-events", "resource.id": "hyperswitch-refund-events", "resource.type": "index_or_alias", "index_uuid": "_na_" } ], "type": "index_not_found_exception", "reason": "no such index [hyperswitch-refund-events]", "index": "hyperswitch-refund-events", "resource.id": "hyperswitch-refund-events", "resource.type": "index_or_alias", "index_uuid": "_na_" }, "status": 404 }, { "error": { "root_cause": [ { "type": "index_not_found_exception", "reason": "no such index [hyperswitch-dispute-events]", "index": "hyperswitch-dispute-events", "resource.id": "hyperswitch-dispute-events", "resource.type": "index_or_alias", "index_uuid": "_na_" } ], "type": "index_not_found_exception", "reason": "no such index [hyperswitch-dispute-events]", "index": "hyperswitch-dispute-events", "resource.id": "hyperswitch-dispute-events", "resource.type": "index_or_alias", "index_uuid": "_na_" }, "status": 404 } ] } ``` In this case it would be better if we treat missing index as 0 hits and log the corresponding errors.
diff --git a/crates/analytics/docs/README.md b/crates/analytics/docs/README.md index b822edd810e..da9a3c79f1f 100644 --- a/crates/analytics/docs/README.md +++ b/crates/analytics/docs/README.md @@ -101,4 +101,18 @@ Here's an example of how to do this: [default.features] audit_trail=true system_metrics=true -``` \ No newline at end of file +global_search=true +``` + +## Viewing the data on OpenSearch Dashboard + +To view the data on the OpenSearch dashboard perform the following steps: + +- Go to the OpenSearch Dashboard home and click on `Stack Management` under the Management tab +- Select `Index Patterns` +- Click on `Create index pattern` +- Define an index pattern with the same name that matches your indices and click on `Next Step` +- Select a time field that will be used for time-based queries +- Save the index pattern + +Now, head on to the `Discover` tab, to select the newly created index pattern and query the data \ No newline at end of file diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs index 7b19ba0ed06..e8f87aaef2e 100644 --- a/crates/analytics/src/opensearch.rs +++ b/crates/analytics/src/opensearch.rs @@ -76,6 +76,8 @@ pub enum OpenSearchError { ResponseError, #[error("Opensearch query building error")] QueryBuildingError, + #[error("Opensearch deserialisation error")] + DeserialisationError, } impl ErrorSwitch<OpenSearchError> for QueryBuildingError { @@ -111,6 +113,12 @@ impl ErrorSwitch<ApiErrorResponse> for OpenSearchError { "Query building error", None, )), + Self::DeserialisationError => ApiErrorResponse::InternalServerError(ApiError::new( + "IR", + 0, + "Deserialisation error", + None, + )), } } } diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs index dc802ff6948..8810dc1e3a1 100644 --- a/crates/analytics/src/search.rs +++ b/crates/analytics/src/search.rs @@ -4,7 +4,7 @@ use api_models::analytics::search::{ }; use common_utils::errors::{CustomResult, ReportSwitchExt}; use error_stack::ResultExt; -use serde_json::Value; +use router_env::tracing; use strum::IntoEnumIterator; use crate::opensearch::{ @@ -22,27 +22,59 @@ pub async fn msearch_results( .add_filter_clause("merchant_id".to_string(), merchant_id.to_string()) .switch()?; - let response_body = client + let response_text: OpenMsearchOutput = client .execute(query_builder) .await .change_context(OpenSearchError::ConnectionError)? - .json::<OpenMsearchOutput<Value>>() + .text() .await - .change_context(OpenSearchError::ResponseError)?; + .change_context(OpenSearchError::ResponseError) + .and_then(|body: String| { + serde_json::from_str::<OpenMsearchOutput>(&body) + .change_context(OpenSearchError::DeserialisationError) + .attach_printable(body.clone()) + })?; + + let response_body: OpenMsearchOutput = response_text; Ok(response_body .responses .into_iter() .zip(SearchIndex::iter()) - .map(|(index_hit, index)| GetSearchResponse { - count: index_hit.hits.total.value, - index, - hits: index_hit - .hits - .hits - .into_iter() - .map(|hit| hit._source) - .collect(), + .map(|(index_hit, index)| match index_hit { + OpensearchOutput::Success(success) => { + if success.status == 200 { + GetSearchResponse { + count: success.hits.total.value, + index, + hits: success + .hits + .hits + .into_iter() + .map(|hit| hit.source) + .collect(), + } + } else { + tracing::error!("Unexpected status code: {}", success.status,); + GetSearchResponse { + count: 0, + index, + hits: Vec::new(), + } + } + } + OpensearchOutput::Error(error) => { + tracing::error!( + index = ?index, + error_response = ?error, + "Search error" + ); + GetSearchResponse { + count: 0, + index, + hits: Vec::new(), + } + } }) .collect()) } @@ -65,22 +97,54 @@ pub async fn search_results( .set_offset_n_count(search_req.offset, search_req.count) .switch()?; - let response_body = client + let response_text: OpensearchOutput = client .execute(query_builder) .await .change_context(OpenSearchError::ConnectionError)? - .json::<OpensearchOutput<Value>>() + .text() .await - .change_context(OpenSearchError::ResponseError)?; + .change_context(OpenSearchError::ResponseError) + .and_then(|body: String| { + serde_json::from_str::<OpensearchOutput>(&body) + .change_context(OpenSearchError::DeserialisationError) + .attach_printable(body.clone()) + })?; + + let response_body: OpensearchOutput = response_text; - Ok(GetSearchResponse { - count: response_body.hits.total.value, - index: req.index, - hits: response_body - .hits - .hits - .into_iter() - .map(|hit| hit._source) - .collect(), - }) + match response_body { + OpensearchOutput::Success(success) => { + if success.status == 200 { + Ok(GetSearchResponse { + count: success.hits.total.value, + index: req.index, + hits: success + .hits + .hits + .into_iter() + .map(|hit| hit.source) + .collect(), + }) + } else { + tracing::error!("Unexpected status code: {}", success.status); + Ok(GetSearchResponse { + count: 0, + index: req.index, + hits: Vec::new(), + }) + } + } + OpensearchOutput::Error(error) => { + tracing::error!( + index = ?req.index, + error_response = ?error, + "Search error" + ); + Ok(GetSearchResponse { + count: 0, + index: req.index, + hits: Vec::new(), + }) + } + } } diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs index 6f6a3f22812..c29bb0e9f71 100644 --- a/crates/api_models/src/analytics/search.rs +++ b/crates/api_models/src/analytics/search.rs @@ -48,19 +48,40 @@ pub struct GetSearchResponse { } #[derive(Debug, serde::Deserialize)] -pub struct OpenMsearchOutput<T> { - pub responses: Vec<OpensearchOutput<T>>, +pub struct OpenMsearchOutput { + pub responses: Vec<OpensearchOutput>, } #[derive(Debug, serde::Deserialize)] -pub struct OpensearchOutput<T> { - pub hits: OpensearchResults<T>, +#[serde(untagged)] +pub enum OpensearchOutput { + Success(OpensearchSuccess), + Error(OpensearchError), } #[derive(Debug, serde::Deserialize)] -pub struct OpensearchResults<T> { +pub struct OpensearchError { + pub error: OpensearchErrorDetails, + pub status: u16, +} + +#[derive(Debug, serde::Deserialize)] +pub struct OpensearchErrorDetails { + #[serde(rename = "type")] + pub error_type: String, + pub reason: String, +} + +#[derive(Debug, serde::Deserialize)] +pub struct OpensearchSuccess { + pub status: u16, + pub hits: OpensearchHits, +} + +#[derive(Debug, serde::Deserialize)] +pub struct OpensearchHits { pub total: OpensearchResultsTotal, - pub hits: Vec<OpensearchHits<T>>, + pub hits: Vec<OpensearchHit>, } #[derive(Debug, serde::Deserialize)] @@ -69,6 +90,7 @@ pub struct OpensearchResultsTotal { } #[derive(Debug, serde::Deserialize)] -pub struct OpensearchHits<T> { - pub _source: T, +pub struct OpensearchHit { + #[serde(rename = "_source")] + pub source: Value, }
2024-06-12T10:13:57Z
## Description <!-- Describe your changes in detail --> - Handled errors when index is not present, by logging the corresponding error message and treating the hits as 0. - Changed the structure of `OpensearchOutput` and corresponding structs which are used to handle the error. ### 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 msearch API errors out since the index is not present, so handled the error. ## 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)? --> - Set up the global search locally - Test the global search with any keyword - Go through the log, and `5xx errors` should not be present anymore, with the errors logged, and handling of the index not found errors. ![image](https://github.com/juspay/hyperswitch/assets/83278309/5c7334b3-a9a8-4db8-9d31-447364c2ff0c)
a7ad7906d7e84fa59df3cfffd16dea8db300e675
- Set up the global search locally - Test the global search with any keyword - Go through the log, and `5xx errors` should not be present anymore, with the errors logged, and handling of the index not found errors. ![image](https://github.com/juspay/hyperswitch/assets/83278309/5c7334b3-a9a8-4db8-9d31-447364c2ff0c)
[ "crates/analytics/docs/README.md", "crates/analytics/src/opensearch.rs", "crates/analytics/src/search.rs", "crates/api_models/src/analytics/search.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4957
Bug: [BUG] Fix typo in `integration_test.toml` `krungsri_bank` it is.
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 738edcbda84..5abbc870fd0 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -9,7 +9,7 @@ online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,pla 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" online_banking_poland.adyen.banks = "blik_psp,place_zipko,m_bank,pay_with_ing,santander_przelew24,bank_pekaosa,bank_millennium,pay_with_alior_bank,banki_spoldzielcze,pay_with_inteligo,bnp_paribas_poland,bank_nowy_sa,credit_agricole,pay_with_bos,pay_with_citi_handlowy,pay_with_plus_bank,toyota_bank,velo_bank,e_transfer_pocztowy24" online_banking_slovakia.adyen.banks = "e_platby_vub,postova_banka,sporo_pay,tatra_pay,viamo" -online_banking_thailand.adyen.banks = "bangkok_bank,krungsrgiri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" +online_banking_thailand.adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" open_banking_uk.adyen.banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,halifax,lloyds,monzo,nat_west,nationwide_bank,royal_bank_of_scotland,starling,tsb_bank,tesco_bank,ulster_bank,barclays,hsbc_bank,revolut,santander_przelew24,open_bank_success,open_bank_failure,open_bank_cancelled" przelewy24.stripe.banks = "alior_bank,bank_millennium,bank_nowy_bfg_sa,bank_pekao_sa,banki_spbdzielcze,blik,bnp_paribas,boz,citi,credit_agricole,e_transfer_pocztowy24,getin_bank,idea_bank,inteligo,mbank_mtransfer,nest_przelew,noble_pay,pbac_z_ipko,plus_bank,santander_przelew24,toyota_bank,volkswagen_bank" @@ -143,8 +143,8 @@ bank_redirect.sofort.connector_list = "stripe,adyen,globalpay" # Mandate suppor bank_redirect.giropay.connector_list = "adyen,globalpay,multisafepay" # Mandate supported payment method type and connector for bank_redirect [mandates.update_mandate_supported] -card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card -card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card +card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card +card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card [network_transaction_id_supported_connectors] connector_list = "stripe,adyen,cybersource"
2024-06-12T05:27:16Z
## Description <!-- Describe your changes in detail --> This PR reverts typo introduced in https://github.com/juspay/hyperswitch/pull/4398 in `integration_test.toml` that resulted in deployments to fail. Resolves #4957 ### 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/deployments/integration_test.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). --> NIL ## 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)? --> Deployments should succeed.
5a81b50ae20760ce3c281719e0853c0f60f23734
Deployments should succeed.
[ "config/deployments/integration_test.toml" ]
juspay/hyperswitch
juspay__hyperswitch-5014
Bug: Updating the API reference documentation We have had feedback related to the API doc being outdated, and lacking proper visibility of the latest spec of the API collection.
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index b11037c2a43..e1ebb547f05 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -857,9 +857,11 @@ pub struct ToggleAllKVResponse { #[schema(example = true)] pub kv_enabled: bool, } + +/// Merchant connector details used to make payments. #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MerchantConnectorDetailsWrap { - /// Creds Identifier is to uniquely identify the credentials. Do not send any sensitive info in this field. And do not send the string "null". + /// Creds Identifier is to uniquely identify the credentials. Do not send any sensitive info, like encoded_data in this field. And do not send the string "null". pub creds_identifier: String, /// Merchant connector details type type. Base64 Encode the credentials and send it in this type and send as a string. #[schema(value_type = Option<MerchantConnectorDetails>, example = r#"{ diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 514e44337c1..1f2896700e9 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -572,6 +572,7 @@ mod test { } } +/// Denotes the retry action #[derive( Debug, serde::Deserialize, diff --git a/crates/api_models/src/ephemeral_key.rs b/crates/api_models/src/ephemeral_key.rs index 42f5a087767..d7ee7bd2517 100644 --- a/crates/api_models/src/ephemeral_key.rs +++ b/crates/api_models/src/ephemeral_key.rs @@ -2,6 +2,7 @@ use common_utils::id_type; use serde; use utoipa::ToSchema; +/// ephemeral_key for the customer_id mentioned #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, ToSchema)] pub struct EphemeralKeyCreateResponse { /// customer_id to which this ephemeral key belongs to diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs index 4adda0d9af4..f4089a16c22 100644 --- a/crates/api_models/src/mandates.rs +++ b/crates/api_models/src/mandates.rs @@ -114,6 +114,7 @@ pub struct MandateListConstraints { pub created_time_gte: Option<PrimitiveDateTime>, } +/// Details required for recurring payment #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum RecurringDetails { diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 2b06afc639f..08388f8db2d 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -179,6 +179,7 @@ mod client_secret_tests { } } +/// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. @@ -202,6 +203,7 @@ pub struct CustomerDetails { pub phone_country_code: Option<String>, } +/// Details of customer attached to this payment #[derive(Debug, Default, serde::Serialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The identifier for the customer. @@ -267,6 +269,7 @@ pub struct PaymentsRequest { /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825")] + #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<String>, #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ @@ -279,11 +282,9 @@ pub struct PaymentsRequest { #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, - /// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, - /// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, @@ -294,6 +295,7 @@ pub struct PaymentsRequest { /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable) @@ -342,16 +344,14 @@ pub struct PaymentsRequest { /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, - /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. + #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, - /// The payment method information provided for making a payment #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, - /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, @@ -361,6 +361,7 @@ pub struct PaymentsRequest { /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] + #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment @@ -391,7 +392,7 @@ pub struct PaymentsRequest { /// 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 + /// We will be Passing this "CustomerAcceptance" object during Payments-Confirm. The customer_acceptance sub object is usually passed by the SDK or client #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, @@ -418,7 +419,7 @@ pub struct PaymentsRequest { #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, - /// Payment Method Type + /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, @@ -434,7 +435,6 @@ pub struct PaymentsRequest { #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, - /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, @@ -448,23 +448,24 @@ pub struct PaymentsRequest { /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] + #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, - /// additional data related to some connectors + /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, - /// additional data that might be required by hyperswitch + /// Additional data that might be required by hyperswitch based on the requested features by the merchants. + #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to get the payment link (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, - /// custom payment link config for the particular payment #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, @@ -473,7 +474,6 @@ pub struct PaymentsRequest { #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub profile_id: Option<String>, - /// surcharge_details for this payment #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, @@ -490,7 +490,7 @@ pub struct PaymentsRequest { #[schema(example = 900)] pub session_expiry: Option<u32>, - /// additional data related to some frm connectors + /// additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, @@ -505,6 +505,7 @@ pub struct PaymentsRequest { pub charges: Option<PaymentChargeRequest>, } +/// Fee information to be charged on the payment being collected #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PaymentChargeRequest { @@ -530,6 +531,8 @@ impl PaymentsRequest { .map(|amount| MinorUnit::from(amount) + surcharge_amount) } } + +/// details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] @@ -905,6 +908,7 @@ impl Default for MandateType { } } +/// We will be Passing this "CustomerAcceptance" object during Payments-Confirm. The customer_acceptance sub object is usually passed by the SDK or client #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { @@ -1462,6 +1466,7 @@ mod payment_method_data_serde { } } +/// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { #[serde(flatten)] @@ -3037,7 +3042,7 @@ pub struct PaymentsCaptureRequest { /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. - #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] + #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } @@ -3290,7 +3295,18 @@ pub struct ReceiverDetails { amount_remaining: Option<i64>, } -#[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] +#[derive( + Setter, + Clone, + Default, + Debug, + PartialEq, + serde::Serialize, + ToSchema, + router_derive::PolymorphicSchema, +)] +#[generate_schemas(PaymentsCreateResponseOpenApi)] + pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. @@ -3306,7 +3322,6 @@ pub struct PaymentsResponse { #[schema(max_length = 255, example = "merchant_1668273825")] pub merchant_id: Option<String>, - /// The status of the current payment that was made #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, @@ -3323,7 +3338,7 @@ pub struct PaymentsResponse { #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: Option<MinorUnit>, - /// The amount which is already captured from the payment + /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = i64, example = 6540)] pub amount_received: Option<MinorUnit>, @@ -3355,14 +3370,13 @@ pub struct PaymentsResponse { )] pub customer_id: Option<id_type::CustomerId>, - /// Details of customer attached to this payment pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, - /// List of refund that happened on this intent + /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, @@ -3380,7 +3394,7 @@ pub struct PaymentsResponse { #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, - /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data + /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, @@ -3454,7 +3468,7 @@ pub struct PaymentsResponse { #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, - /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS + /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, @@ -3481,16 +3495,18 @@ pub struct PaymentsResponse { pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector + #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector + #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, - /// Payment Method Type + /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, @@ -3537,10 +3553,11 @@ pub struct PaymentsResponse { #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated - /// reference to the payment at connector side + /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, + /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment pub profile_id: Option<String>, @@ -3557,7 +3574,7 @@ pub struct PaymentsResponse { /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment pub merchant_connector_id: Option<String>, - /// If true incremental authorization can be performed on this payment + /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment @@ -3572,19 +3589,20 @@ pub struct PaymentsResponse { /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, - /// Date Time expiry of the payment + /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, - /// Payment Fingerprint + /// Payment Fingerprint, to identify a particular card. + /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, - /// Payment Method Id + /// Identifier for Payment Method pub payment_method_id: Option<String>, /// Payment Method Status @@ -3604,6 +3622,7 @@ pub struct PaymentsResponse { pub frm_metadata: Option<pii::SecretSerdeValue>, } +/// Fee information to be charged on the payment being collected #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentChargeResponse { /// Identifier for charge created for the payment @@ -3621,6 +3640,7 @@ pub struct PaymentChargeResponse { pub transfer_account_id: String, } +/// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless @@ -4227,6 +4247,7 @@ pub struct ApplepaySessionRequest { pub initiative_context: String, } +/// additional data related to some connectors #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, @@ -4633,7 +4654,7 @@ pub struct PaymentsCancelRequest { /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. - #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] + #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } @@ -4665,6 +4686,7 @@ pub struct PaymentsExternalAuthenticationRequest { pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } +/// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment @@ -4697,6 +4719,7 @@ pub enum ThreeDsCompletionIndicator { NotAvailable, } +/// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] @@ -4705,6 +4728,7 @@ pub enum DeviceChannel { Browser, } +/// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device @@ -4723,7 +4747,7 @@ pub struct SdkInformation { #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { - /// Indicates the trans status + /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, @@ -4731,13 +4755,13 @@ pub struct PaymentsExternalAuthenticationResponse { pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, - /// Unique identifier assigned by the EMVCo + /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, - /// Contains the JWS object created by the ACS for the ARes message + /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, @@ -4768,6 +4792,7 @@ pub struct PaymentsStartRequest { pub attempt_id: String, } +/// additional data that might be required by hyperswitch #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios @@ -4959,6 +4984,7 @@ mod tests { #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { + /// It's a token used for client side verification. pub client_secret: Option<String>, } @@ -4970,16 +4996,24 @@ pub struct PaymentLinkResponse { #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { + /// Identifier for Payment Link pub payment_link_id: String, + /// Identifier for Merchant pub merchant_id: String, + /// Payment Link pub link_to_pay: String, + /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, + /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, + /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, + /// Description for Payment Link pub description: Option<String>, + /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, @@ -5090,6 +5124,7 @@ pub struct PaymentLinkListResponse { pub data: Vec<PaymentLinkResponse>, } +/// custom payment link config for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] @@ -5111,6 +5146,7 @@ pub struct OrderDetailsWithStringAmount { pub product_img_link: Option<String>, } +/// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 5ee0bae6d61..2d64a61450d 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -19,6 +19,7 @@ pub mod diesel_exports { }; } +/// The status of the attempt #[derive( Clone, Copy, @@ -205,6 +206,7 @@ impl AttemptStatus { } } +/// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set #[derive( Clone, Copy, @@ -232,6 +234,7 @@ pub enum AuthenticationType { NoThreeDs, } +/// The status of the capture #[derive( Clone, Copy, @@ -308,6 +311,7 @@ pub enum BlocklistDataKind { ExtendedCardBin, } +/// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors #[derive( Clone, Copy, @@ -1164,6 +1168,7 @@ pub enum MerchantStorageScheme { RedisKv, } +/// The status of the current payment that was made #[derive( Clone, Copy, @@ -1197,6 +1202,7 @@ pub enum IntentStatus { PartiallyCapturedAndCapturable, } +/// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[derive( Clone, Copy, @@ -1251,6 +1257,7 @@ pub enum PaymentMethodIssuerCode { JpBacs, } +/// Payment Method Status #[derive( Clone, Copy, @@ -1603,6 +1610,7 @@ pub enum CardNetwork { Maestro, } +/// Stage of the dispute #[derive( Clone, Copy, @@ -1627,6 +1635,7 @@ pub enum DisputeStage { PreArbitration, } +/// Status of the dispute #[derive( Clone, Debug, @@ -2499,6 +2508,7 @@ pub enum RoleScope { Organization, } +/// Indicates the transaction status #[derive( Clone, Default, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index a259559c51d..3b37824be35 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -350,6 +350,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentsUpdateRequest, api_models::payments::PaymentsConfirmRequest, api_models::payments::PaymentsResponse, + api_models::payments::PaymentsCreateResponseOpenApi, api_models::payments::PaymentsStartRequest, api_models::payments::PaymentRetrieveBody, api_models::payments::PaymentsRetrieveRequest, diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs index a93be8828a2..66e6ce42962 100644 --- a/crates/openapi/src/routes/payments.rs +++ b/crates/openapi/src/routes/payments.rs @@ -191,7 +191,7 @@ ), ), responses( - (status = 200, description = "Payment created", body = PaymentsResponse), + (status = 200, description = "Payment created", body = PaymentsCreateResponseOpenApi), (status = 400, description = "Missing Mandatory fields") ), tag = "Payments", @@ -268,7 +268,7 @@ pub fn payments_retrieve() {} ) ), responses( - (status = 200, description = "Payment updated", body = PaymentsResponse), + (status = 200, description = "Payment updated", body = PaymentsCreateResponseOpenApi), (status = 400, description = "Missing mandatory fields") ), tag = "Payments", @@ -326,7 +326,7 @@ pub fn payments_update() {} ) ), responses( - (status = 200, description = "Payment confirmed", body = PaymentsResponse), + (status = 200, description = "Payment confirmed", body = PaymentsCreateResponseOpenApi), (status = 400, description = "Missing mandatory fields") ), tag = "Payments",
2024-06-11T19:46:00Z
## Description This is regarding the API Reference Doc changes using OpenAPI. This PR just the doc changes for Payments - Create (Including the Payments - 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). --> Partial resolution of #5014 ## 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)? -->
d2626fa3fe4216504fd0df216eea8462c87cce07
[ "crates/api_models/src/admin.rs", "crates/api_models/src/enums.rs", "crates/api_models/src/ephemeral_key.rs", "crates/api_models/src/mandates.rs", "crates/api_models/src/payments.rs", "crates/common_enums/src/enums.rs", "crates/openapi/src/openapi.rs", "crates/openapi/src/routes/payments.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4975
Bug: Include the pre-routing connectors in apple pay retries Currently for apple pay pre-routing is done before the session call and only one connector is decided based on the routing logic. Now since we want to enable auto retries for apple pay we need to consider all the connectors form the routing rule and construct a list of it. After which this connectors should be filtered out with the connectors that supports apple pay simplified flow. Once this is done there will be a list of connectors with which apple pay retries can we performed.
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 0641c842390..04983ed8b19 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2085,7 +2085,15 @@ pub async fn list_payment_methods( } if let Some(choice) = result.get(&intermediate.payment_method_type) { - intermediate.connector == choice.connector.connector_name.to_string() + if let Some(first_routable_connector) = choice.first() { + intermediate.connector + == first_routable_connector + .connector + .connector_name + .to_string() + } else { + false + } } else { false } @@ -2105,26 +2113,32 @@ pub async fn list_payment_methods( let mut pre_routing_results: HashMap< api_enums::PaymentMethodType, - routing_types::RoutableConnectorChoice, + storage::PreRoutingConnectorChoice, > = HashMap::new(); - for (pm_type, choice) in result { - let routable_choice = routing_types::RoutableConnectorChoice { - #[cfg(feature = "backwards_compatibility")] - choice_kind: routing_types::RoutableChoiceKind::FullStruct, - connector: choice - .connector - .connector_name - .to_string() - .parse::<api_enums::RoutableConnectors>() - .change_context(errors::ApiErrorResponse::InternalServerError)?, - #[cfg(feature = "connector_choice_mca_id")] - merchant_connector_id: choice.connector.merchant_connector_id, - #[cfg(not(feature = "connector_choice_mca_id"))] - sub_label: choice.sub_label, - }; - - pre_routing_results.insert(pm_type, routable_choice); + for (pm_type, routing_choice) in result { + let mut routable_choice_list = vec![]; + for choice in routing_choice { + let routable_choice = routing_types::RoutableConnectorChoice { + #[cfg(feature = "backwards_compatibility")] + choice_kind: routing_types::RoutableChoiceKind::FullStruct, + connector: choice + .connector + .connector_name + .to_string() + .parse::<api_enums::RoutableConnectors>() + .change_context(errors::ApiErrorResponse::InternalServerError)?, + #[cfg(feature = "connector_choice_mca_id")] + merchant_connector_id: choice.connector.merchant_connector_id.clone(), + #[cfg(not(feature = "connector_choice_mca_id"))] + sub_label: choice.sub_label, + }; + routable_choice_list.push(routable_choice); + } + pre_routing_results.insert( + pm_type, + storage::PreRoutingConnectorChoice::Multiple(routable_choice_list), + ); } let redis_conn = db @@ -2135,15 +2149,28 @@ pub async fn list_payment_methods( let mut val = Vec::new(); for (payment_method_type, routable_connector_choice) in &pre_routing_results { + let routable_connector_list = match routable_connector_choice { + storage::PreRoutingConnectorChoice::Single(routable_connector) => { + vec![routable_connector.clone()] + } + storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => { + routable_connector_list.clone() + } + }; + + let first_routable_connector = routable_connector_list + .first() + .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; + #[cfg(not(feature = "connector_choice_mca_id"))] let connector_label = get_connector_label( payment_intent.business_country, payment_intent.business_label.as_ref(), #[cfg(not(feature = "connector_choice_mca_id"))] - routable_connector_choice.sub_label.as_ref(), + first_routable_connector.sub_label.as_ref(), #[cfg(feature = "connector_choice_mca_id")] None, - routable_connector_choice.connector.to_string().as_str(), + first_routable_connector.connector.to_string().as_str(), ); #[cfg(not(feature = "connector_choice_mca_id"))] let matched_mca = filtered_mcas @@ -2152,7 +2179,7 @@ pub async fn list_payment_methods( #[cfg(feature = "connector_choice_mca_id")] let matched_mca = filtered_mcas.iter().find(|m| { - routable_connector_choice.merchant_connector_id.as_ref() + first_routable_connector.merchant_connector_id.as_ref() == Some(&m.merchant_connector_id) }); diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index e1290637dbe..50eedcfb568 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3182,32 +3182,51 @@ where .as_ref() .zip(payment_data.payment_attempt.payment_method_type.as_ref()) { - if let (Some(choice), None) = ( + if let (Some(routable_connector_choice), None) = ( pre_routing_results.get(storage_pm_type), &payment_data.token_data, ) { - let connector_data = api::ConnectorData::get_connector_by_name( - &state.conf.connectors, - &choice.connector.to_string(), - api::GetToken::Connector, - #[cfg(feature = "connector_choice_mca_id")] - choice.merchant_connector_id.clone(), - #[cfg(not(feature = "connector_choice_mca_id"))] - None, - ) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Invalid connector name received")?; + let routable_connector_list = match routable_connector_choice { + storage::PreRoutingConnectorChoice::Single(routable_connector) => { + vec![routable_connector.clone()] + } + storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => { + routable_connector_list.clone() + } + }; + + let mut pre_routing_connector_data_list = vec![]; + + let first_routable_connector = routable_connector_list + .first() + .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; - routing_data.routed_through = Some(choice.connector.to_string()); + routing_data.routed_through = Some(first_routable_connector.connector.to_string()); #[cfg(feature = "connector_choice_mca_id")] { routing_data .merchant_connector_id - .clone_from(&choice.merchant_connector_id); + .clone_from(&first_routable_connector.merchant_connector_id); } #[cfg(not(feature = "connector_choice_mca_id"))] { - routing_data.business_sub_label = choice.sub_label.clone(); + routing_data.business_sub_label = first_routable_connector.sub_label.clone(); + } + + for connector_choice in routable_connector_list.clone() { + let connector_data = api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &connector_choice.connector.to_string(), + api::GetToken::Connector, + #[cfg(feature = "connector_choice_mca_id")] + connector_choice.merchant_connector_id.clone(), + #[cfg(not(feature = "connector_choice_mca_id"))] + None, + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received")?; + + pre_routing_connector_data_list.push(connector_data); } #[cfg(all(feature = "retry", feature = "connector_choice_mca_id"))] @@ -3224,8 +3243,11 @@ where merchant_account, payment_data, key_store, - connector_data.clone(), - choice.merchant_connector_id.clone().as_ref(), + &pre_routing_connector_data_list, + first_routable_connector + .merchant_connector_id + .clone() + .as_ref(), ) .await?; @@ -3237,7 +3259,13 @@ where } } - return Ok(ConnectorCallType::PreDetermined(connector_data)); + let first_pre_routing_connector_data_list = pre_routing_connector_data_list + .first() + .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; + + return Ok(ConnectorCallType::PreDetermined( + first_pre_routing_connector_data_list.clone(), + )); } } @@ -3614,11 +3642,22 @@ where })); let mut final_list: Vec<api::SessionConnectorData> = Vec::new(); - for (routed_pm_type, choice) in pre_routing_results.into_iter() { - if let Some(session_connector_data) = - payment_methods.remove(&(choice.to_string(), routed_pm_type)) - { - final_list.push(session_connector_data); + for (routed_pm_type, pre_routing_choice) in pre_routing_results.into_iter() { + let routable_connector_list = match pre_routing_choice { + storage::PreRoutingConnectorChoice::Single(routable_connector) => { + vec![routable_connector.clone()] + } + storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => { + routable_connector_list.clone() + } + }; + for routable_connector in routable_connector_list { + if let Some(session_connector_data) = + payment_methods.remove(&(routable_connector.to_string(), routed_pm_type)) + { + final_list.push(session_connector_data); + break; + } } } @@ -3666,8 +3705,11 @@ where if !routing_enabled_pms.contains(&connector_data.payment_method_type) { final_list.push(connector_data); } else if let Some(choice) = result.get(&connector_data.payment_method_type) { - if connector_data.connector.connector_name == choice.connector.connector_name { - connector_data.business_sub_label = choice.sub_label.clone(); + let routing_choice = choice + .first() + .ok_or(errors::ApiErrorResponse::InternalServerError)?; + if connector_data.connector.connector_name == routing_choice.connector.connector_name { + connector_data.business_sub_label = routing_choice.sub_label.clone(); final_list.push(connector_data); } } @@ -3678,7 +3720,10 @@ where if !routing_enabled_pms.contains(&connector_data.payment_method_type) { final_list.push(connector_data); } else if let Some(choice) = result.get(&connector_data.payment_method_type) { - if connector_data.connector.connector_name == choice.connector.connector_name { + let routing_choice = choice + .first() + .ok_or(errors::ApiErrorResponse::InternalServerError)?; + if connector_data.connector.connector_name == routing_choice.connector.connector_name { final_list.push(connector_data); } } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index c94c1c714c7..a3751465b2c 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -4022,7 +4022,7 @@ pub async fn get_apple_pay_retryable_connectors<F>( merchant_account: &domain::MerchantAccount, payment_data: &mut PaymentData<F>, key_store: &domain::MerchantKeyStore, - decided_connector_data: api::ConnectorData, + pre_routing_connector_data_list: &[api::ConnectorData], merchant_connector_id: Option<&String>, ) -> CustomResult<Option<Vec<api::ConnectorData>>, errors::ApiErrorResponse> where @@ -4037,13 +4037,17 @@ where field_name: "profile_id", })?; + let pre_decided_connector_data_first = pre_routing_connector_data_list + .first() + .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; + let merchant_connector_account_type = get_merchant_connector_account( &state, merchant_account.merchant_id.as_str(), payment_data.creds_identifier.to_owned(), key_store, profile_id, - &decided_connector_data.connector_name.to_string(), + &pre_decided_connector_data_first.connector_name.to_string(), merchant_connector_id, ) .await?; @@ -4070,7 +4074,7 @@ where Some(profile_id.to_string()), ); - let mut connector_data_list = vec![decided_connector_data.clone()]; + let mut connector_data_list = vec![pre_decided_connector_data_first.clone()]; for merchant_connector_account in profile_specific_merchant_connector_account_list { if is_apple_pay_simplified_flow( @@ -4107,16 +4111,31 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get merchant default fallback connectors config")?; + let mut routing_connector_data_list = Vec::new(); + + pre_routing_connector_data_list.iter().for_each(|pre_val| { + routing_connector_data_list.push(pre_val.merchant_connector_id.clone()) + }); + + fallback_connetors_list.iter().for_each(|fallback_val| { + routing_connector_data_list + .iter() + .all(|val| *val != fallback_val.merchant_connector_id) + .then(|| { + routing_connector_data_list.push(fallback_val.merchant_connector_id.clone()) + }); + }); + // connector_data_list is the list of connectors for which Apple Pay simplified flow is configured. - // This list is arranged in the same order as the merchant's default fallback connectors configuration. - let mut ordered_connector_data_list = vec![decided_connector_data.clone()]; - fallback_connetors_list + // This list is arranged in the same order as the merchant's connectors routingconfiguration. + + let mut ordered_connector_data_list = Vec::new(); + + routing_connector_data_list .iter() - .for_each(|fallback_connector| { + .for_each(|merchant_connector_id| { let connector_data = connector_data_list.iter().find(|connector_data| { - fallback_connector.merchant_connector_id == connector_data.merchant_connector_id - && fallback_connector.merchant_connector_id - != decided_connector_data.merchant_connector_id + *merchant_connector_id == connector_data.merchant_connector_id }); if let Some(connector_data_details) = connector_data { ordered_connector_data_list.push(connector_data_details.clone()); diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 4394637d99a..3afb933d467 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -855,7 +855,8 @@ pub async fn perform_eligibility_analysis_with_fallback<F: Clone>( pub async fn perform_session_flow_routing( session_input: SessionFlowRoutingInput<'_>, transaction_type: &api_enums::TransactionType, -) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, routing_types::SessionRoutingChoice>> { +) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>>> +{ let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> = FxHashMap::default(); @@ -962,8 +963,10 @@ pub async fn perform_session_flow_routing( ); } - let mut result: FxHashMap<api_enums::PaymentMethodType, routing_types::SessionRoutingChoice> = - FxHashMap::default(); + let mut result: FxHashMap< + api_enums::PaymentMethodType, + Vec<routing_types::SessionRoutingChoice>, + > = FxHashMap::default(); for (pm_type, allowed_connectors) in pm_type_map { let euclid_pmt: euclid_enums::PaymentMethodType = pm_type; @@ -985,20 +988,37 @@ pub async fn perform_session_flow_routing( ))] profile_id: session_input.payment_intent.profile_id.clone(), }; - let maybe_choice = - perform_session_routing_for_pm_type(session_pm_input, transaction_type).await?; - - // (connector, sub_label) - if let Some(data) = maybe_choice { - result.insert( - pm_type, - routing_types::SessionRoutingChoice { - connector: data.0, + let routable_connector_choice_option = + perform_session_routing_for_pm_type(&session_pm_input, transaction_type).await?; + + if let Some(routable_connector_choice) = routable_connector_choice_option { + let mut session_routing_choice: Vec<routing_types::SessionRoutingChoice> = Vec::new(); + + for selection in routable_connector_choice { + let connector_name = selection.connector.to_string(); + if let Some(get_token) = session_pm_input.allowed_connectors.get(&connector_name) { + let connector_data = api::ConnectorData::get_connector_by_name( + &session_pm_input.state.clone().conf.connectors, + &connector_name, + get_token.clone(), + #[cfg(feature = "connector_choice_mca_id")] + selection.merchant_connector_id, + #[cfg(not(feature = "connector_choice_mca_id"))] + None, + ) + .change_context(errors::RoutingError::InvalidConnectorName(connector_name))?; #[cfg(not(feature = "connector_choice_mca_id"))] - sub_label: data.1, - payment_method_type: pm_type, - }, - ); + let sub_label = selection.sub_label; + + session_routing_choice.push(routing_types::SessionRoutingChoice { + connector: connector_data, + #[cfg(not(feature = "connector_choice_mca_id"))] + sub_label: sub_label, + payment_method_type: pm_type, + }); + } + } + result.insert(pm_type, session_routing_choice); } } @@ -1006,9 +1026,9 @@ pub async fn perform_session_flow_routing( } async fn perform_session_routing_for_pm_type( - session_pm_input: SessionRoutingPmTypeInput<'_>, + session_pm_input: &SessionRoutingPmTypeInput<'_>, transaction_type: &api_enums::TransactionType, -) -> RoutingResult<Option<(api::ConnectorData, Option<String>)>> { +) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> { let merchant_id = &session_pm_input.key_store.merchant_id; let chosen_connectors = match session_pm_input.routing_algorithm { @@ -1091,7 +1111,7 @@ async fn perform_session_routing_for_pm_type( &session_pm_input.state.clone(), session_pm_input.key_store, fallback, - session_pm_input.backend_input, + session_pm_input.backend_input.clone(), None, #[cfg(feature = "business_profile_routing")] session_pm_input.profile_id.clone(), @@ -1100,32 +1120,11 @@ async fn perform_session_routing_for_pm_type( .await?; } - let mut final_choice: Option<(api::ConnectorData, Option<String>)> = None; - - for selection in final_selection { - let connector_name = selection.connector.to_string(); - if let Some(get_token) = session_pm_input.allowed_connectors.get(&connector_name) { - let connector_data = api::ConnectorData::get_connector_by_name( - &session_pm_input.state.clone().conf.connectors, - &connector_name, - get_token.clone(), - #[cfg(feature = "connector_choice_mca_id")] - selection.merchant_connector_id, - #[cfg(not(feature = "connector_choice_mca_id"))] - None, - ) - .change_context(errors::RoutingError::InvalidConnectorName(connector_name))?; - #[cfg(not(feature = "connector_choice_mca_id"))] - let sub_label = selection.sub_label; - #[cfg(feature = "connector_choice_mca_id")] - let sub_label = None; - - final_choice = Some((connector_data, sub_label)); - break; - } + if final_selection.is_empty() { + Ok(None) + } else { + Ok(Some(final_selection)) } - - Ok(final_choice) } pub fn make_dsl_input_for_surcharge( diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 77550bedabe..79c8b2ed2f0 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -81,14 +81,21 @@ pub struct RoutingData { pub struct PaymentRoutingInfo { pub algorithm: Option<routing::StraightThroughAlgorithm>, pub pre_routing_results: - Option<HashMap<api_models::enums::PaymentMethodType, routing::RoutableConnectorChoice>>, + Option<HashMap<api_models::enums::PaymentMethodType, PreRoutingConnectorChoice>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRoutingInfoInner { pub algorithm: Option<routing::StraightThroughAlgorithm>, pub pre_routing_results: - Option<HashMap<api_models::enums::PaymentMethodType, routing::RoutableConnectorChoice>>, + Option<HashMap<api_models::enums::PaymentMethodType, PreRoutingConnectorChoice>>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(untagged)] +pub enum PreRoutingConnectorChoice { + Single(routing::RoutableConnectorChoice), + Multiple(Vec<routing::RoutableConnectorChoice>), } #[derive(Debug, serde::Serialize, serde::Deserialize)]
2024-06-11T16:09:43Z
## Description <!-- Describe your changes in detail --> Currently for apple pay pre-routing is done before the session call and only one connector is decided based on the routing logic. Now since we want to enable auto retries for apple pay we need to consider all the connectors form the routing rule and construct a list of it. After which this connectors should be filtered out with the connectors that supports apple pay simplified flow. Once this is done there will be a list of connectors with which apple pay retries can we performed. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create merchant account -> Enable auto retries for the specific `merchant_id` ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "should_call_gsm_merchant_1718202727", "value": "true" }' ``` -> Set the maximum retry counts for the auto retries enabled `merchant_id` ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "max_auto_retries_enabled_merchant_1718202727", "value": "1" }' ``` -> Configure the error code and error message in the gsm ``` curl --location 'localhost:8080/gsm' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "connector": "stripe", "flow": "Authorize", "sub_flow": "sub_flow", "code": "No error code", "message": "No error message", "status": "Failure", "decision": "retry", "step_up_possible": false }' ``` -> Create merchant connector accounts (enable apple pay simplified if you wish to retry the failed apple pay payment with it) metadata for simplified flow ``` "apple_pay_combined": { "simplified": { "session_token_data": { "initiative_context": "sdk-test-app.netlify.app", "merchant_business_country": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` -> Configure the routing rules for the configured connectors ``` curl --location 'http://localhost:8080/routing' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_T4l0hzK8OqmFbaNYGWEVhC6d0RkxRKPCMyA3Fi0C94C7kweFZSErnTz5fNuw8sCn' \ --data '{ "name": "priority config", "description": "some desc", "algorithm": { "type": "priority", "data": [ { "connector": "stripe", "merchant_connector_id": "mca_eF7yV3fNcAZ2wmGlKORq" }, { "connector": "cybersource", "merchant_connector_id": "mca_YAgldl8pmWD7mlqKrPlj" }, { "connector": "adyen", "merchant_connector_id": "mca_rkYJzRw3mSpDnPr25huU" }, { "connector": "rapyd", "merchant_connector_id": "mca_Vjg1fbX8FKP2ywlU4kOq" } ] }, "profile_id": "pro_Rv8QaYCARaEOCglUGXpa" }' ``` <img width="1133" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0fc7248d-abcb-487f-b266-afa98b28b2d6"> -> Create a apple pay payment with confirm false ``` { "amount": 6500, "currency": "USD", "confirm": false, "amount_to_capture": 6500, "customer_id": "test_priority_routing", "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", "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" } } } ``` <img width="1001" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/5674379f-7f8a-4705-ace3-f36f1d761671"> -> List payment methods for merchant ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_uKquqDLCGBBzbXpsEKyy_secret_soCWAMLK8xCq7WZ42KQD' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_97bb28e2fc3b42099d802df96188f7ec' ``` <img width="1120" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9eac6d54-f99d-4b5a-bddb-3b1b8aecade2"> -> Confirm the payment with `payment_id` ``` curl --location 'http://localhost:8080/payments/pay_uKquqDLCGBBzbXpsEKyy/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_T4l0hzK8OqmFbaNYGWEVhC6d0RkxRKPCMyA3Fi0C94C7kweFZSErnTz5fNuw8sCn' \ --data '{ "payment_method": "wallet", "payment_method_type": "apple_pay", "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" }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSTBNRFV5TVRBM016TXlORm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlEa29VdTlwZ01JUHR2R0VEZi9tSXk3LzNjSTg2b3U5eTJaZkV6RkhuRFN0TUFvR0NDcUdTTTQ5QkFNQ0JFWXdSQUlnTWdkSG9rZHNWQndya3RYRzd1VmowMm9QVVNsQllaWGVPeXJyd3RsQk5MUUNJRDdzZnZPaThZcjVWNkVyNjFqU05sKzR3ZDhpR050YUxEdFRMZjNBQ0VhNkFBQUFBQUFBIiwiaGVhZGVyIjp7InB1YmxpY0tleUhhc2giOiJ4MnFmMTFaemRXbnFCZnc0U0NyOWxIYzZRc1JQOEp6Z2xrZnU5RTVkWUpnPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRmdzNldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } }' ``` <img width="1075" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9400e62e-7a9b-4f4b-b8af-cba74d61719e"> -> Retrieve the payment with the `payment_id`. ``` curl --location 'http://localhost:8080/payments/pay_uKquqDLCGBBzbXpsEKyy?expand_attempts=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_T4l0hzK8OqmFbaNYGWEVhC6d0RkxRKPCMyA3Fi0C94C7kweFZSErnTz5fNuw8sCn' ``` <img width="737" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/6b290982-7d4b-4e92-b21b-cd756c2d4f02"> In the above response we can see that apple payment got failed with stripe and it was auto retried with adyen based on the configured routing rule. -> The routing rule configured during test is as shown below <img width="1133" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/c7916e7f-f3f8-4529-b90c-aafc67de28a9"> -> Below is entry of the pre-routing in the payment attempt table "apple_pay": [{"connector": "stripe", "merchant_c onnector_id": "mca_eF7yV3fNcAZ2wmGlKORq"}, {"connector": "cybersource", "merchant_connector_id": "mca_YAgldl8pmWD7mlqKrPlj"}, {"connector": "adyen", "merchant_connector_id": "mca_rkYJzRw3mSpDnPr25huU"}, {"connector": "rapyd", "merchant_connector_id": "mca_Vjg1fbX8FKP2ywlU4kOq"}], -> The order of apple pay retryable connector as below. As per the routing rules the stripe comes in the first of the list followed by adyen, as apple pay simplified flow is configured only for stripe and adyen. ![image](https://github.com/juspay/hyperswitch/assets/83439957/220ebe4b-95f4-4dfa-ac9c-65202c399e96)
b847606d665388fba898425b31dd5f207f60a56e
-> Create merchant account -> Enable auto retries for the specific `merchant_id` ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "should_call_gsm_merchant_1718202727", "value": "true" }' ``` -> Set the maximum retry counts for the auto retries enabled `merchant_id` ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "max_auto_retries_enabled_merchant_1718202727", "value": "1" }' ``` -> Configure the error code and error message in the gsm ``` curl --location 'localhost:8080/gsm' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "connector": "stripe", "flow": "Authorize", "sub_flow": "sub_flow", "code": "No error code", "message": "No error message", "status": "Failure", "decision": "retry", "step_up_possible": false }' ``` -> Create merchant connector accounts (enable apple pay simplified if you wish to retry the failed apple pay payment with it) metadata for simplified flow ``` "apple_pay_combined": { "simplified": { "session_token_data": { "initiative_context": "sdk-test-app.netlify.app", "merchant_business_country": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` -> Configure the routing rules for the configured connectors ``` curl --location 'http://localhost:8080/routing' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_T4l0hzK8OqmFbaNYGWEVhC6d0RkxRKPCMyA3Fi0C94C7kweFZSErnTz5fNuw8sCn' \ --data '{ "name": "priority config", "description": "some desc", "algorithm": { "type": "priority", "data": [ { "connector": "stripe", "merchant_connector_id": "mca_eF7yV3fNcAZ2wmGlKORq" }, { "connector": "cybersource", "merchant_connector_id": "mca_YAgldl8pmWD7mlqKrPlj" }, { "connector": "adyen", "merchant_connector_id": "mca_rkYJzRw3mSpDnPr25huU" }, { "connector": "rapyd", "merchant_connector_id": "mca_Vjg1fbX8FKP2ywlU4kOq" } ] }, "profile_id": "pro_Rv8QaYCARaEOCglUGXpa" }' ``` <img width="1133" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0fc7248d-abcb-487f-b266-afa98b28b2d6"> -> Create a apple pay payment with confirm false ``` { "amount": 6500, "currency": "USD", "confirm": false, "amount_to_capture": 6500, "customer_id": "test_priority_routing", "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", "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" } } } ``` <img width="1001" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/5674379f-7f8a-4705-ace3-f36f1d761671"> -> List payment methods for merchant ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_uKquqDLCGBBzbXpsEKyy_secret_soCWAMLK8xCq7WZ42KQD' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_97bb28e2fc3b42099d802df96188f7ec' ``` <img width="1120" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9eac6d54-f99d-4b5a-bddb-3b1b8aecade2"> -> Confirm the payment with `payment_id` ``` curl --location 'http://localhost:8080/payments/pay_uKquqDLCGBBzbXpsEKyy/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_T4l0hzK8OqmFbaNYGWEVhC6d0RkxRKPCMyA3Fi0C94C7kweFZSErnTz5fNuw8sCn' \ --data '{ "payment_method": "wallet", "payment_method_type": "apple_pay", "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" }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSTBNRFV5TVRBM016TXlORm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlEa29VdTlwZ01JUHR2R0VEZi9tSXk3LzNjSTg2b3U5eTJaZkV6RkhuRFN0TUFvR0NDcUdTTTQ5QkFNQ0JFWXdSQUlnTWdkSG9rZHNWQndya3RYRzd1VmowMm9QVVNsQllaWGVPeXJyd3RsQk5MUUNJRDdzZnZPaThZcjVWNkVyNjFqU05sKzR3ZDhpR050YUxEdFRMZjNBQ0VhNkFBQUFBQUFBIiwiaGVhZGVyIjp7InB1YmxpY0tleUhhc2giOiJ4MnFmMTFaemRXbnFCZnc0U0NyOWxIYzZRc1JQOEp6Z2xrZnU5RTVkWUpnPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRmdzNldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } }' ``` <img width="1075" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9400e62e-7a9b-4f4b-b8af-cba74d61719e"> -> Retrieve the payment with the `payment_id`. ``` curl --location 'http://localhost:8080/payments/pay_uKquqDLCGBBzbXpsEKyy?expand_attempts=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_T4l0hzK8OqmFbaNYGWEVhC6d0RkxRKPCMyA3Fi0C94C7kweFZSErnTz5fNuw8sCn' ``` <img width="737" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/6b290982-7d4b-4e92-b21b-cd756c2d4f02"> In the above response we can see that apple payment got failed with stripe and it was auto retried with adyen based on the configured routing rule. -> The routing rule configured during test is as shown below <img width="1133" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/c7916e7f-f3f8-4529-b90c-aafc67de28a9"> -> Below is entry of the pre-routing in the payment attempt table "apple_pay": [{"connector": "stripe", "merchant_c onnector_id": "mca_eF7yV3fNcAZ2wmGlKORq"}, {"connector": "cybersource", "merchant_connector_id": "mca_YAgldl8pmWD7mlqKrPlj"}, {"connector": "adyen", "merchant_connector_id": "mca_rkYJzRw3mSpDnPr25huU"}, {"connector": "rapyd", "merchant_connector_id": "mca_Vjg1fbX8FKP2ywlU4kOq"}], -> The order of apple pay retryable connector as below. As per the routing rules the stripe comes in the first of the list followed by adyen, as apple pay simplified flow is configured only for stripe and adyen. ![image](https://github.com/juspay/hyperswitch/assets/83439957/220ebe4b-95f4-4dfa-ac9c-65202c399e96)
[ "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/helpers.rs", "crates/router/src/core/payments/routing.rs", "crates/router/src/types/storage.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4950
Bug: [FEATURE] [BOA/CYB] Make all BillTo fields optional ### Feature Description Make all BillTo fields optional for prod testing ### Possible Implementation Make all BillTo fields optional for prod testing ### 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/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 671cc40e05c..143c1a4c6fa 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -260,15 +260,15 @@ pub struct Amount { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BillTo { - first_name: Secret<String>, - last_name: Secret<String>, - address1: Secret<String>, - locality: Secret<String>, + first_name: Option<Secret<String>>, + last_name: Option<Secret<String>>, + address1: Option<Secret<String>>, + locality: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] administrative_area: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] postal_code: Option<Secret<String>>, - country: api_enums::CountryAlpha2, + country: Option<api_enums::CountryAlpha2>, email: pii::Email, } @@ -442,47 +442,77 @@ impl<F, T> } // for bankofamerica each item in Billing is mandatory +// fn build_bill_to( +// address_details: &payments::Address, +// email: pii::Email, +// ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { +// let address = address_details +// .address +// .as_ref() +// .ok_or_else(utils::missing_field_err("billing.address"))?; + +// let country = address.get_country()?.to_owned(); +// let first_name = address.get_first_name()?; + +// let (administrative_area, postal_code) = +// if country == api_enums::CountryAlpha2::US || country == api_enums::CountryAlpha2::CA { +// let mut state = address.to_state_code()?.peek().clone(); +// state.truncate(20); +// ( +// Some(Secret::from(state)), +// Some(address.get_zip()?.to_owned()), +// ) +// } else { +// let zip = address.zip.clone(); +// let mut_state = address.state.clone().map(|state| state.expose()); +// match mut_state { +// Some(mut state) => { +// state.truncate(20); +// (Some(Secret::from(state)), zip) +// } +// None => (None, zip), +// } +// }; +// Ok(BillTo { +// first_name: first_name.clone(), +// last_name: address.get_last_name().unwrap_or(first_name).clone(), +// address1: address.get_line1()?.to_owned(), +// locality: Secret::new(address.get_city()?.to_owned()), +// administrative_area, +// postal_code, +// country, +// email, +// }) +// } + fn build_bill_to( - address_details: &payments::Address, + address_details: Option<&payments::Address>, email: pii::Email, ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { - let address = address_details - .address - .as_ref() - .ok_or_else(utils::missing_field_err("billing.address"))?; - - let country = address.get_country()?.to_owned(); - let first_name = address.get_first_name()?; - - let (administrative_area, postal_code) = - if country == api_enums::CountryAlpha2::US || country == api_enums::CountryAlpha2::CA { - let mut state = address.to_state_code()?.peek().clone(); - state.truncate(20); - ( - Some(Secret::from(state)), - Some(address.get_zip()?.to_owned()), - ) - } else { - let zip = address.zip.clone(); - let mut_state = address.state.clone().map(|state| state.expose()); - match mut_state { - Some(mut state) => { - state.truncate(20); - (Some(Secret::from(state)), zip) - } - None => (None, zip), - } - }; - Ok(BillTo { - first_name: first_name.clone(), - last_name: address.get_last_name().unwrap_or(first_name).clone(), - address1: address.get_line1()?.to_owned(), - locality: Secret::new(address.get_city()?.to_owned()), - administrative_area, - postal_code, - country, - email, - }) + let default_address = BillTo { + first_name: None, + last_name: None, + address1: None, + locality: None, + administrative_area: None, + postal_code: None, + country: None, + email: email.clone(), + }; + Ok(address_details + .and_then(|addr| { + addr.address.as_ref().map(|addr| BillTo { + first_name: addr.first_name.clone(), + last_name: addr.last_name.clone(), + address1: addr.line1.clone(), + locality: addr.city.clone(), + administrative_area: addr.to_state_code_as_optional().ok().flatten(), + postal_code: addr.zip.clone(), + country: addr.country, + email, + }) + }) + .unwrap_or(default_address)) } impl From<CardIssuer> for String { @@ -876,7 +906,7 @@ impl ), ) -> Result<Self, Self::Error> { let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, bill_to)); let payment_information = PaymentInformation::try_from(&ccard)?; @@ -939,7 +969,7 @@ impl ), ) -> Result<Self, Self::Error> { let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let payment_information = PaymentInformation::try_from(&ccard)?; let processing_information = ProcessingInformation::try_from((item, None, None))?; @@ -976,7 +1006,7 @@ impl ), ) -> Result<Self, Self::Error> { let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let processing_information = ProcessingInformation::try_from(( item, @@ -1030,7 +1060,7 @@ impl ), ) -> Result<Self, Self::Error> { let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let payment_information = PaymentInformation::from(&google_pay_data); let processing_information = @@ -1081,8 +1111,10 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> }, None => { let email = item.router_data.request.get_email()?; - let bill_to = - build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to( + item.router_data.get_optional_billing(), + email, + )?; let order_information: OrderInformationWithBill = OrderInformationWithBill::from((item, Some(bill_to))); let processing_information = @@ -1897,7 +1929,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsPreProcessingRouterData>> .1 .to_string(); let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill { amount_details, bill_to: Some(bill_to), @@ -3098,7 +3130,7 @@ impl TryFrom<&types::SetupMandateRouterData> for OrderInformationWithBill { fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { let email = item.request.get_email()?; - let bill_to = build_bill_to(item.get_billing()?, email)?; + let bill_to = build_bill_to(item.get_optional_billing(), email)?; Ok(Self { amount_details: Amount { diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index edc5c0cac1d..346f66b5d2e 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -65,7 +65,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { let email = item.request.get_email()?; - let bill_to = build_bill_to(item.get_billing()?, email)?; + let bill_to = build_bill_to(item.get_optional_billing(), email)?; let order_information = OrderInformationWithBill { amount_details: Amount { @@ -478,15 +478,15 @@ impl From<PaymentSolution> for String { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BillTo { - first_name: Secret<String>, - last_name: Secret<String>, - address1: Secret<String>, - locality: String, + first_name: Option<Secret<String>>, + last_name: Option<Secret<String>>, + address1: Option<Secret<String>>, + locality: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] administrative_area: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] postal_code: Option<Secret<String>>, - country: api_enums::CountryAlpha2, + country: Option<api_enums::CountryAlpha2>, email: pii::Email, } @@ -862,47 +862,77 @@ impl } // for cybersource each item in Billing is mandatory +// fn build_bill_to( +// address_details: &payments::Address, +// email: pii::Email, +// ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { +// let address = address_details +// .address +// .as_ref() +// .ok_or_else(utils::missing_field_err("billing.address"))?; + +// let country = address.get_country()?.to_owned(); +// let first_name = address.get_first_name()?; + +// let (administrative_area, postal_code) = +// if country == api_enums::CountryAlpha2::US || country == api_enums::CountryAlpha2::CA { +// let mut state = address.to_state_code()?.peek().clone(); +// state.truncate(20); +// ( +// Some(Secret::from(state)), +// Some(address.get_zip()?.to_owned()), +// ) +// } else { +// let zip = address.zip.clone(); +// let mut_state = address.state.clone().map(|state| state.expose()); +// match mut_state { +// Some(mut state) => { +// state.truncate(20); +// (Some(Secret::from(state)), zip) +// } +// None => (None, zip), +// } +// }; +// Ok(BillTo { +// first_name: first_name.clone(), +// last_name: address.get_last_name().unwrap_or(first_name).clone(), +// address1: address.get_line1()?.to_owned(), +// locality: address.get_city()?.to_owned(), +// administrative_area, +// postal_code, +// country, +// email, +// }) +// } + fn build_bill_to( - address_details: &payments::Address, + address_details: Option<&payments::Address>, email: pii::Email, ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { - let address = address_details - .address - .as_ref() - .ok_or_else(utils::missing_field_err("billing.address"))?; - - let country = address.get_country()?.to_owned(); - let first_name = address.get_first_name()?; - - let (administrative_area, postal_code) = - if country == api_enums::CountryAlpha2::US || country == api_enums::CountryAlpha2::CA { - let mut state = address.to_state_code()?.peek().clone(); - state.truncate(20); - ( - Some(Secret::from(state)), - Some(address.get_zip()?.to_owned()), - ) - } else { - let zip = address.zip.clone(); - let mut_state = address.state.clone().map(|state| state.expose()); - match mut_state { - Some(mut state) => { - state.truncate(20); - (Some(Secret::from(state)), zip) - } - None => (None, zip), - } - }; - Ok(BillTo { - first_name: first_name.clone(), - last_name: address.get_last_name().unwrap_or(first_name).clone(), - address1: address.get_line1()?.to_owned(), - locality: address.get_city()?.to_owned(), - administrative_area, - postal_code, - country, - email, - }) + let default_address = BillTo { + first_name: None, + last_name: None, + address1: None, + locality: None, + administrative_area: None, + postal_code: None, + country: None, + email: email.clone(), + }; + Ok(address_details + .and_then(|addr| { + addr.address.as_ref().map(|addr| BillTo { + first_name: addr.first_name.clone(), + last_name: addr.last_name.clone(), + address1: addr.line1.clone(), + locality: addr.city.clone(), + administrative_area: addr.to_state_code_as_optional().ok().flatten(), + postal_code: addr.zip.clone(), + country: addr.country, + email, + }) + }) + .unwrap_or(default_address)) } impl ForeignFrom<Value> for Vec<MerchantDefinedInformation> { @@ -937,7 +967,7 @@ impl ), ) -> Result<Self, Self::Error> { let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let card_issuer = ccard.get_card_issuer(); @@ -1015,7 +1045,7 @@ impl ), ) -> Result<Self, Self::Error> { let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, bill_to)); let card_issuer = ccard.get_card_issuer(); @@ -1096,7 +1126,7 @@ impl ), ) -> Result<Self, Self::Error> { let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let processing_information = ProcessingInformation::try_from(( item, @@ -1163,7 +1193,7 @@ impl ), ) -> Result<Self, Self::Error> { let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let payment_information = @@ -1223,8 +1253,10 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> }, None => { let email = item.router_data.request.get_email()?; - let bill_to = - build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to( + item.router_data.get_optional_billing(), + email, + )?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let processing_information = @@ -2212,7 +2244,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsPreProcessingRouterData>> .1 .to_string(); let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill { amount_details, bill_to: Some(bill_to),
2024-06-11T11:59:38Z
## Description <!-- Describe your changes in detail --> Make billTo fields optional in connector BOA and Cybersource. This change is required for prod testing. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/4950 ## 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 should be done for BOA and Cybersource. Payments should work if billing address is passed and payments should be failed at connector if billing address is not passed. Failure Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_mF5ApaF7qylFyewcvRbsOVw9bhOUy2ufhC8MutbWQvLwNWWqX7CZGDPf5SnZ6KRE' \ --data-raw '{ "amount": 101, "currency": "USD", "confirm": true, "customer_id": "mearX", "email": "guest@deepanshu.com", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "Bernard Eugine", "card_cvc": "123" } } }' ``` Failure Response: ``` { "payment_id": "pay_7iL2BAQtdP07gisZ5lgy", "merchant_id": "merchant_1718024306", "status": "failed", "amount": 101, "net_amount": 101, "amount_capturable": 0, "amount_received": null, "connector": "bankofamerica", "client_secret": "pay_7iL2BAQtdP07gisZ5lgy_secret_aLewy2zRmIcXiVmgPRsZ", "created": "2024-06-11T12:11:53.042Z", "currency": "USD", "customer_id": "mearX", "customer": { "id": "mearX", "name": "John Doe", "email": "guest@deepanshu.com", "phone": "999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "Bernard Eugine", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_hlcvyB0Vp6vQJ2v4Uk5g", "shipping": null, "billing": null, "order_details": null, "email": "guest@deepanshu.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": "MISSING_FIELD", "error_message": "Declined - The request is missing one or more fields, detailed_error_information: orderInformation.billTo.locality : MISSING_FIELD, orderInformation.billTo.address1 : MISSING_FIELD, orderInformation.billTo.country : MISSING_FIELD", "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": "mearX", "created_at": 1718107912, "expires": 1718111512, "secret": "epk_8c55074dbcc94632811fe1bd02a06edb" }, "manual_retry_allowed": true, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_sjoiFN7MPB9SdG5Zr0iT", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_QxbSnL7xEEr3Wc2sODHD", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-11T12:26:53.041Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-06-11T12:11:54.679Z", "charges": null, "frm_metadata": null } ``` Success Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_mF5ApaF7qylFyewcvRbsOVw9bhOUy2ufhC8MutbWQvLwNWWqX7CZGDPf5SnZ6KRE' \ --data-raw '{ "amount": 101, "currency": "USD", "confirm": true, "customer_id": "mearX", "email": "guest@deepanshu.com", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "Bernard Eugine", "card_cvc": "123" } }, "billing": { "address": { "line1": "eqnkl", "city": "San Francisco", "state": "BC", "zip": "V2S 1A6", "country": "DE", "first_name": "John", "last_name": "Bond" } } }' ``` Success Response: ``` { "payment_id": "pay_kRyRpMuXP8jqDMCkwWcI", "merchant_id": "merchant_1718024306", "status": "succeeded", "amount": 101, "net_amount": 101, "amount_capturable": 0, "amount_received": 101, "connector": "bankofamerica", "client_secret": "pay_kRyRpMuXP8jqDMCkwWcI_secret_kC4PSvgrobptzODtJgEn", "created": "2024-06-11T12:12:55.139Z", "currency": "USD", "customer_id": "mearX", "customer": { "id": "mearX", "name": "John Doe", "email": "guest@deepanshu.com", "phone": "999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "Bernard Eugine", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": { "resultCode": "M", "resultCodeRaw": "M" }, "approval_code": "831000", "consumer_authentication_response": { "code": "2", "codeRaw": "2" }, "cavv": null, "eci": null, "eci_raw": null }, "authentication_data": { "retrieval_reference_number": "416312127150", "acs_transaction_id": null, "system_trace_audit_number": "127150" } }, "billing": null }, "payment_token": "token_JLkgC0o4OvAPM1lxzecO", "shipping": null, "billing": { "address": { "city": "San Francisco", "country": "DE", "line1": "eqnkl", "line2": null, "line3": null, "zip": "V2S 1A6", "state": "BC", "first_name": "John", "last_name": "Bond" }, "phone": null, "email": null }, "order_details": null, "email": "guest@deepanshu.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "mearX", "created_at": 1718107975, "expires": 1718111575, "secret": "epk_b51ed8a854734e3c96a4c702ce610921" }, "manual_retry_allowed": false, "connector_transaction_id": "7181079753616046504951", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_kRyRpMuXP8jqDMCkwWcI_1", "payment_link": null, "profile_id": "pro_sjoiFN7MPB9SdG5Zr0iT", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_QxbSnL7xEEr3Wc2sODHD", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-11T12:27:55.139Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-06-11T12:12:56.234Z", "charges": null, "frm_metadata": null } ```
b705757be37a9803b964ef94d04c664c0f1e102d
Testing should be done for BOA and Cybersource. Payments should work if billing address is passed and payments should be failed at connector if billing address is not passed. Failure Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_mF5ApaF7qylFyewcvRbsOVw9bhOUy2ufhC8MutbWQvLwNWWqX7CZGDPf5SnZ6KRE' \ --data-raw '{ "amount": 101, "currency": "USD", "confirm": true, "customer_id": "mearX", "email": "guest@deepanshu.com", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "Bernard Eugine", "card_cvc": "123" } } }' ``` Failure Response: ``` { "payment_id": "pay_7iL2BAQtdP07gisZ5lgy", "merchant_id": "merchant_1718024306", "status": "failed", "amount": 101, "net_amount": 101, "amount_capturable": 0, "amount_received": null, "connector": "bankofamerica", "client_secret": "pay_7iL2BAQtdP07gisZ5lgy_secret_aLewy2zRmIcXiVmgPRsZ", "created": "2024-06-11T12:11:53.042Z", "currency": "USD", "customer_id": "mearX", "customer": { "id": "mearX", "name": "John Doe", "email": "guest@deepanshu.com", "phone": "999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "Bernard Eugine", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_hlcvyB0Vp6vQJ2v4Uk5g", "shipping": null, "billing": null, "order_details": null, "email": "guest@deepanshu.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": "MISSING_FIELD", "error_message": "Declined - The request is missing one or more fields, detailed_error_information: orderInformation.billTo.locality : MISSING_FIELD, orderInformation.billTo.address1 : MISSING_FIELD, orderInformation.billTo.country : MISSING_FIELD", "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": "mearX", "created_at": 1718107912, "expires": 1718111512, "secret": "epk_8c55074dbcc94632811fe1bd02a06edb" }, "manual_retry_allowed": true, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_sjoiFN7MPB9SdG5Zr0iT", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_QxbSnL7xEEr3Wc2sODHD", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-11T12:26:53.041Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-06-11T12:11:54.679Z", "charges": null, "frm_metadata": null } ``` Success Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_mF5ApaF7qylFyewcvRbsOVw9bhOUy2ufhC8MutbWQvLwNWWqX7CZGDPf5SnZ6KRE' \ --data-raw '{ "amount": 101, "currency": "USD", "confirm": true, "customer_id": "mearX", "email": "guest@deepanshu.com", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "Bernard Eugine", "card_cvc": "123" } }, "billing": { "address": { "line1": "eqnkl", "city": "San Francisco", "state": "BC", "zip": "V2S 1A6", "country": "DE", "first_name": "John", "last_name": "Bond" } } }' ``` Success Response: ``` { "payment_id": "pay_kRyRpMuXP8jqDMCkwWcI", "merchant_id": "merchant_1718024306", "status": "succeeded", "amount": 101, "net_amount": 101, "amount_capturable": 0, "amount_received": 101, "connector": "bankofamerica", "client_secret": "pay_kRyRpMuXP8jqDMCkwWcI_secret_kC4PSvgrobptzODtJgEn", "created": "2024-06-11T12:12:55.139Z", "currency": "USD", "customer_id": "mearX", "customer": { "id": "mearX", "name": "John Doe", "email": "guest@deepanshu.com", "phone": "999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "Bernard Eugine", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": { "resultCode": "M", "resultCodeRaw": "M" }, "approval_code": "831000", "consumer_authentication_response": { "code": "2", "codeRaw": "2" }, "cavv": null, "eci": null, "eci_raw": null }, "authentication_data": { "retrieval_reference_number": "416312127150", "acs_transaction_id": null, "system_trace_audit_number": "127150" } }, "billing": null }, "payment_token": "token_JLkgC0o4OvAPM1lxzecO", "shipping": null, "billing": { "address": { "city": "San Francisco", "country": "DE", "line1": "eqnkl", "line2": null, "line3": null, "zip": "V2S 1A6", "state": "BC", "first_name": "John", "last_name": "Bond" }, "phone": null, "email": null }, "order_details": null, "email": "guest@deepanshu.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "mearX", "created_at": 1718107975, "expires": 1718111575, "secret": "epk_b51ed8a854734e3c96a4c702ce610921" }, "manual_retry_allowed": false, "connector_transaction_id": "7181079753616046504951", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_kRyRpMuXP8jqDMCkwWcI_1", "payment_link": null, "profile_id": "pro_sjoiFN7MPB9SdG5Zr0iT", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_QxbSnL7xEEr3Wc2sODHD", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-11T12:27:55.139Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-06-11T12:12:56.234Z", "charges": null, "frm_metadata": null } ```
[ "crates/router/src/connector/bankofamerica/transformers.rs", "crates/router/src/connector/cybersource/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4948
Bug: [REFACTOR] wrap the encryption and file storage interface client in appstate with `Arc` as opposed to `Box` Currently, the encryption interface and file storage interface client is wrapped with `Box`. These clients live in AppState. Since state is cloned for each api handler, wrap the clients in `Arc` so that the internal data doesn't gets cloned.
diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs index 311cee0cede..e64b5dbd4ad 100644 --- a/crates/drainer/src/settings.rs +++ b/crates/drainer/src/settings.rs @@ -31,7 +31,7 @@ pub struct CmdLineConf { #[derive(Clone)] pub struct AppState { pub conf: Arc<Settings<RawSecret>>, - pub encryption_client: Box<dyn EncryptionManagementInterface>, + pub encryption_client: Arc<dyn EncryptionManagementInterface>, } impl AppState { diff --git a/crates/external_services/src/file_storage.rs b/crates/external_services/src/file_storage.rs index fb419b6ec64..e551cfee2af 100644 --- a/crates/external_services/src/file_storage.rs +++ b/crates/external_services/src/file_storage.rs @@ -2,7 +2,10 @@ //! Module for managing file storage operations with support for multiple storage schemes. //! -use std::fmt::{Display, Formatter}; +use std::{ + fmt::{Display, Formatter}, + sync::Arc, +}; use common_utils::errors::CustomResult; @@ -39,11 +42,11 @@ impl FileStorageConfig { } /// Retrieves the appropriate file storage client based on the file storage configuration. - pub async fn get_file_storage_client(&self) -> Box<dyn FileStorageInterface> { + pub async fn get_file_storage_client(&self) -> Arc<dyn FileStorageInterface> { match self { #[cfg(feature = "aws_s3")] - Self::AwsS3 { aws_s3 } => Box::new(aws_s3::AwsFileStorageClient::new(aws_s3).await), - Self::FileSystem => Box::new(file_system::FileSystem), + Self::AwsS3 { aws_s3 } => Arc::new(aws_s3::AwsFileStorageClient::new(aws_s3).await), + Self::FileSystem => Arc::new(file_system::FileSystem), } } } diff --git a/crates/external_services/src/managers/encryption_management.rs b/crates/external_services/src/managers/encryption_management.rs index 4612190926c..678239c60b1 100644 --- a/crates/external_services/src/managers/encryption_management.rs +++ b/crates/external_services/src/managers/encryption_management.rs @@ -2,6 +2,8 @@ //! Encryption management util module //! +use std::sync::Arc; + use common_utils::errors::CustomResult; use hyperswitch_interfaces::encryption_interface::{ EncryptionError, EncryptionManagementInterface, @@ -42,12 +44,12 @@ impl EncryptionManagementConfig { /// Retrieves the appropriate encryption client based on the configuration. pub async fn get_encryption_management_client( &self, - ) -> CustomResult<Box<dyn EncryptionManagementInterface>, EncryptionError> { + ) -> CustomResult<Arc<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::AwsKms { aws_kms } => Arc::new(aws_kms::core::AwsKmsClient::new(aws_kms).await), - Self::NoEncryption => Box::new(NoEncryption), + Self::NoEncryption => Arc::new(NoEncryption), }) } } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 83d8c714e92..8d88d9c4b26 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -82,7 +82,7 @@ pub struct SessionState { pub email_client: Arc<dyn EmailService>, #[cfg(feature = "olap")] pub pool: AnalyticsProvider, - pub file_storage_client: Box<dyn FileStorageInterface>, + pub file_storage_client: Arc<dyn FileStorageInterface>, pub request_id: Option<RequestId>, pub base_url: String, pub tenant: String, @@ -144,8 +144,8 @@ pub struct AppState { #[cfg(feature = "olap")] pub opensearch_client: Arc<OpenSearchClient>, pub request_id: Option<RequestId>, - pub file_storage_client: Box<dyn FileStorageInterface>, - pub encryption_client: Box<dyn EncryptionManagementInterface>, + pub file_storage_client: Arc<dyn FileStorageInterface>, + pub encryption_client: Arc<dyn EncryptionManagementInterface>, } impl scheduler::SchedulerAppState for AppState { fn get_tenants(&self) -> Vec<String> {
2024-06-11T11:33:16Z
## Description <!-- Describe your changes in detail --> Currently, the encryption interface and file storage interface client is wrapped with `Box`. These clients live in `AppState`. Since state is cloned for each api handler, wrapping the clients in Arc will help in not cloning the actual internal data rather maintaining a counter on the single client instance. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Basic sanity testing should suffice
b705757be37a9803b964ef94d04c664c0f1e102d
Basic sanity testing should suffice
[ "crates/drainer/src/settings.rs", "crates/external_services/src/file_storage.rs", "crates/external_services/src/managers/encryption_management.rs", "crates/router/src/routes/app.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4945
Bug: [REFACTOR] Move trait ConnectorIntegration to crate hyperswitch_interfaces ### Feature Description The trait ConnectorIntegration needs to be moved to crate hyperswitch_interfaces from router. This is required to move connector code out from crate router. ### Possible Implementation The trait ConnectorIntegration along with it's dependent types needs to be moved to crate hyperswitch_interfaces. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index 77f9b33ddc4..6ea7937eca6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3695,11 +3695,22 @@ name = "hyperswitch_interfaces" version = "0.1.0" dependencies = [ "async-trait", + "bytes 1.6.0", "common_utils", "dyn-clone", + "http 0.2.12", + "hyperswitch_domain_models", "masking", + "mime", + "once_cell", + "reqwest", + "router_derive", + "router_env", "serde", + "serde_json", + "storage_impl", "thiserror", + "time", ] [[package]] diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.toml index 034e0a67d92..95b3b98af05 100644 --- a/crates/hyperswitch_interfaces/Cargo.toml +++ b/crates/hyperswitch_interfaces/Cargo.toml @@ -6,12 +6,28 @@ rust-version.workspace = true readme = "README.md" license.workspace = true +[features] +default = ["dummy_connector", "payouts"] +dummy_connector = [] +payouts = [] + [dependencies] async-trait = "0.1.79" +bytes = "1.6.0" dyn-clone = "1.0.17" +http = "0.2.12" +mime = "0.3.17" +once_cell = "1.19.0" +reqwest = "0.11.27" serde = { version = "1.0.197", features = ["derive"] } +serde_json = "1.0.115" thiserror = "1.0.58" +time = "0.3.35" # First party crates common_utils = { version = "0.1.0", path = "../common_utils" } +hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } masking = { version = "0.1.0", path = "../masking" } +router_derive = { version = "0.1.0", path = "../router_derive" } +router_env = { version = "0.1.0", path = "../router_env" } +storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false } diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs new file mode 100644 index 00000000000..63cbc6dabf8 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/api.rs @@ -0,0 +1,183 @@ +//! API interface + +use common_utils::{ + errors::CustomResult, + request::{Method, Request, RequestContent}, +}; +use hyperswitch_domain_models::router_data::{ErrorResponse, RouterData}; +use masking::Maskable; +use serde_json::json; + +use crate::{ + configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, metrics, types, +}; + +/// type BoxedConnectorIntegration +pub type BoxedConnectorIntegration<'a, T, Req, Resp> = + Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>; + +/// trait ConnectorIntegrationAny +pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static { + /// fn get_connector_integration + fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>; +} + +impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S +where + S: ConnectorIntegration<T, Req, Resp> + Send + Sync, +{ + fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> { + Box::new(self) + } +} + +/// trait ConnectorIntegration +pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> + Sync { + /// fn get_headers + fn get_headers( + &self, + _req: &RouterData<T, Req, Resp>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + Ok(vec![]) + } + + /// fn get_content_type + fn get_content_type(&self) -> &'static str { + mime::APPLICATION_JSON.essence_str() + } + + /// primarily used when creating signature based on request method of payment flow + fn get_http_method(&self) -> Method { + Method::Post + } + + /// fn get_url + fn get_url( + &self, + _req: &RouterData<T, Req, Resp>, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(String::new()) + } + + /// fn get_request_body + fn get_request_body( + &self, + _req: &RouterData<T, Req, Resp>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + Ok(RequestContent::Json(Box::new(json!(r#"{}"#)))) + } + + /// fn get_request_form_data + fn get_request_form_data( + &self, + _req: &RouterData<T, Req, Resp>, + ) -> CustomResult<Option<reqwest::multipart::Form>, errors::ConnectorError> { + Ok(None) + } + + /// fn build_request + fn build_request( + &self, + req: &RouterData<T, Req, Resp>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + metrics::UNIMPLEMENTED_FLOW.add( + &metrics::CONTEXT, + 1, + &[metrics::add_attributes("connector", req.connector.clone())], + ); + Ok(None) + } + + /// fn handle_response + fn handle_response( + &self, + data: &RouterData<T, Req, Resp>, + event_builder: Option<&mut ConnectorEvent>, + _res: types::Response, + ) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError> + where + T: Clone, + Req: Clone, + Resp: Clone, + { + event_builder.map(|e| e.set_error(json!({"error": "Not Implemented"}))); + Ok(data.clone()) + } + + /// fn get_error_response + fn get_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}))); + Ok(ErrorResponse::get_not_implemented()) + } + + /// fn get_5xx_error_response + 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", + 502 => "bad_gateway", + 503 => "service_unavailable", + 504 => "gateway_timeout", + 505 => "http_version_not_supported", + 506 => "variant_also_negotiates", + 507 => "insufficient_storage", + 508 => "loop_detected", + 510 => "not_extended", + 511 => "network_authentication_required", + _ => "unknown_error", + }; + Ok(ErrorResponse { + code: res.status_code.to_string(), + message: error_message.to_string(), + reason: String::from_utf8(res.response.to_vec()).ok(), + status_code: res.status_code, + attempt_status: None, + connector_transaction_id: None, + }) + } + + /// whenever capture sync is implemented at the connector side, this method should be overridden + fn get_multiple_capture_sync_method( + &self, + ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("multiple capture sync".into()).into()) + } + + /// fn get_certificate + fn get_certificate( + &self, + _req: &RouterData<T, Req, Resp>, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + Ok(None) + } + + /// fn get_certificate_key + fn get_certificate_key( + &self, + _req: &RouterData<T, Req, Resp>, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + Ok(None) + } +} + +/// Sync Methods for multiple captures +#[derive(Debug)] +pub enum CaptureSyncMethod { + /// For syncing multiple captures individually + Individual, + /// For syncing multiple captures together + Bulk, +} diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs new file mode 100644 index 00000000000..8f3b5600f08 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/configs.rs @@ -0,0 +1,132 @@ +//! Configs interface +use router_derive; +use serde::Deserialize; +use storage_impl::errors::ApplicationError; + +// struct Connectors +#[allow(missing_docs, missing_debug_implementations)] +#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] +#[serde(default)] +pub struct Connectors { + pub aci: ConnectorParams, + #[cfg(feature = "payouts")] + pub adyen: ConnectorParamsWithSecondaryBaseUrl, + pub adyenplatform: ConnectorParams, + #[cfg(not(feature = "payouts"))] + pub adyen: ConnectorParams, + pub airwallex: ConnectorParams, + pub applepay: ConnectorParams, + pub authorizedotnet: ConnectorParams, + pub bambora: ConnectorParams, + pub bankofamerica: ConnectorParams, + pub billwerk: ConnectorParams, + pub bitpay: ConnectorParams, + pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, + pub boku: ConnectorParams, + pub braintree: ConnectorParams, + pub cashtocode: ConnectorParams, + pub checkout: ConnectorParams, + pub coinbase: ConnectorParams, + pub cryptopay: ConnectorParams, + pub cybersource: ConnectorParams, + pub datatrans: ConnectorParams, + pub dlocal: ConnectorParams, + #[cfg(feature = "dummy_connector")] + pub dummyconnector: ConnectorParams, + pub ebanx: ConnectorParams, + pub fiserv: ConnectorParams, + pub forte: ConnectorParams, + pub globalpay: ConnectorParams, + pub globepay: ConnectorParams, + pub gocardless: ConnectorParams, + pub gpayments: ConnectorParams, + pub helcim: ConnectorParams, + pub iatapay: ConnectorParams, + pub klarna: ConnectorParams, + pub mifinity: ConnectorParams, + pub mollie: ConnectorParams, + pub multisafepay: ConnectorParams, + pub netcetera: ConnectorParams, + pub nexinets: ConnectorParams, + pub nmi: ConnectorParams, + pub noon: ConnectorParamsWithModeType, + pub nuvei: ConnectorParams, + pub opayo: ConnectorParams, + pub opennode: ConnectorParams, + pub payeezy: ConnectorParams, + pub payme: ConnectorParams, + pub payone: ConnectorParams, + pub paypal: ConnectorParams, + pub payu: ConnectorParams, + pub placetopay: ConnectorParams, + pub powertranz: ConnectorParams, + pub prophetpay: ConnectorParams, + pub rapyd: ConnectorParams, + pub riskified: ConnectorParams, + pub shift4: ConnectorParams, + pub signifyd: ConnectorParams, + pub square: ConnectorParams, + pub stax: ConnectorParams, + pub stripe: ConnectorParamsWithFileUploadUrl, + pub threedsecureio: ConnectorParams, + pub trustpay: ConnectorParamsWithMoreUrls, + pub tsys: ConnectorParams, + pub volt: ConnectorParams, + pub wise: ConnectorParams, + pub worldline: ConnectorParams, + pub worldpay: ConnectorParams, + pub zen: ConnectorParams, + pub zsl: ConnectorParams, +} + +/// struct ConnectorParams +#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] +#[serde(default)] +pub struct ConnectorParams { + /// base url + pub base_url: String, + /// secondary base url + pub secondary_base_url: Option<String>, +} + +/// struct ConnectorParamsWithModeType +#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] +#[serde(default)] +pub struct ConnectorParamsWithModeType { + /// base url + pub base_url: String, + /// secondary base url + pub secondary_base_url: Option<String>, + /// Can take values like Test or Live for Noon + pub key_mode: String, +} + +/// struct ConnectorParamsWithMoreUrls +#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] +#[serde(default)] +pub struct ConnectorParamsWithMoreUrls { + /// base url + pub base_url: String, + /// base url for bank redirects + pub base_url_bank_redirects: String, +} + +/// struct ConnectorParamsWithFileUploadUrl +#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] +#[serde(default)] +pub struct ConnectorParamsWithFileUploadUrl { + /// base url + pub base_url: String, + /// base url for file upload + pub base_url_file_upload: String, +} + +/// struct ConnectorParamsWithSecondaryBaseUrl +#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] +#[serde(default)] +pub struct ConnectorParamsWithSecondaryBaseUrl { + /// base url + pub base_url: String, + /// secondary base url + pub secondary_base_url: String, +} diff --git a/crates/hyperswitch_interfaces/src/errors.rs b/crates/hyperswitch_interfaces/src/errors.rs new file mode 100644 index 00000000000..e36707af6b0 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/errors.rs @@ -0,0 +1,149 @@ +//! Errors interface + +use common_utils::errors::ErrorSwitch; +use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse; + +/// Connector Errors +#[allow(missing_docs, missing_debug_implementations)] +#[derive(Debug, thiserror::Error, PartialEq)] +pub enum ConnectorError { + #[error("Error while obtaining URL for the integration")] + FailedToObtainIntegrationUrl, + #[error("Failed to encode connector request")] + RequestEncodingFailed, + #[error("Request encoding failed : {0}")] + RequestEncodingFailedWithReason(String), + #[error("Parsing failed")] + ParsingFailed, + #[error("Failed to deserialize connector response")] + ResponseDeserializationFailed, + #[error("Failed to execute a processing step: {0:?}")] + ProcessingStepFailed(Option<bytes::Bytes>), + #[error("The connector returned an unexpected response: {0:?}")] + UnexpectedResponseError(bytes::Bytes), + #[error("Failed to parse custom routing rules from merchant account")] + RoutingRulesParsingError, + #[error("Failed to obtain preferred connector from merchant account")] + FailedToObtainPreferredConnector, + #[error("An invalid connector name was provided")] + InvalidConnectorName, + #[error("An invalid Wallet was used")] + InvalidWallet, + #[error("Failed to handle connector response")] + ResponseHandlingFailed, + #[error("Missing required field: {field_name}")] + MissingRequiredField { field_name: &'static str }, + #[error("Missing required fields: {field_names:?}")] + MissingRequiredFields { field_names: Vec<&'static str> }, + #[error("Failed to obtain authentication type")] + FailedToObtainAuthType, + #[error("Failed to obtain certificate")] + FailedToObtainCertificate, + #[error("Connector meta data not found")] + NoConnectorMetaData, + #[error("Failed to obtain certificate key")] + FailedToObtainCertificateKey, + #[error("This step has not been implemented for: {0}")] + NotImplemented(String), + #[error("{message} is not supported by {connector}")] + NotSupported { + message: String, + connector: &'static str, + }, + #[error("{flow} flow not supported by {connector} connector")] + FlowNotSupported { flow: String, connector: String }, + #[error("Capture method not supported")] + CaptureMethodNotSupported, + #[error("Missing connector mandate ID")] + MissingConnectorMandateID, + #[error("Missing connector transaction ID")] + MissingConnectorTransactionID, + #[error("Missing connector refund ID")] + MissingConnectorRefundID, + #[error("Missing apple pay tokenization data")] + MissingApplePayTokenData, + #[error("Webhooks not implemented for this connector")] + WebhooksNotImplemented, + #[error("Failed to decode webhook event body")] + WebhookBodyDecodingFailed, + #[error("Signature not found for incoming webhook")] + WebhookSignatureNotFound, + #[error("Failed to verify webhook source")] + WebhookSourceVerificationFailed, + #[error("Could not find merchant secret in DB for incoming webhook source verification")] + WebhookVerificationSecretNotFound, + #[error("Merchant secret found for incoming webhook source verification is invalid")] + WebhookVerificationSecretInvalid, + #[error("Incoming webhook object reference ID not found")] + WebhookReferenceIdNotFound, + #[error("Incoming webhook event type not found")] + WebhookEventTypeNotFound, + #[error("Incoming webhook event resource object not found")] + WebhookResourceObjectNotFound, + #[error("Could not respond to the incoming webhook event")] + WebhookResponseEncodingFailed, + #[error("Invalid Date/time format")] + InvalidDateFormat, + #[error("Date Formatting Failed")] + DateFormattingFailed, + #[error("Invalid Data format")] + InvalidDataFormat { field_name: &'static str }, + #[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")] + MismatchedPaymentData, + #[error("Failed to parse {wallet_name} wallet token")] + InvalidWalletToken { wallet_name: String }, + #[error("Missing Connector Related Transaction ID")] + MissingConnectorRelatedTransactionID { id: String }, + #[error("File Validation failed")] + FileValidationFailed { reason: String }, + #[error("Missing 3DS redirection payload: {field_name}")] + MissingConnectorRedirectionPayload { field_name: &'static str }, + #[error("Failed at connector's end with code '{code}'")] + FailedAtConnector { message: String, code: String }, + #[error("Payment Method Type not found")] + MissingPaymentMethodType, + #[error("Balance in the payment method is low")] + InSufficientBalanceInPaymentMethod, + #[error("Server responded with Request Timeout")] + RequestTimeoutReceived, + #[error("The given currency method is not configured with the given connector")] + CurrencyNotSupported { + message: String, + connector: &'static str, + }, + #[error("Invalid Configuration")] + InvalidConnectorConfig { config: &'static str }, + #[error("Failed to convert amount to required type")] + AmountConversionFailed, +} + +impl ConnectorError { + /// fn is_connector_timeout + pub fn is_connector_timeout(&self) -> bool { + self == &Self::RequestTimeoutReceived + } +} + +impl ErrorSwitch<ConnectorError> for common_utils::errors::ParsingError { + fn switch(&self) -> ConnectorError { + ConnectorError::ParsingFailed + } +} + +impl ErrorSwitch<ApiErrorResponse> for ConnectorError { + fn switch(&self) -> ApiErrorResponse { + match self { + Self::WebhookSourceVerificationFailed => ApiErrorResponse::WebhookAuthenticationFailed, + Self::WebhookSignatureNotFound + | Self::WebhookReferenceIdNotFound + | Self::WebhookResourceObjectNotFound + | Self::WebhookBodyDecodingFailed + | Self::WebhooksNotImplemented => ApiErrorResponse::WebhookBadRequest, + Self::WebhookEventTypeNotFound => ApiErrorResponse::WebhookUnprocessableEntity, + Self::WebhookVerificationSecretInvalid => { + ApiErrorResponse::WebhookInvalidMerchantSecret + } + _ => ApiErrorResponse::InternalServerError, + } + } +} diff --git a/crates/hyperswitch_interfaces/src/events.rs b/crates/hyperswitch_interfaces/src/events.rs new file mode 100644 index 00000000000..3dcb7519545 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/events.rs @@ -0,0 +1,3 @@ +//! Events interface + +pub mod connector_api_logs; diff --git a/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs b/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs new file mode 100644 index 00000000000..79b172e9ea7 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs @@ -0,0 +1,96 @@ +//! Connector API logs interface + +use common_utils::request::Method; +use router_env::tracing_actix_web::RequestId; +use serde::Serialize; +use serde_json::json; +use time::OffsetDateTime; + +/// struct ConnectorEvent +#[derive(Debug, Serialize)] +pub struct ConnectorEvent { + connector_name: String, + flow: String, + request: String, + masked_response: Option<String>, + error: Option<String>, + url: String, + method: String, + payment_id: String, + merchant_id: String, + created_at: i128, + /// Connector Event Request ID + pub request_id: String, + latency: u128, + refund_id: Option<String>, + dispute_id: Option<String>, + status_code: u16, +} + +impl ConnectorEvent { + /// fn new ConnectorEvent + #[allow(clippy::too_many_arguments)] + pub fn new( + connector_name: String, + flow: &str, + request: serde_json::Value, + url: String, + method: Method, + payment_id: String, + merchant_id: String, + request_id: Option<&RequestId>, + latency: u128, + refund_id: Option<String>, + dispute_id: Option<String>, + status_code: u16, + ) -> Self { + Self { + connector_name, + flow: flow + .rsplit_once("::") + .map(|(_, s)| s) + .unwrap_or(flow) + .to_string(), + request: request.to_string(), + masked_response: None, + error: None, + url, + method: method.to_string(), + payment_id, + merchant_id, + created_at: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000, + request_id: request_id + .map(|i| i.as_hyphenated().to_string()) + .unwrap_or("NO_REQUEST_ID".to_string()), + latency, + refund_id, + dispute_id, + status_code, + } + } + + /// fn set_response_body + 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()})), + } + } + + /// fn set_error_response_body + 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()})), + } + } + + /// fn set_error + pub fn set_error(&mut self, error: serde_json::Value) { + self.error = Some(error.to_string()); + } +} diff --git a/crates/hyperswitch_interfaces/src/lib.rs b/crates/hyperswitch_interfaces/src/lib.rs index 3f7b8d41c3e..7d3b319df83 100644 --- a/crates/hyperswitch_interfaces/src/lib.rs +++ b/crates/hyperswitch_interfaces/src/lib.rs @@ -1,7 +1,11 @@ //! Hyperswitch interface - #![warn(missing_docs, missing_debug_implementations)] -pub mod secrets_interface; - +pub mod api; +pub mod configs; pub mod encryption_interface; +pub mod errors; +pub mod events; +pub mod metrics; +pub mod secrets_interface; +pub mod types; diff --git a/crates/hyperswitch_interfaces/src/metrics.rs b/crates/hyperswitch_interfaces/src/metrics.rs new file mode 100644 index 00000000000..a03215a175d --- /dev/null +++ b/crates/hyperswitch_interfaces/src/metrics.rs @@ -0,0 +1,16 @@ +//! Metrics interface + +use router_env::{counter_metric, global_meter, metrics_context, opentelemetry}; + +metrics_context!(CONTEXT); +global_meter!(GLOBAL_METER, "ROUTER_API"); + +counter_metric!(UNIMPLEMENTED_FLOW, GLOBAL_METER); + +/// fn add attributes +pub fn add_attributes<T: Into<opentelemetry::Value>>( + key: &'static str, + value: T, +) -> opentelemetry::KeyValue { + opentelemetry::KeyValue::new(key, value) +} diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs new file mode 100644 index 00000000000..2f0c5c2fbda --- /dev/null +++ b/crates/hyperswitch_interfaces/src/types.rs @@ -0,0 +1,12 @@ +//! Types interface + +/// struct Response +#[derive(Clone, Debug)] +pub struct Response { + /// headers + pub headers: Option<http::HeaderMap>, + /// response + pub response: bytes::Bytes, + /// status code + pub status_code: u16, +} diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index ac8689d21b4..06cff596312 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -17,6 +17,7 @@ use external_services::{ secrets_management::SecretsManagementConfig, }, }; +pub use hyperswitch_interfaces::configs::Connectors; use hyperswitch_interfaces::secrets_interface::secret_state::{ RawSecret, SecretState, SecretStateContainer, SecuredSecret, }; @@ -544,117 +545,6 @@ pub struct SupportedConnectors { pub wallets: Vec<String>, } -#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] -#[serde(default)] -pub struct Connectors { - pub aci: ConnectorParams, - #[cfg(feature = "payouts")] - pub adyen: ConnectorParamsWithSecondaryBaseUrl, - pub adyenplatform: ConnectorParams, - #[cfg(not(feature = "payouts"))] - pub adyen: ConnectorParams, - pub airwallex: ConnectorParams, - pub applepay: ConnectorParams, - pub authorizedotnet: ConnectorParams, - pub bambora: ConnectorParams, - pub bankofamerica: ConnectorParams, - pub billwerk: ConnectorParams, - pub bitpay: ConnectorParams, - pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, - pub boku: ConnectorParams, - pub braintree: ConnectorParams, - pub cashtocode: ConnectorParams, - pub checkout: ConnectorParams, - pub coinbase: ConnectorParams, - pub cryptopay: ConnectorParams, - pub cybersource: ConnectorParams, - pub datatrans: ConnectorParams, - pub dlocal: ConnectorParams, - #[cfg(feature = "dummy_connector")] - pub dummyconnector: ConnectorParams, - pub ebanx: ConnectorParams, - pub fiserv: ConnectorParams, - pub forte: ConnectorParams, - pub globalpay: ConnectorParams, - pub globepay: ConnectorParams, - pub gocardless: ConnectorParams, - pub gpayments: ConnectorParams, - pub helcim: ConnectorParams, - pub iatapay: ConnectorParams, - pub klarna: ConnectorParams, - pub mifinity: ConnectorParams, - pub mollie: ConnectorParams, - pub multisafepay: ConnectorParams, - pub netcetera: ConnectorParams, - pub nexinets: ConnectorParams, - pub nmi: ConnectorParams, - pub noon: ConnectorParamsWithModeType, - pub nuvei: ConnectorParams, - pub opayo: ConnectorParams, - pub opennode: ConnectorParams, - pub payeezy: ConnectorParams, - pub payme: ConnectorParams, - pub payone: ConnectorParams, - pub paypal: ConnectorParams, - pub payu: ConnectorParams, - pub placetopay: ConnectorParams, - pub powertranz: ConnectorParams, - pub prophetpay: ConnectorParams, - pub rapyd: ConnectorParams, - pub riskified: ConnectorParams, - pub shift4: ConnectorParams, - pub signifyd: ConnectorParams, - pub square: ConnectorParams, - pub stax: ConnectorParams, - pub stripe: ConnectorParamsWithFileUploadUrl, - pub threedsecureio: ConnectorParams, - pub trustpay: ConnectorParamsWithMoreUrls, - pub tsys: ConnectorParams, - pub volt: ConnectorParams, - pub wise: ConnectorParams, - pub worldline: ConnectorParams, - pub worldpay: ConnectorParams, - pub zen: ConnectorParams, - pub zsl: ConnectorParams, -} - -#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] -#[serde(default)] -pub struct ConnectorParams { - pub base_url: String, - pub secondary_base_url: Option<String>, -} - -#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] -#[serde(default)] -pub struct ConnectorParamsWithModeType { - pub base_url: String, - pub secondary_base_url: Option<String>, - /// Can take values like Test or Live for Noon - pub key_mode: String, -} - -#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] -#[serde(default)] -pub struct ConnectorParamsWithMoreUrls { - pub base_url: String, - pub base_url_bank_redirects: String, -} - -#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] -#[serde(default)] -pub struct ConnectorParamsWithFileUploadUrl { - pub base_url: String, - pub base_url_file_upload: String, -} - -#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] -#[serde(default)] -pub struct ConnectorParamsWithSecondaryBaseUrl { - pub base_url: String, - pub secondary_base_url: String, -} - #[cfg(feature = "kv_store")] #[derive(Debug, Clone, Deserialize)] #[serde(default)] diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index e1ef11265c0..d6d376fa0ef 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -1837,12 +1837,6 @@ where json.parse_value(std::any::type_name::<T>()).switch() } -impl common_utils::errors::ErrorSwitch<errors::ConnectorError> for errors::ParsingError { - fn switch(&self) -> errors::ConnectorError { - errors::ConnectorError::ParsingFailed - } -} - pub fn base64_decode(data: String) -> Result<Vec<u8>, Error> { consts::BASE64_ENGINE .decode(data) diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 0e9e4022798..83fa2143648 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -14,6 +14,7 @@ pub use hyperswitch_domain_models::errors::{ api_error_response::{ApiErrorResponse, ErrorType, NotImplementedMessage}, StorageError as DataStorageError, }; +pub use hyperswitch_interfaces::errors::ConnectorError; pub use redis_interface::errors::RedisError; use scheduler::errors as sch_errors; use storage_impl::errors as storage_impl_errors; @@ -111,118 +112,6 @@ pub fn http_not_implemented() -> actix_web::HttpResponse<BoxBody> { .error_response() } -#[derive(Debug, thiserror::Error, PartialEq)] -pub enum ConnectorError { - #[error("Error while obtaining URL for the integration")] - FailedToObtainIntegrationUrl, - #[error("Failed to encode connector request")] - RequestEncodingFailed, - #[error("Request encoding failed : {0}")] - RequestEncodingFailedWithReason(String), - #[error("Parsing failed")] - ParsingFailed, - #[error("Failed to deserialize connector response")] - ResponseDeserializationFailed, - #[error("Failed to execute a processing step: {0:?}")] - ProcessingStepFailed(Option<bytes::Bytes>), - #[error("The connector returned an unexpected response: {0:?}")] - UnexpectedResponseError(bytes::Bytes), - #[error("Failed to parse custom routing rules from merchant account")] - RoutingRulesParsingError, - #[error("Failed to obtain preferred connector from merchant account")] - FailedToObtainPreferredConnector, - #[error("An invalid connector name was provided")] - InvalidConnectorName, - #[error("An invalid Wallet was used")] - InvalidWallet, - #[error("Failed to handle connector response")] - ResponseHandlingFailed, - #[error("Missing required field: {field_name}")] - MissingRequiredField { field_name: &'static str }, - #[error("Missing required fields: {field_names:?}")] - MissingRequiredFields { field_names: Vec<&'static str> }, - #[error("Failed to obtain authentication type")] - FailedToObtainAuthType, - #[error("Failed to obtain certificate")] - FailedToObtainCertificate, - #[error("Connector meta data not found")] - NoConnectorMetaData, - #[error("Failed to obtain certificate key")] - FailedToObtainCertificateKey, - #[error("This step has not been implemented for: {0}")] - NotImplemented(String), - #[error("{message} is not supported by {connector}")] - NotSupported { - message: String, - connector: &'static str, - }, - #[error("{flow} flow not supported by {connector} connector")] - FlowNotSupported { flow: String, connector: String }, - #[error("Capture method not supported")] - CaptureMethodNotSupported, - #[error("Missing connector mandate ID")] - MissingConnectorMandateID, - #[error("Missing connector transaction ID")] - MissingConnectorTransactionID, - #[error("Missing connector refund ID")] - MissingConnectorRefundID, - #[error("Missing apple pay tokenization data")] - MissingApplePayTokenData, - #[error("Webhooks not implemented for this connector")] - WebhooksNotImplemented, - #[error("Failed to decode webhook event body")] - WebhookBodyDecodingFailed, - #[error("Signature not found for incoming webhook")] - WebhookSignatureNotFound, - #[error("Failed to verify webhook source")] - WebhookSourceVerificationFailed, - #[error("Could not find merchant secret in DB for incoming webhook source verification")] - WebhookVerificationSecretNotFound, - #[error("Merchant secret found for incoming webhook source verification is invalid")] - WebhookVerificationSecretInvalid, - #[error("Incoming webhook object reference ID not found")] - WebhookReferenceIdNotFound, - #[error("Incoming webhook event type not found")] - WebhookEventTypeNotFound, - #[error("Incoming webhook event resource object not found")] - WebhookResourceObjectNotFound, - #[error("Could not respond to the incoming webhook event")] - WebhookResponseEncodingFailed, - #[error("Invalid Date/time format")] - InvalidDateFormat, - #[error("Date Formatting Failed")] - DateFormattingFailed, - #[error("Invalid Data format")] - InvalidDataFormat { field_name: &'static str }, - #[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")] - MismatchedPaymentData, - #[error("Failed to parse {wallet_name} wallet token")] - InvalidWalletToken { wallet_name: String }, - #[error("Missing Connector Related Transaction ID")] - MissingConnectorRelatedTransactionID { id: String }, - #[error("File Validation failed")] - FileValidationFailed { reason: String }, - #[error("Missing 3DS redirection payload: {field_name}")] - MissingConnectorRedirectionPayload { field_name: &'static str }, - #[error("Failed at connector's end with code '{code}'")] - FailedAtConnector { message: String, code: String }, - #[error("Payment Method Type not found")] - MissingPaymentMethodType, - #[error("Balance in the payment method is low")] - InSufficientBalanceInPaymentMethod, - #[error("Server responded with Request Timeout")] - RequestTimeoutReceived, - #[error("The given currency method is not configured with the given connector")] - CurrencyNotSupported { - message: String, - connector: &'static str, - }, - #[error("Invalid Configuration")] - InvalidConnectorConfig { config: &'static str }, - #[error("Failed to convert amount to required type")] - AmountConversionFailed, -} - #[derive(Debug, thiserror::Error)] pub enum HealthCheckOutGoing { #[error("Outgoing call failed with error: {message}")] @@ -335,12 +224,6 @@ pub enum ApplePayDecryptionError { DerivingSharedSecretKeyFailed, } -impl ConnectorError { - pub fn is_connector_timeout(&self) -> bool { - self == &Self::RequestTimeoutReceived - } -} - #[cfg(feature = "detailed_errors")] pub mod error_stack_parsing { diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs index df529f81803..f5e90771c14 100644 --- a/crates/router/src/core/errors/transformers.rs +++ b/crates/router/src/core/errors/transformers.rs @@ -1,25 +1,7 @@ use common_utils::errors::ErrorSwitch; use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse; -use super::{ConnectorError, CustomersErrorResponse, StorageError}; - -impl ErrorSwitch<ApiErrorResponse> for ConnectorError { - fn switch(&self) -> ApiErrorResponse { - match self { - Self::WebhookSourceVerificationFailed => ApiErrorResponse::WebhookAuthenticationFailed, - Self::WebhookSignatureNotFound - | Self::WebhookReferenceIdNotFound - | Self::WebhookResourceObjectNotFound - | Self::WebhookBodyDecodingFailed - | Self::WebhooksNotImplemented => ApiErrorResponse::WebhookBadRequest, - Self::WebhookEventTypeNotFound => ApiErrorResponse::WebhookUnprocessableEntity, - Self::WebhookVerificationSecretInvalid => { - ApiErrorResponse::WebhookInvalidMerchantSecret - } - _ => ApiErrorResponse::InternalServerError, - } - } -} +use super::{CustomersErrorResponse, StorageError}; impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for CustomersErrorResponse { fn switch(&self) -> api_models::errors::types::ApiErrorResponse { diff --git a/crates/router/src/events/connector_api_logs.rs b/crates/router/src/events/connector_api_logs.rs index af026356826..7c354620b5a 100644 --- a/crates/router/src/events/connector_api_logs.rs +++ b/crates/router/src/events/connector_api_logs.rs @@ -1,95 +1,8 @@ -use common_utils::request::Method; -use router_env::tracing_actix_web::RequestId; -use serde::Serialize; -use serde_json::json; -use time::OffsetDateTime; +pub use hyperswitch_interfaces::events::connector_api_logs::ConnectorEvent; use super::EventType; use crate::services::kafka::KafkaMessage; -#[derive(Debug, Serialize)] -pub struct ConnectorEvent { - connector_name: String, - flow: String, - request: String, - masked_response: Option<String>, - error: Option<String>, - url: String, - method: String, - payment_id: String, - merchant_id: String, - created_at: i128, - request_id: String, - latency: u128, - refund_id: Option<String>, - dispute_id: Option<String>, - status_code: u16, -} - -impl ConnectorEvent { - #[allow(clippy::too_many_arguments)] - pub fn new( - connector_name: String, - flow: &str, - request: serde_json::Value, - url: String, - method: Method, - payment_id: String, - merchant_id: String, - request_id: Option<&RequestId>, - latency: u128, - refund_id: Option<String>, - dispute_id: Option<String>, - status_code: u16, - ) -> Self { - Self { - connector_name, - flow: flow - .rsplit_once("::") - .map(|(_, s)| s) - .unwrap_or(flow) - .to_string(), - request: request.to_string(), - masked_response: None, - error: None, - url, - method: method.to_string(), - payment_id, - merchant_id, - created_at: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000, - request_id: request_id - .map(|i| i.as_hyphenated().to_string()) - .unwrap_or("NO_REQUEST_ID".to_string()), - latency, - refund_id, - dispute_id, - 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 KafkaMessage for ConnectorEvent { fn event_type(&self) -> EventType { EventType::ConnectorApiLogs diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 18014c6e193..eef85410981 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -76,7 +76,6 @@ counter_metric!(REDIRECTION_TRIGGERED, GLOBAL_METER); // Connector Level Metric counter_metric!(REQUEST_BUILD_FAILURE, GLOBAL_METER); -counter_metric!(UNIMPLEMENTED_FLOW, GLOBAL_METER); // Connector http status code metrics counter_metric!(CONNECTOR_HTTP_STATUS_CODE_1XX_COUNT, GLOBAL_METER); counter_metric!(CONNECTOR_HTTP_STATUS_CODE_2XX_COUNT, GLOBAL_METER); diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index baa824ced3f..cccbaa496e1 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -25,6 +25,9 @@ use common_utils::{ }; use error_stack::{report, Report, ResultExt}; pub use hyperswitch_domain_models::router_response_types::RedirectForm; +pub use hyperswitch_interfaces::api::{ + BoxedConnectorIntegration, CaptureSyncMethod, ConnectorIntegration, ConnectorIntegrationAny, +}; use masking::{Maskable, PeekInterface}; use router_env::{instrument, tracing, tracing_actix_web::RequestId, Tag}; use serde::Serialize; @@ -34,7 +37,7 @@ use tera::{Context, Tera}; use self::request::{HeaderExt, RequestBuilderExt}; use super::authentication::AuthenticateAndFetch; use crate::{ - configs::{settings::Connectors, Settings}, + configs::Settings, consts, core::{ api_locking, @@ -58,22 +61,6 @@ use crate::{ }, }; -pub type BoxedConnectorIntegration<'a, T, Req, Resp> = - Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>; - -pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static { - fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>; -} - -impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S -where - S: ConnectorIntegration<T, Req, Resp> + Send + Sync, -{ - fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> { - Box::new(self) - } -} - pub trait ConnectorValidation: ConnectorCommon { fn validate_capture_method( &self, @@ -129,145 +116,6 @@ pub trait ConnectorValidation: ConnectorCommon { } } -#[async_trait::async_trait] -pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> + Sync { - fn get_headers( - &self, - _req: &types::RouterData<T, Req, Resp>, - _connectors: &Connectors, - ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { - Ok(vec![]) - } - - fn get_content_type(&self) -> &'static str { - mime::APPLICATION_JSON.essence_str() - } - - /// primarily used when creating signature based on request method of payment flow - fn get_http_method(&self) -> Method { - Method::Post - } - - fn get_url( - &self, - _req: &types::RouterData<T, Req, Resp>, - _connectors: &Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(String::new()) - } - - fn get_request_body( - &self, - _req: &types::RouterData<T, Req, Resp>, - _connectors: &Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - Ok(RequestContent::Json(Box::new(json!(r#"{}"#)))) - } - - fn get_request_form_data( - &self, - _req: &types::RouterData<T, Req, Resp>, - ) -> CustomResult<Option<reqwest::multipart::Form>, errors::ConnectorError> { - Ok(None) - } - - fn build_request( - &self, - req: &types::RouterData<T, Req, Resp>, - _connectors: &Connectors, - ) -> CustomResult<Option<Request>, errors::ConnectorError> { - metrics::UNIMPLEMENTED_FLOW.add( - &metrics::CONTEXT, - 1, - &[metrics::request::add_attributes( - "connector", - req.connector.clone(), - )], - ); - Ok(None) - } - - 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 - T: Clone, - 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, - 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", - 502 => "bad_gateway", - 503 => "service_unavailable", - 504 => "gateway_timeout", - 505 => "http_version_not_supported", - 506 => "variant_also_negotiates", - 507 => "insufficient_storage", - 508 => "loop_detected", - 510 => "not_extended", - 511 => "network_authentication_required", - _ => "unknown_error", - }; - Ok(ErrorResponse { - code: res.status_code.to_string(), - message: error_message.to_string(), - reason: String::from_utf8(res.response.to_vec()).ok(), - status_code: res.status_code, - attempt_status: None, - connector_transaction_id: None, - }) - } - - // whenever capture sync is implemented at the connector side, this method should be overridden - fn get_multiple_capture_sync_method( - &self, - ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("multiple capture sync".into()).into()) - } - - fn get_certificate( - &self, - _req: &types::RouterData<T, Req, Resp>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - Ok(None) - } - - fn get_certificate_key( - &self, - _req: &types::RouterData<T, Req, Resp>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - Ok(None) - } -} - -pub enum CaptureSyncMethod { - Individual, - Bulk, -} - /// 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 diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index d864eabd093..38e0bed699f 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -52,6 +52,7 @@ pub use hyperswitch_domain_models::{ VerifyWebhookSourceResponseData, VerifyWebhookStatus, }, }; +pub use hyperswitch_interfaces::types::Response; pub use crate::core::payments::CustomerDetails; #[cfg(feature = "payouts")] @@ -684,13 +685,6 @@ pub struct ConnectorsList { pub connectors: Vec<String>, } -#[derive(Clone, Debug)] -pub struct Response { - pub headers: Option<http::HeaderMap>, - pub response: bytes::Bytes, - pub status_code: u16, -} - impl ForeignTryFrom<ConnectorAuthType> for AccessTokenRequestData { type Error = errors::ApiErrorResponse; fn foreign_try_from(connector_auth: ConnectorAuthType) -> Result<Self, Self::Error> { diff --git a/crates/router_derive/src/macros/misc.rs b/crates/router_derive/src/macros/misc.rs index 4717fe730d9..04c37e75950 100644 --- a/crates/router_derive/src/macros/misc.rs +++ b/crates/router_derive/src/macros/misc.rs @@ -52,6 +52,7 @@ pub fn validate_config(input: syn::DeriveInput) -> Result<proc_macro2::TokenStre let expansion = quote::quote! { impl #struct_name { + /// Validates that the configuration provided for the `parent_field` does not contain empty or default values pub fn validate(&self, parent_field: &str) -> Result<(), ApplicationError> { #(#function_expansions)* Ok(())
2024-06-11T09:50:21Z
## Description <!-- Describe your changes in detail --> The trait ConnectorIntegration needs to be moved to crate hyperswitch_interfaces from router. This is required to move connector code out from crate 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). --> https://github.com/juspay/hyperswitch/issues/4945 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Basic testing is required for all the production connectors(and payment methods) on sandbox.
658272904897f7cbc4d9a349278712f35a8d3e96
Basic testing is required for all the production connectors(and payment methods) on sandbox.
[ "Cargo.lock", "crates/hyperswitch_interfaces/Cargo.toml", "crates/hyperswitch_interfaces/src/api.rs", "crates/hyperswitch_interfaces/src/configs.rs", "crates/hyperswitch_interfaces/src/errors.rs", "crates/hyperswitch_interfaces/src/events.rs", "crates/hyperswitch_interfaces/src/events/connector_api_logs...
juspay/hyperswitch
juspay__hyperswitch-4947
Bug: [REFACTOR] Allow deletion of Default Payment Methods ### Feature Description Allow deletion of Payment Methods , even if there is only one PM for that respective connector ### Possible Implementation Allow deletion of Payment Methods , even if there is only one PM for that respective connector ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 499eddafc1f..0641c842390 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3993,16 +3993,6 @@ pub async fn delete_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; - let payment_methods_count = db - .get_payment_method_count_by_customer_id_merchant_id_status( - &key.customer_id, - &merchant_account.merchant_id, - api_enums::PaymentMethodStatus::Active, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to get a count of payment methods for a customer")?; - let customer = db .find_customer_by_customer_id_merchant_id( &key.customer_id, @@ -4014,12 +4004,6 @@ pub async fn delete_payment_method( .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("Customer not found for the payment method")?; - utils::when( - customer.default_payment_method_id.as_ref() == Some(&pm_id.payment_method_id) - && payment_methods_count > 1, - || Err(errors::ApiErrorResponse::PaymentMethodDeleteFailed), - )?; - if key.payment_method == Some(enums::PaymentMethod::Card) { let response = delete_card_from_locker( &state,
2024-06-11T08:57:32Z
## Description Previously we did not support the deletion of the Default Payment Method, if it's the only PM for the particular customer. In this PR we enable deletion of default Payment Methods ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? - Create a MA and a MCA - Do a payment , with `setup_future_usag:off_session`; the card would be saved - Do a List PM for Customers, you'll have only one card , which has been set as default ``` Response { "customer_payment_methods": [ { "payment_token": "token_FC8TupTKMEmhtM69dmYS", "payment_method_id": "pm_Syvbg2Nb8mGdZC9oi4Sv", "customer_id": "CustomerX", "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "11", "expiry_year": "2040", "card_token": null, "card_holder_name": "AKA", "card_fingerprint": null, "nick_name": "HELO", "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "metadata": null, "created": "2024-06-11T10:14:09.587Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-06-11T10:14:09.587Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } } ], "is_guest_customer": null } ``` - Delete the Payment Method, it'll be a success ``` Request curl --location --request DELETE 'http://localhost:8080/payment_methods/:payment_method_id' \ --header 'Accept: application/json' \ --header 'api-key: dev_u3eBlxHY8BxUeQxxgvZGxKRXf7HEPaAw0sXmhjXjFFTmQ0pfyslENYRDajyrQnOf' ``` ``` Response { "payment_method_id": "pm_50cS5VsVOhgbKQ63WReh", "deleted": true } ``` - List the Pm for Customer would be empty ``` Response { "customer_payment_methods": [], "is_guest_customer": null } ```
b705757be37a9803b964ef94d04c664c0f1e102d
- Create a MA and a MCA - Do a payment , with `setup_future_usag:off_session`; the card would be saved - Do a List PM for Customers, you'll have only one card , which has been set as default ``` Response { "customer_payment_methods": [ { "payment_token": "token_FC8TupTKMEmhtM69dmYS", "payment_method_id": "pm_Syvbg2Nb8mGdZC9oi4Sv", "customer_id": "CustomerX", "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "11", "expiry_year": "2040", "card_token": null, "card_holder_name": "AKA", "card_fingerprint": null, "nick_name": "HELO", "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "metadata": null, "created": "2024-06-11T10:14:09.587Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-06-11T10:14:09.587Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } } ], "is_guest_customer": null } ``` - Delete the Payment Method, it'll be a success ``` Request curl --location --request DELETE 'http://localhost:8080/payment_methods/:payment_method_id' \ --header 'Accept: application/json' \ --header 'api-key: dev_u3eBlxHY8BxUeQxxgvZGxKRXf7HEPaAw0sXmhjXjFFTmQ0pfyslENYRDajyrQnOf' ``` ``` Response { "payment_method_id": "pm_50cS5VsVOhgbKQ63WReh", "deleted": true } ``` - List the Pm for Customer would be empty ``` Response { "customer_payment_methods": [], "is_guest_customer": null } ```
[ "crates/router/src/core/payment_methods/cards.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4938
Bug: [FEATURE] Add support for gauge metrics and include IMC metrics Add support for gauge metrics. Additionally also add a background thread, which will be spawned during application startup, that runs for every fixed interval (configurable) of time, collecting the metrics. For now this collector can collect the gauge metrics of `cache_entry_count` of all the cache types.
diff --git a/config/config.example.toml b/config/config.example.toml index f4a6a66cd61..81516ee8b6b 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -112,6 +112,7 @@ otel_exporter_otlp_endpoint = "http://localhost:4317" # endpoint to send metrics otel_exporter_otlp_timeout = 5000 # timeout (in milliseconds) for sending metrics and traces use_xray_generator = false # Set this to true for AWS X-ray compatible traces route_to_trace = ["*/confirm"] +bg_metrics_collection_interval_in_secs = 15 # Interval for collecting the metrics in background thread # This section provides some secret values. [secrets] diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index a097e1b66dc..9ab790b8ee8 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -139,6 +139,7 @@ otel_exporter_otlp_endpoint = "http://localhost:4317" # endpoint to send metrics otel_exporter_otlp_timeout = 5000 # timeout (in milliseconds) for sending metrics and traces use_xray_generator = false # Set this to true for AWS X-ray compatible traces route_to_trace = ["*/confirm"] +bg_metrics_collection_interval_in_secs = 15 # Interval for collecting the metrics in background thread [lock_settings] delay_between_retries_in_milliseconds = 500 # Delay between retries in milliseconds diff --git a/config/development.toml b/config/development.toml index 2c6d67e7515..e475459573a 100644 --- a/config/development.toml +++ b/config/development.toml @@ -10,6 +10,7 @@ log_format = "default" traces_enabled = false metrics_enabled = false use_xray_generator = false +bg_metrics_collection_interval_in_secs = 15 # TODO: Update database credentials before running application [master_database] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 2a4fe369286..2cd93eade01 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -18,7 +18,8 @@ traces_enabled = false # Whether traces are metrics_enabled = true # Whether metrics are enabled. ignore_errors = false # Whether to ignore errors during traces or metrics pipeline setup. otel_exporter_otlp_endpoint = "https://otel-collector:4317" # Endpoint to send metrics and traces to. -use_xray_generator = false +use_xray_generator = false # Set this to true for AWS X-ray compatible traces +bg_metrics_collection_interval_in_secs = 15 # Interval for collecting the metrics in background thread [master_database] username = "db_user" diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rs index 094f799cb27..8271e458b24 100644 --- a/crates/router/src/bin/router.rs +++ b/crates/router/src/bin/router.rs @@ -2,6 +2,7 @@ use router::{ configs::settings::{CmdLineConf, Settings}, core::errors::{ApplicationError, ApplicationResult}, logger, + routes::metrics, }; #[tokio::main] @@ -27,6 +28,11 @@ async fn main() -> ApplicationResult<()> { logger::info!("Application started [{:?}] [{:?}]", conf.server, conf.log); + // Spawn a thread for collecting metrics at fixed intervals + metrics::bg_metrics_collector::spawn_metrics_collector( + &conf.log.telemetry.bg_metrics_collection_interval_in_secs, + ); + #[allow(clippy::expect_used)] let server = Box::pin(router::start_server(conf)) .await diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 1123be1a874..18014c6e193 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -1,4 +1,8 @@ -use router_env::{counter_metric, global_meter, histogram_metric, metrics_context}; +pub mod bg_metrics_collector; +pub mod request; +pub mod utils; + +use router_env::{counter_metric, gauge_metric, global_meter, histogram_metric, metrics_context}; metrics_context!(CONTEXT); global_meter!(GLOBAL_METER, "ROUTER_API"); @@ -133,5 +137,5 @@ counter_metric!(ACCESS_TOKEN_CACHE_HIT, GLOBAL_METER); // A counter to indicate the access token cache miss counter_metric!(ACCESS_TOKEN_CACHE_MISS, GLOBAL_METER); -pub mod request; -pub mod utils; +// Metrics for In-memory cache +gauge_metric!(CACHE_ENTRY_COUNT, GLOBAL_METER); diff --git a/crates/router/src/routes/metrics/bg_metrics_collector.rs b/crates/router/src/routes/metrics/bg_metrics_collector.rs new file mode 100644 index 00000000000..65cb7a13e5e --- /dev/null +++ b/crates/router/src/routes/metrics/bg_metrics_collector.rs @@ -0,0 +1,46 @@ +use storage_impl::redis::cache; + +const DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS: u16 = 15; + +macro_rules! gauge_metrics_for_imc { + ($($cache:ident),*) => { + $( + { + cache::$cache.run_pending_tasks().await; + + super::CACHE_ENTRY_COUNT.observe( + &super::CONTEXT, + cache::$cache.get_entry_count(), + &[super::request::add_attributes( + "cache_type", + stringify!($cache), + )], + ); + } + )* + }; +} + +pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: &Option<u16>) { + let metrics_collection_interval = metrics_collection_interval_in_secs + .unwrap_or(DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS); + + tokio::spawn(async move { + loop { + gauge_metrics_for_imc!( + CONFIG_CACHE, + ACCOUNTS_CACHE, + ROUTING_CACHE, + CGRAPH_CACHE, + PM_FILTERS_CGRAPH_CACHE, + DECISION_MANAGER_CACHE, + SURCHARGE_CACHE + ); + + tokio::time::sleep(std::time::Duration::from_secs( + metrics_collection_interval.into(), + )) + .await + } + }); +} diff --git a/crates/router_env/src/logger/config.rs b/crates/router_env/src/logger/config.rs index 09d285a8628..135451f266e 100644 --- a/crates/router_env/src/logger/config.rs +++ b/crates/router_env/src/logger/config.rs @@ -103,6 +103,8 @@ pub struct LogTelemetry { pub use_xray_generator: bool, /// Route Based Tracing pub route_to_trace: Option<Vec<String>>, + /// Interval for collecting the metrics (such as gauge) in background thread + pub bg_metrics_collection_interval_in_secs: Option<u16>, } /// Telemetry / tracing. diff --git a/crates/router_env/src/metrics.rs b/crates/router_env/src/metrics.rs index e145caace00..e75cacaa3c9 100644 --- a/crates/router_env/src/metrics.rs +++ b/crates/router_env/src/metrics.rs @@ -101,3 +101,22 @@ macro_rules! histogram_metric_i64 { > = once_cell::sync::Lazy::new(|| $meter.i64_histogram($description).init()); }; } + +/// Create a [`ObservableGauge`][ObservableGauge] metric with the specified name and an optional description, +/// associated with the specified meter. Note that the meter must be to a valid [`Meter`][Meter]. +/// +/// [ObservableGauge]: opentelemetry::metrics::ObservableGauge +/// [Meter]: opentelemetry::metrics::Meter +#[macro_export] +macro_rules! gauge_metric { + ($name:ident, $meter:ident) => { + pub(crate) static $name: once_cell::sync::Lazy< + $crate::opentelemetry::metrics::ObservableGauge<u64>, + > = once_cell::sync::Lazy::new(|| $meter.u64_observable_gauge(stringify!($name)).init()); + }; + ($name:ident, $meter:ident, description:literal) => { + pub(crate) static $name: once_cell::sync::Lazy< + $crate::opentelemetry::metrics::ObservableGauge<u64>, + > = once_cell::sync::Lazy::new(|| $meter.u64_observable_gauge($description).init()); + }; +} diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs index e4efab0da33..6ad96be2795 100644 --- a/crates/storage_impl/src/redis/cache.rs +++ b/crates/storage_impl/src/redis/cache.rs @@ -207,6 +207,16 @@ impl Cache { pub async fn remove(&self, key: CacheKey) { self.inner.invalidate::<String>(&key.into()).await; } + + /// Performs any pending maintenance operations needed by the cache. + pub async fn run_pending_tasks(&self) { + self.inner.run_pending_tasks().await; + } + + /// Returns an approximate number of entries in this cache. + pub fn get_entry_count(&self) -> u64 { + self.inner.entry_count() + } } #[instrument(skip_all)]
2024-06-10T18:02:28Z
## Description <!-- Describe your changes in detail --> This PR adds support for gauge metrics. Additionally the pr also adds a background thread, which will be spawned during application startup, that runs for every fixed interval (configurable) of time, collecting the metrics. For now this collector collects the gauge metrics of `cache_entry_count` of all the cache types. ### 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)? --> Hit list payment methods for a merchant endpoint and check for `router_CACHE_ENTRY_COUNT` metric in grafana ![image](https://github.com/juspay/hyperswitch/assets/70657455/7b08c4e5-d7f8-433e-8561-6bdefef039dc)
b705757be37a9803b964ef94d04c664c0f1e102d
Hit list payment methods for a merchant endpoint and check for `router_CACHE_ENTRY_COUNT` metric in grafana ![image](https://github.com/juspay/hyperswitch/assets/70657455/7b08c4e5-d7f8-433e-8561-6bdefef039dc)
[ "config/config.example.toml", "config/deployments/env_specific.toml", "config/development.toml", "config/docker_compose.toml", "crates/router/src/bin/router.rs", "crates/router/src/routes/metrics.rs", "crates/router/src/routes/metrics/bg_metrics_collector.rs", "crates/router_env/src/logger/config.rs",...
juspay/hyperswitch
juspay__hyperswitch-4934
Bug: [BUG] 5xx is thrown when invalid certificate and private key is configured in MCA for Netcetera ### Bug Description 5xx is thrown during authentication call when invalid certificate and private key is configured in MCA for Netcetera ### Expected Behavior 4xx should be thrown when invalid certificate or private keys are configured during MCA creation or updation. ### Actual Behavior 5xx is thrown during authentication call when invalid certificate and private key is configured in MCA for Netcetera ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Create a netcetera connector with invalid certificate or private key. 2. No validation error is thrown. ### 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/admin.rs b/crates/router/src/core/admin.rs index f9da9908d95..fc83573e21d 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -858,27 +858,7 @@ pub async fn create_payment_connector( expected_format: "auth_type and api_key".to_string(), })?; - validate_auth_and_metadata_type(req.connector_name, &auth, &req.metadata).map_err(|err| { - match *err.current_context() { - errors::ConnectorError::InvalidConnectorName => { - err.change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "The connector name is invalid".to_string(), - }) - } - errors::ConnectorError::InvalidConnectorConfig { config: field_name } => err - .change_context(errors::ApiErrorResponse::InvalidRequestData { - message: format!("The {} is invalid", field_name), - }), - errors::ConnectorError::FailedToObtainAuthType => { - err.change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "The auth type is invalid for the connector".to_string(), - }) - } - _ => err.change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "The request body is invalid".to_string(), - }), - } - })?; + validate_auth_and_metadata_type(req.connector_name, &auth, &req.metadata)?; let frm_configs = get_frm_config_as_secret(req.frm_configs); @@ -1208,27 +1188,7 @@ pub async fn update_payment_connector( field_name: "connector", }) .attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?; - validate_auth_and_metadata_type(connector_enum, &auth, &metadata).map_err(|err| match *err - .current_context() - { - errors::ConnectorError::InvalidConnectorName => { - err.change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "The connector name is invalid".to_string(), - }) - } - errors::ConnectorError::InvalidConnectorConfig { config: field_name } => err - .change_context(errors::ApiErrorResponse::InvalidRequestData { - message: format!("The {} is invalid", field_name), - }), - errors::ConnectorError::FailedToObtainAuthType => { - err.change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "The auth type is invalid for the connector".to_string(), - }) - } - _ => err.change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "The request body is invalid".to_string(), - }), - })?; + validate_auth_and_metadata_type(connector_enum, &auth, &metadata)?; let (connector_status, disabled) = validate_status_and_disabled(req.status, req.disabled, auth, mca.status)?; @@ -1817,7 +1777,35 @@ pub async fn connector_agnostic_mit_toggle( )) } -pub(crate) fn validate_auth_and_metadata_type( +pub fn validate_auth_and_metadata_type( + connector_name: api_models::enums::Connector, + auth_type: &types::ConnectorAuthType, + connector_meta_data: &Option<pii::SecretSerdeValue>, +) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { + validate_connector_auth_type(auth_type)?; + validate_auth_and_metadata_type_with_connector(connector_name, auth_type, connector_meta_data) + .map_err(|err| match *err.current_context() { + errors::ConnectorError::InvalidConnectorName => { + err.change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "The connector name is invalid".to_string(), + }) + } + errors::ConnectorError::InvalidConnectorConfig { config: field_name } => err + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: format!("The {} is invalid", field_name), + }), + errors::ConnectorError::FailedToObtainAuthType => { + err.change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "The auth type is invalid for the connector".to_string(), + }) + } + _ => err.change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "The request body is invalid".to_string(), + }), + }) +} + +pub(crate) fn validate_auth_and_metadata_type_with_connector( connector_name: api_models::enums::Connector, val: &types::ConnectorAuthType, connector_meta_data: &Option<pii::SecretSerdeValue>, @@ -2094,6 +2082,84 @@ pub(crate) fn validate_auth_and_metadata_type( } } +pub(crate) fn validate_connector_auth_type( + auth_type: &types::ConnectorAuthType, +) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { + let validate_non_empty_field = |field_value: &str, field_name: &str| { + if field_value.trim().is_empty() { + Err(errors::ApiErrorResponse::InvalidDataFormat { + field_name: format!("connector_account_details.{}", field_name), + expected_format: "a non empty String".to_string(), + } + .into()) + } else { + Ok(()) + } + }; + match auth_type { + hyperswitch_domain_models::router_data::ConnectorAuthType::TemporaryAuth => Ok(()), + hyperswitch_domain_models::router_data::ConnectorAuthType::HeaderKey { api_key } => { + validate_non_empty_field(api_key.peek(), "api_key") + } + hyperswitch_domain_models::router_data::ConnectorAuthType::BodyKey { api_key, key1 } => { + validate_non_empty_field(api_key.peek(), "api_key")?; + validate_non_empty_field(key1.peek(), "key1") + } + hyperswitch_domain_models::router_data::ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } => { + validate_non_empty_field(api_key.peek(), "api_key")?; + validate_non_empty_field(key1.peek(), "key1")?; + validate_non_empty_field(api_secret.peek(), "api_secret") + } + hyperswitch_domain_models::router_data::ConnectorAuthType::MultiAuthKey { + api_key, + key1, + api_secret, + key2, + } => { + validate_non_empty_field(api_key.peek(), "api_key")?; + validate_non_empty_field(key1.peek(), "key1")?; + validate_non_empty_field(api_secret.peek(), "api_secret")?; + validate_non_empty_field(key2.peek(), "key2") + } + hyperswitch_domain_models::router_data::ConnectorAuthType::CurrencyAuthKey { + auth_key_map, + } => { + if auth_key_map.is_empty() { + Err(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "connector_account_details.auth_key_map".to_string(), + expected_format: "a non empty map".to_string(), + } + .into()) + } else { + Ok(()) + } + } + hyperswitch_domain_models::router_data::ConnectorAuthType::CertificateAuth { + certificate, + private_key, + } => { + helpers::create_identity_from_certificate_and_key( + certificate.to_owned(), + private_key.to_owned(), + ) + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: + "connector_account_details.certificate or connector_account_details.private_key" + .to_string(), + expected_format: + "a valid base64 encoded string of PEM encoded Certificate and Private Key" + .to_string(), + })?; + Ok(()) + } + hyperswitch_domain_models::router_data::ConnectorAuthType::NoKey => Ok(()), + } +} + #[cfg(feature = "dummy_connector")] pub async fn validate_dummy_connector_enabled( state: &SessionState,
2024-06-10T11:13:12Z
## Description <!-- Describe your changes in detail --> Wrote a validation function to validate ConnectorAuthType being passed during MCA create and update. ### 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. SignatureKey ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_3589e3c3-2b53-4627-b0f9-8449b37a9c07/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "cybersource", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "", "key1": "", "api_secret": "" }, "test_mode": true, "disabled": false, "business_country": "US", "business_label": "default", "metadata": { "acquirer_bin": "438309", "acquirer_merchant_id": "00002000000" } }' ``` 2. BodyKey ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "airwallex", "connector_account_details": { "auth_type": "BodyKey", "api_key": "", "key1": "" }, "test_mode": true, "disabled": false, "business_country": "US", "business_label": "default", "metadata": { "acquirer_bin": "438309", "acquirer_merchant_id": "00002000000" } }' ``` 3. SignatureKey ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "checkout", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "", "key1": "", "api_secret": "" }, "test_mode": true, "disabled": false, "business_country": "US", "business_label": "default", "metadata": { "acquirer_bin": "438309", "acquirer_merchant_id": "00002000000" } }' ``` 4. MultiAuthKey ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "forte", "connector_account_details": { "auth_type": "MultiAuthKey", "api_key": "", "key1": "", "api_secret": "", "key2": "" }, "test_mode": true, "disabled": false, "business_country": "US", "business_label": "default", "metadata": { "acquirer_bin": "438309", "acquirer_merchant_id": "00002000000" } }' ``` 5. CurrencyAuthKey ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "cashtocode", "connector_account_details": { "auth_type": "CurrencyAuthKey", "auth_key_map": {} }, "test_mode": true, "disabled": false, "business_country": "US", "business_label": "default", "metadata": { "acquirer_bin": "438309", "acquirer_merchant_id": "00002000000" } }' ``` 6. CertificateAuth ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "authentication_processor", "business_country": "US", "business_label": "default", "connector_name": "netcetera", "connector_account_details": { "auth_type": "CertificateAuth", "certificate": "", "private_key": "" }, "test_mode": true, "disabled": false, "metadata": { "mcc": "5411", "merchant_country_code": "840", "merchant_name": "Dummy Merchant", "endpoint_prefix": "flowbird", "three_ds_requestor_name": "juspay-prev", "three_ds_requestor_id": "juspay-prev", "pull_mechanism_for_external_3ds_enabled": false } }' ``` All above curls contain invalid data in connector_account_details. So should be getting appropriate error message like below. ``` { "error": { "type": "invalid_request", "message": "connector_account_details.certificate or connector_account_details.private_key contains invalid data. Expected format is a valid base64 encoded string of PEM encoded Certificate and Private Key", "code": "IR_05" } } ```
7085a46271791ca3f1c7b86afa7c8b199b93c0cd
Manual. 1. SignatureKey ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_3589e3c3-2b53-4627-b0f9-8449b37a9c07/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "cybersource", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "", "key1": "", "api_secret": "" }, "test_mode": true, "disabled": false, "business_country": "US", "business_label": "default", "metadata": { "acquirer_bin": "438309", "acquirer_merchant_id": "00002000000" } }' ``` 2. BodyKey ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "airwallex", "connector_account_details": { "auth_type": "BodyKey", "api_key": "", "key1": "" }, "test_mode": true, "disabled": false, "business_country": "US", "business_label": "default", "metadata": { "acquirer_bin": "438309", "acquirer_merchant_id": "00002000000" } }' ``` 3. SignatureKey ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "checkout", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "", "key1": "", "api_secret": "" }, "test_mode": true, "disabled": false, "business_country": "US", "business_label": "default", "metadata": { "acquirer_bin": "438309", "acquirer_merchant_id": "00002000000" } }' ``` 4. MultiAuthKey ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "forte", "connector_account_details": { "auth_type": "MultiAuthKey", "api_key": "", "key1": "", "api_secret": "", "key2": "" }, "test_mode": true, "disabled": false, "business_country": "US", "business_label": "default", "metadata": { "acquirer_bin": "438309", "acquirer_merchant_id": "00002000000" } }' ``` 5. CurrencyAuthKey ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "cashtocode", "connector_account_details": { "auth_type": "CurrencyAuthKey", "auth_key_map": {} }, "test_mode": true, "disabled": false, "business_country": "US", "business_label": "default", "metadata": { "acquirer_bin": "438309", "acquirer_merchant_id": "00002000000" } }' ``` 6. CertificateAuth ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "authentication_processor", "business_country": "US", "business_label": "default", "connector_name": "netcetera", "connector_account_details": { "auth_type": "CertificateAuth", "certificate": "", "private_key": "" }, "test_mode": true, "disabled": false, "metadata": { "mcc": "5411", "merchant_country_code": "840", "merchant_name": "Dummy Merchant", "endpoint_prefix": "flowbird", "three_ds_requestor_name": "juspay-prev", "three_ds_requestor_id": "juspay-prev", "pull_mechanism_for_external_3ds_enabled": false } }' ``` All above curls contain invalid data in connector_account_details. So should be getting appropriate error message like below. ``` { "error": { "type": "invalid_request", "message": "connector_account_details.certificate or connector_account_details.private_key contains invalid data. Expected format is a valid base64 encoded string of PEM encoded Certificate and Private Key", "code": "IR_05" } } ```
[ "crates/router/src/core/admin.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4931
Bug: [CHORE] : update apple pay metadata fields ### Feature Description Currently apple pay iOS Certificate flow contains seven fields, in addition to that three more fields needs to be added. ### Possible Implementation update the wasm to accept the fields ### 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/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 246eb566a91..5d4aea5d5dd 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -244,6 +244,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [adyen.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -360,6 +361,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [authorizedotnet.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -463,6 +465,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [bankofamerica.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -540,6 +543,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [bluesnap.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -772,6 +776,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [checkout.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -854,6 +859,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [cybersource.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -1331,6 +1337,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [nexinets.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -1402,6 +1409,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [nmi.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -1469,6 +1477,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [noon.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -1548,6 +1557,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [nuvei.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -1869,6 +1879,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [rapyd.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -2023,6 +2034,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [stripe.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -2180,6 +2192,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [trustpay.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -2347,6 +2360,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [worldpay.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 30b63249881..eb35dbf3df2 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -139,6 +139,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [adyen.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -248,6 +249,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [authorizedotnet.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -322,6 +324,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [bluesnap.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -476,6 +479,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [bankofamerica.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -651,6 +655,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [checkout.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -721,6 +726,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [cybersource.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -1126,6 +1132,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [nexinets.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -1383,6 +1390,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [rapyd.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -1521,6 +1529,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [stripe.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -1593,6 +1602,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [trustpay.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -1701,6 +1711,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [worldpay.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index dee4e5e4fb6..acc422f3bd9 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -244,6 +244,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [adyen.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -360,6 +361,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [authorizedotnet.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -463,6 +465,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [bankofamerica.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -540,6 +543,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [bluesnap.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -772,6 +776,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [checkout.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -854,6 +859,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [cybersource.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -1331,6 +1337,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [nexinets.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -1402,6 +1409,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [nmi.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -1469,6 +1477,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [noon.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -1548,6 +1557,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [nuvei.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -1869,6 +1879,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [rapyd.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -2023,6 +2034,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [stripe.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -2180,6 +2192,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [trustpay.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"] @@ -2347,6 +2360,7 @@ merchant_identifier="Apple Merchant Identifier" display_name="Display Name" initiative="Domain" initiative_context="Domain Name" +payment_processing_details_at="Connector" [worldpay.metadata.apple_pay.payment_request_data] supported_networks=["visa","masterCard","amex","discover"] merchant_capabilities=["supports3DS"]
2024-06-10T10:39:57Z
## Description <!-- Describe your changes in detail --> update apple pay metadata <img width="574" alt="image" src="https://github.com/juspay/hyperswitch/assets/120017870/7ac299bf-99e7-4cfb-b0f4-224a028d3406"> <img width="557" alt="image" src="https://github.com/juspay/hyperswitch/assets/120017870/a5d5826a-7865-4419-87c6-fa79cb4fe053"> ### 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)? -->
7085a46271791ca3f1c7b86afa7c8b199b93c0cd
[ "crates/connector_configs/toml/development.toml", "crates/connector_configs/toml/production.toml", "crates/connector_configs/toml/sandbox.toml" ]
juspay/hyperswitch
juspay__hyperswitch-4929
Bug: [BUG] [CRYPTOPAY] Amount conversion to lower unit causing parsing error ### Bug Description The conversion of a f64 base amount to i64 minor amount is causing parsing error in cryptopay. This needs to be fixed by using decimal type instead of f64. ### Expected Behavior The conversion of a f64 base amount to i64 minor amount should not cause parsing error in cryptopay. ### Actual Behavior The conversion of a f64 base amount to i64 minor amount is causing parsing error in cryptopay. ### Steps To Reproduce Try doing a Cryptopay payment using amount 115. ### 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/cryptopay.rs b/crates/router/src/connector/cryptopay.rs index f7d137eff20..a3e0844842c 100644 --- a/crates/router/src/connector/cryptopay.rs +++ b/crates/router/src/connector/cryptopay.rs @@ -1,13 +1,12 @@ pub mod transformers; -use std::fmt::Debug; - use base64::Engine; use common_utils::{ crypto::{self, GenerateDigest, SignMessage}, date_time, ext_traits::ByteSliceExt, request::RequestContent, + types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::ResultExt; use hex::encode; @@ -36,8 +35,18 @@ use crate::{ utils::BytesExt, }; -#[derive(Debug, Clone)] -pub struct Cryptopay; +#[derive(Clone)] +pub struct Cryptopay { + amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), +} + +impl Cryptopay { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMajorUnitForConnector, + } + } +} impl api::Payment for Cryptopay {} impl api::PaymentSession for Cryptopay {} @@ -123,7 +132,7 @@ where (headers::DATE.to_string(), date.into()), ( headers::CONTENT_TYPE.to_string(), - Self.get_content_type().to_string().into(), + self.get_content_type().to_string().into(), ), ]; Ok(headers) @@ -244,12 +253,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cryptopay::CryptopayRouterData::try_from(( - &self.get_currency_unit(), + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount, req.request.currency, - req.request.amount, - req, - ))?; + )?; + let connector_router_data = cryptopay::CryptopayRouterData::from((amount, req)); let connector_req = cryptopay::CryptopayPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -288,13 +297,21 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + let capture_amount_in_minor_units = match response.data.price_amount { + Some(ref amount) => Some(utils::convert_back( + self.amount_converter, + amount.clone(), + data.request.currency, + )?), + None => None, + }; types::RouterData::foreign_try_from(( types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }, - data.request.currency, + capture_amount_in_minor_units, )) } @@ -375,13 +392,21 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + let capture_amount_in_minor_units = match response.data.price_amount { + Some(ref amount) => Some(utils::convert_back( + self.amount_converter, + amount.clone(), + data.request.currency, + )?), + None => None, + }; types::RouterData::foreign_try_from(( types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }, - data.request.currency, + capture_amount_in_minor_units, )) } diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index bcbc9a043a1..6c999727841 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -1,10 +1,11 @@ -use common_utils::pii; -use error_stack::ResultExt; +use common_utils::{ + pii, + types::{MinorUnit, StringMajorUnit}, +}; use masking::Secret; use reqwest::Url; use serde::{Deserialize, Serialize}; -use super::utils as connector_utils; use crate::{ connector::utils::{self, is_payment_failure, CryptoData, PaymentsAuthorizeRequestData}, consts, @@ -15,31 +16,22 @@ use crate::{ #[derive(Debug, Serialize)] pub struct CryptopayRouterData<T> { - pub amount: String, + pub amount: StringMajorUnit, pub router_data: T, } -impl<T> TryFrom<(&types::api::CurrencyUnit, enums::Currency, i64, T)> for CryptopayRouterData<T> { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, - enums::Currency, - i64, - T, - ), - ) -> Result<Self, Self::Error> { - let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; - Ok(Self { +impl<T> From<(StringMajorUnit, T)> for CryptopayRouterData<T> { + fn from((amount, item): (StringMajorUnit, T)) -> Self { + Self { amount, router_data: item, - }) + } } } #[derive(Default, Debug, Serialize)] pub struct CryptopayPaymentsRequest { - price_amount: String, + price_amount: StringMajorUnit, price_currency: enums::Currency, pay_currency: String, #[serde(skip_serializing_if = "Option::is_none")] @@ -62,7 +54,7 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> domain::PaymentMethodData::Crypto(ref cryptodata) => { let pay_currency = cryptodata.get_pay_currency()?; Ok(Self { - price_amount: item.amount.to_owned(), + price_amount: item.amount.clone(), price_currency: item.router_data.request.currency, pay_currency, network: cryptodata.network.to_owned(), @@ -140,20 +132,20 @@ impl From<CryptopayPaymentStatus> for enums::AttemptStatus { #[derive(Debug, Serialize, Deserialize)] pub struct CryptopayPaymentsResponse { - data: CryptopayPaymentResponseData, + pub data: CryptopayPaymentResponseData, } impl<F, T> ForeignTryFrom<( types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>, - diesel_models::enums::Currency, + Option<MinorUnit>, )> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from( - (item, currency): ( + (item, amount_captured_in_minor_units): ( types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>, - diesel_models::enums::Currency, + Option<MinorUnit>, ), ) -> Result<Self, Self::Error> { let status = enums::AttemptStatus::from(item.response.data.status.clone()); @@ -196,15 +188,9 @@ impl<F, T> charge_id: None, }) }; - - match item.response.data.price_amount { - Some(price_amount) => { - let amount_captured = Some( - connector_utils::to_currency_lower_unit(price_amount, currency)? - .parse::<i64>() - .change_context(errors::ConnectorError::ParsingFailed)?, - ); - + match amount_captured_in_minor_units { + Some(minor_amount) => { + let amount_captured = Some(minor_amount.get_amount_as_i64()); Ok(Self { status, response, @@ -243,9 +229,9 @@ pub struct CryptopayPaymentResponseData { pub address: Option<Secret<String>>, pub network: Option<String>, pub uri: Option<String>, - pub price_amount: Option<String>, + pub price_amount: Option<StringMajorUnit>, pub price_currency: Option<String>, - pub pay_amount: Option<String>, + pub pay_amount: Option<StringMajorUnit>, pub pay_currency: Option<String>, pub fee: Option<String>, pub fee_currency: Option<String>, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index ee62b2ce551..498da04c6a2 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -329,7 +329,7 @@ impl ConnectorData { enums::Connector::Cashtocode => Ok(Box::new(&connector::Cashtocode)), enums::Connector::Checkout => Ok(Box::new(&connector::Checkout)), enums::Connector::Coinbase => Ok(Box::new(&connector::Coinbase)), - enums::Connector::Cryptopay => Ok(Box::new(&connector::Cryptopay)), + enums::Connector::Cryptopay => Ok(Box::new(connector::Cryptopay::new())), enums::Connector::Cybersource => Ok(Box::new(&connector::Cybersource)), enums::Connector::Dlocal => Ok(Box::new(&connector::Dlocal)), #[cfg(feature = "dummy_connector")] diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs index 20c727756e7..988c704249a 100644 --- a/crates/router/tests/connectors/cryptopay.rs +++ b/crates/router/tests/connectors/cryptopay.rs @@ -13,7 +13,7 @@ impl utils::Connector for CryptopayTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Cryptopay; api::ConnectorData { - connector: Box::new(&Cryptopay), + connector: Box::new(Cryptopay::new()), connector_name: types::Connector::Cryptopay, get_token: api::GetToken::Connector, merchant_connector_id: None,
2024-06-10T09:46:16Z
## Description <!-- Describe your changes in detail --> The conversion of a f64 base amount to i64 minor amount is causing parsing error in cryptopay. This needs to be fixed by using decimal type instead of f64. Also this Pr adds amount conversion framework to Cryptopay Note: Cryptopay uses String Major Unit ![image](https://github.com/juspay/hyperswitch/assets/41580413/54a9311f-6220-4675-a3c5-934ba6637c79) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/4929 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> We need to test Cryptopay payments for various different amounts. Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 115, "currency": "USD", "confirm": true, "email": "guest@example.com", "return_url": "https://google.com", "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_experience": "redirect_to_url", "payment_method_data": { "crypto": { "pay_currency": "LTC", "network": "litecoin" } } }' ``` Response: ``` { "payment_id": "pay_6xbLnqQCFF6t23vtANeX", "merchant_id": "merchant_1717926706", "status": "requires_customer_action", "amount": 115, "net_amount": 115, "amount_capturable": 115, "amount_received": 115, "connector": "cryptopay", "client_secret": "pay_6xbLnqQCFF6t23vtANeX_secret_YIJnRmmD1hu2YhtJ3rpR", "created": "2024-06-10T10:02:23.598Z", "currency": "USD", "customer_id": null, "customer": null, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "crypto", "payment_method_data": { "crypto": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_6xbLnqQCFF6t23vtANeX/merchant_1717926706/pay_6xbLnqQCFF6t23vtANeX_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": "redirect_to_url", "payment_method_type": "crypto_currency", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "a31c8590-3fc7-495c-91f0-392c3aa65b26", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_6xbLnqQCFF6t23vtANeX_1", "payment_link": null, "profile_id": "pro_kr0RocqcrWsWzyfCMsbV", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_cbz96DuLRCEdzUAd4syf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-10T10:17:23.598Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-06-10T10:02:24.390Z", "charges": null, "frm_metadata": null } ``` Note: Specifically test for amount 115.
7085a46271791ca3f1c7b86afa7c8b199b93c0cd
We need to test Cryptopay payments for various different amounts. Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 115, "currency": "USD", "confirm": true, "email": "guest@example.com", "return_url": "https://google.com", "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_experience": "redirect_to_url", "payment_method_data": { "crypto": { "pay_currency": "LTC", "network": "litecoin" } } }' ``` Response: ``` { "payment_id": "pay_6xbLnqQCFF6t23vtANeX", "merchant_id": "merchant_1717926706", "status": "requires_customer_action", "amount": 115, "net_amount": 115, "amount_capturable": 115, "amount_received": 115, "connector": "cryptopay", "client_secret": "pay_6xbLnqQCFF6t23vtANeX_secret_YIJnRmmD1hu2YhtJ3rpR", "created": "2024-06-10T10:02:23.598Z", "currency": "USD", "customer_id": null, "customer": null, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "crypto", "payment_method_data": { "crypto": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_6xbLnqQCFF6t23vtANeX/merchant_1717926706/pay_6xbLnqQCFF6t23vtANeX_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": "redirect_to_url", "payment_method_type": "crypto_currency", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "a31c8590-3fc7-495c-91f0-392c3aa65b26", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_6xbLnqQCFF6t23vtANeX_1", "payment_link": null, "profile_id": "pro_kr0RocqcrWsWzyfCMsbV", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_cbz96DuLRCEdzUAd4syf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-10T10:17:23.598Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-06-10T10:02:24.390Z", "charges": null, "frm_metadata": null } ``` Note: Specifically test for amount 115.
[ "crates/router/src/connector/cryptopay.rs", "crates/router/src/connector/cryptopay/transformers.rs", "crates/router/src/types/api.rs", "crates/router/tests/connectors/cryptopay.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4924
Bug: Add `is_connector_agnostic_mit_enabled` in the business profile APIs `is_connector_agnostic_mit_enabled` this filed is used to make connector agnostic MIT payments. If set to `true` the recurring payments (MIT) can be routed to any other connector which supports network transaction id flow. If it `false` the subsequent MITs needs to be routed trough the same connector as CIT. Hence adding support create and update the filed in business profile create, update and in business profile response.
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 58cb6fbf3e2..bd569b1febb 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -938,6 +938,12 @@ pub struct BusinessProfileCreate { /// A boolean value to indicate if customer shipping details needs to be sent for wallets payments pub collect_shipping_details_from_wallet_connector: Option<bool>, + + /// Indicates if the MIT (merchant initiated transaction) payments can be made connector + /// agnostic, i.e., MITs may be processed through different connector than CIT (customer + /// initiated transaction) based on the routing rules. + /// If set to `false`, MIT will go through the same connector as the CIT. + pub is_connector_agnostic_mit_enabled: Option<bool>, } #[derive(Clone, Debug, ToSchema, Serialize)] @@ -1016,6 +1022,12 @@ pub struct BusinessProfileResponse { /// A boolean value to indicate if customer shipping details needs to be sent for wallets payments pub collect_shipping_details_from_wallet_connector: Option<bool>, + + /// Indicates if the MIT (merchant initiated transaction) payments can be made connector + /// agnostic, i.e., MITs may be processed through different connector than CIT (customer + /// initiated transaction) based on the routing rules. + /// If set to `false`, MIT will go through the same connector as the CIT. + pub is_connector_agnostic_mit_enabled: Option<bool>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] @@ -1086,6 +1098,12 @@ pub struct BusinessProfileUpdate { /// A boolean value to indicate if customer shipping details needs to be sent for wallets payments pub collect_shipping_details_from_wallet_connector: Option<bool>, + + /// Indicates if the MIT (merchant initiated transaction) payments can be made connector + /// agnostic, i.e., MITs may be processed through different connector than CIT (customer + /// initiated transaction) based on the routing rules. + /// If set to `false`, MIT will go through the same connector as the CIT. + pub is_connector_agnostic_mit_enabled: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index fb1b62e5436..872bb0c09d6 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -124,6 +124,7 @@ pub enum BusinessProfileUpdate { extended_card_info_config: Option<pii::SecretSerdeValue>, use_billing_as_payment_method_billing: Option<bool>, collect_shipping_details_from_wallet_connector: Option<bool>, + is_connector_agnostic_mit_enabled: Option<bool>, }, ExtendedCardInfoUpdate { is_extended_card_info_enabled: Option<bool>, @@ -157,6 +158,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { extended_card_info_config, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, + is_connector_agnostic_mit_enabled, } => Self { profile_name, modified_at, @@ -178,6 +180,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { extended_card_info_config, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, + is_connector_agnostic_mit_enabled, ..Default::default() }, BusinessProfileUpdate::ExtendedCardInfoUpdate { diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index f9da9908d95..bd1b122f57c 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -442,6 +442,7 @@ pub async fn update_business_profile_cascade( extended_card_info_config: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, + is_connector_agnostic_mit_enabled: None, }; let update_futures = business_profiles.iter().map(|business_profile| async { @@ -1728,6 +1729,7 @@ pub async fn update_business_profile( use_billing_as_payment_method_billing: request.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: request .collect_shipping_details_from_wallet_connector, + is_connector_agnostic_mit_enabled: request.is_connector_agnostic_mit_enabled, }; let updated_business_profile = db diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 2e1032e8e4c..c77802a1503 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -277,6 +277,7 @@ pub async fn update_business_profile_active_algorithm_ref( extended_card_info_config: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, + is_connector_agnostic_mit_enabled: None, }; db.update_business_profile_by_profile_id(current_business_profile, business_profile_update) diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index b79819ed634..09c362c1164 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -87,6 +87,7 @@ impl ForeignTryFrom<storage::business_profile::BusinessProfile> for BusinessProf .transpose()?, collect_shipping_details_from_wallet_connector: item .collect_shipping_details_from_wallet_connector, + is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled, }) } } @@ -183,7 +184,7 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)> .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "authentication_connector_details", })?, - is_connector_agnostic_mit_enabled: None, + is_connector_agnostic_mit_enabled: request.is_connector_agnostic_mit_enabled, is_extended_card_info_enabled: None, extended_card_info_config: None, use_billing_as_payment_method_billing: request
2024-06-10T07:21:03Z
## Description <!-- Describe your changes in detail --> `is_connector_agnostic_mit_enabled` this field is used to make connector agnostic MIT payments. If set to `true` the recurring payments (MIT) can be routed to any other connector which supports network transaction id flow. If it `false` the subsequent MITs needs to be routed trough the same connector as CIT. Hence adding support create and update the filed in business profile create, update and in business profile response. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a merchant account -> Create a business profile under the above merchant account ``` curl --location 'http://localhost:8080/account/merchant_1718004259/business_profile' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "profile_name": "Pg_agnostic_mit", "collect_shipping_details_from_wallet_connector": true, "is_connector_agnostic_mit_enabled": true }' ``` Business profile create response <img width="926" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/42dbde60-18da-4d41-8fff-84fb2a19aa6e"> Field update in the db ![image](https://github.com/juspay/hyperswitch/assets/83439957/fcc8d6de-8704-4eae-8d2a-48d4104ae535) -> Update business profile ``` curl --location 'http://localhost:8080/account/merchant_1718004259/business_profile/pro_xmsxiQK2NBWahvXgWbmv' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "is_connector_agnostic_mit_enabled": false }' ``` Update business profile response <img width="574" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/275778c6-085a-4b6f-be0c-4eadfc66ba38"> Field updated in the db ![image](https://github.com/juspay/hyperswitch/assets/83439957/91ee9711-bea9-426a-9595-ee177975c48f)
ff93981ec776031af1de946cd6e9f90d2f410cd2
-> Create a merchant account -> Create a business profile under the above merchant account ``` curl --location 'http://localhost:8080/account/merchant_1718004259/business_profile' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "profile_name": "Pg_agnostic_mit", "collect_shipping_details_from_wallet_connector": true, "is_connector_agnostic_mit_enabled": true }' ``` Business profile create response <img width="926" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/42dbde60-18da-4d41-8fff-84fb2a19aa6e"> Field update in the db ![image](https://github.com/juspay/hyperswitch/assets/83439957/fcc8d6de-8704-4eae-8d2a-48d4104ae535) -> Update business profile ``` curl --location 'http://localhost:8080/account/merchant_1718004259/business_profile/pro_xmsxiQK2NBWahvXgWbmv' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "is_connector_agnostic_mit_enabled": false }' ``` Update business profile response <img width="574" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/275778c6-085a-4b6f-be0c-4eadfc66ba38"> Field updated in the db ![image](https://github.com/juspay/hyperswitch/assets/83439957/91ee9711-bea9-426a-9595-ee177975c48f)
[ "crates/api_models/src/admin.rs", "crates/diesel_models/src/business_profile.rs", "crates/router/src/core/admin.rs", "crates/router/src/core/routing/helpers.rs", "crates/router/src/types/api/admin.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4914
Bug: fix(payments): populate payments method data in list Populate payment method data in payments list to get details of card network.
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 49319dff3a2..abc1bdd0a1c 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -966,6 +966,15 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay attempt_count: pi.attempt_count, profile_id: pi.profile_id, merchant_connector_id: pa.merchant_connector_id, + payment_method_data: pa.payment_method_data.and_then(|data| { + match data.parse_value("PaymentMethodDataResponseWithBilling") { + Ok(parsed_data) => Some(parsed_data), + Err(e) => { + router_env::logger::error!("Failed to parse 'PaymentMethodDataResponseWithBilling' from payment method data. Error: {}", e); + None + } + } + }), ..Default::default() } }
2024-06-07T13:24:40Z
## Description Populate payment method data in payments list to get card network details. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes [#4914](https://github.com/juspay/hyperswitch/issues/4914) ## How did you test it? Tested with curl for payments list ``` curl --location 'http://localhost:8080/payments/list' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ; Cookie_1=value' \ --header 'Authorization: Bearer HWT' \ --data '{ "amount_filter": { "start_amount": 12600, "end_amount": 12600 } }' ``` Response ``` { "count": 1, "total_count": 1, "data": [ { "payment_id": "test_JUwD6r4ImcpnW9RhkWcN", "merchant_id": "merchant_1715344934", "status": "succeeded", "amount": 12600, "net_amount": 0, "amount_capturable": 12600, "amount_received": null, "connector": "paypal_test", "client_secret": "test_JUwD6r4ImcpnW9RhkWcN_secret_IRO8wJMTouwAUjAVcBg9", "created": "2024-06-02T05:43:07.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "customer": null, "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "30", "card_holder_name": "John", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_JUwD6r4ImcpnW9RhkWcN_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_IF0OamH2WybnNqqbgYWx", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null } ] } ``` <img width="802" alt="Screenshot 2024-06-07 at 6 52 30 PM" src="https://github.com/juspay/hyperswitch/assets/64925866/12432d43-5678-4025-a090-d1810b3d91c7">
d784fcb5e65060eb35424448b4762f09f83d532b
Tested with curl for payments list ``` curl --location 'http://localhost:8080/payments/list' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ; Cookie_1=value' \ --header 'Authorization: Bearer HWT' \ --data '{ "amount_filter": { "start_amount": 12600, "end_amount": 12600 } }' ``` Response ``` { "count": 1, "total_count": 1, "data": [ { "payment_id": "test_JUwD6r4ImcpnW9RhkWcN", "merchant_id": "merchant_1715344934", "status": "succeeded", "amount": 12600, "net_amount": 0, "amount_capturable": 12600, "amount_received": null, "connector": "paypal_test", "client_secret": "test_JUwD6r4ImcpnW9RhkWcN_secret_IRO8wJMTouwAUjAVcBg9", "created": "2024-06-02T05:43:07.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "customer": null, "description": "This is a sample payment", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "30", "card_holder_name": "John", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "test_JUwD6r4ImcpnW9RhkWcN_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_IF0OamH2WybnNqqbgYWx", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null } ] } ``` <img width="802" alt="Screenshot 2024-06-07 at 6 52 30 PM" src="https://github.com/juspay/hyperswitch/assets/64925866/12432d43-5678-4025-a090-d1810b3d91c7">
[ "crates/router/src/core/payments/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4475
Bug: Add tenant_id as a field for data pipeline 1. Add `Tenant_id` as a field for all logs 2. Add `Tenant_id` action for Kafka messages as well , headers to be a combination of ( tenant_id, merchant_id, payment_id ) 3. Make logical databases and physical tables in clickhouse for different tenants
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index c360b41a6cf..0545191318d 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1109,9 +1109,8 @@ impl QueueInterface for KafkaStore { entry_id: &RedisEntryId, fields: Vec<(&str, String)>, ) -> CustomResult<(), RedisError> { - let stream_name = format!("{}_{}", &self.tenant_id.0, stream); self.diesel_store - .stream_append_entry(&stream_name, entry_id, fields) + .stream_append_entry(stream, entry_id, fields) .await }
2024-06-07T12:32:22Z
## Description <!-- Describe your changes in detail --> As part of multitenancy feature, we added tenant prefix in the redisinterface directly. so this specific handling of tenant id in append_stream function is not required anymore ### 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). --> #4475 Remove tenant id from redis stream key of kafkaStore ## 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. Make a payment and see if the entries are added in process tracker 2. Check if the analytics for the payment is visible from the dashboard
d0fd7095cd4a433aa7eb51258303ef45008e28de
1. Make a payment and see if the entries are added in process tracker 2. Check if the analytics for the payment is visible from the dashboard
[ "crates/router/src/db/kafka_store.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4675
Bug: Add audit events for PaymentCapture update
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 447f7b92906..02c69681a88 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -12,6 +12,7 @@ use crate::{ errors::{self, RouterResult, StorageErrorExt}, payments::{self, helpers, operations, types::MultipleCaptureData}, }, + events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ @@ -255,7 +256,7 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRe async fn update_trackers<'b>( &'b self, db: &'b SessionState, - _req_state: ReqState, + req_state: ReqState, mut payment_data: payments::PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, @@ -294,6 +295,16 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRe } else { payment_data.payment_attempt }; + let capture_amount = payment_data.payment_attempt.amount_to_capture; + let multiple_capture_count = payment_data.payment_attempt.multiple_capture_count; + req_state + .event_context + .event(AuditEvent::new(AuditEventType::PaymentCapture { + capture_amount, + multiple_capture_count, + })) + .with(payment_data.to_event()) + .emit(); Ok((Box::new(self), payment_data)) } } diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs index 6fc19018655..367a573a93b 100644 --- a/crates/router/src/events/audit_events.rs +++ b/crates/router/src/events/audit_events.rs @@ -1,3 +1,4 @@ +use common_utils::types::MinorUnit; use diesel_models::fraud_check::FraudCheck; use events::{Event, EventInfo}; use serde::Serialize; @@ -22,6 +23,10 @@ pub enum AuditEventType { PaymentCancelled { cancellation_reason: Option<String>, }, + PaymentCapture { + capture_amount: Option<MinorUnit>, + multiple_capture_count: Option<i16>, + }, } #[derive(Debug, Clone, Serialize)] @@ -55,6 +60,7 @@ impl Event for AuditEvent { AuditEventType::PaymentConfirm { .. } => "payment_confirm", AuditEventType::ConnectorDecided => "connector_decided", AuditEventType::ConnectorCalled => "connector_called", + AuditEventType::PaymentCapture { .. } => "payment_capture", AuditEventType::RefundCreated => "refund_created", AuditEventType::RefundSuccess => "refund_success", AuditEventType::RefundFail => "refund_fail", diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 12da9e6765f..baa824ced3f 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -958,6 +958,9 @@ where } })?? }; + request_state + .event_context + .record_info(("tenant_id".to_string(), tenant_id.to_string())); // let tenant_id = "public".to_string(); let mut session_state = Arc::new(app_state.clone()).get_session_state(tenant_id.as_str(), || {
2024-06-07T11:15:30Z
## Description <!-- Describe your changes in detail --> Added an event each time a payment capture happens with the relevant contextual info - Pass along request_state to payment_core - Modify the UpdateTracker trait to accept request state - Modify the PaymentCapture implementation of UpdateTracker to generate an event - Showing the `capture_amount` and `multiple_capture_count` fields in the event - Added `tenant_id` field for the event ### 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 generate audit events whenever the payment state changes so we can get a brief overview without needing to comb through the logs. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Implemented an event trigger that activates whenever the payment capture API is utilized. This event triggers an audit event, the details of which are subsequently reflected in the Kafka UI. - Create a payment & then capture it. - Fields that need to be tested are: `capture_amount`, `multiple_capture_count` and `tenant_id`. ``` {"topic": "hyperswitch-audit-events"} ``` <img width="894" alt="Screenshot 2024-06-10 at 4 09 13 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/6bc8137f-6fa8-4fbe-8daa-e31360b9321d"> <img width="879" alt="Screenshot 2024-06-10 at 4 09 51 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/ee713dd5-f4ff-4c64-9442-ad07c5860dc9">
2119de9c1e6b1293a1eeff04010942895d7d5d4e
- Implemented an event trigger that activates whenever the payment capture API is utilized. This event triggers an audit event, the details of which are subsequently reflected in the Kafka UI. - Create a payment & then capture it. - Fields that need to be tested are: `capture_amount`, `multiple_capture_count` and `tenant_id`. ``` {"topic": "hyperswitch-audit-events"} ``` <img width="894" alt="Screenshot 2024-06-10 at 4 09 13 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/6bc8137f-6fa8-4fbe-8daa-e31360b9321d"> <img width="879" alt="Screenshot 2024-06-10 at 4 09 51 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/ee713dd5-f4ff-4c64-9442-ad07c5860dc9">
[ "crates/router/src/core/payments/operations/payment_capture.rs", "crates/router/src/events/audit_events.rs", "crates/router/src/services/api.rs" ]
juspay/hyperswitch
juspay__hyperswitch-5237
Bug: [FEAT] add key in keymanager [FEAT] add key in keymanager
diff --git a/config/config.example.toml b/config/config.example.toml index e4a15e7fb12..5a734237513 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -28,6 +28,10 @@ certificate = "/path/to/certificate.pem" idle_pool_connection_timeout = 90 # Timeout for idle pool connections (defaults to 90s) +# Configuration for the Key Manager Service +[key_manager] +url = "http://localhost:5000" # URL of the encryption service + # Main SQL data store credentials [master_database] username = "db_user" # DB Username diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 67f32396b74..3f7fb52f502 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -248,6 +248,10 @@ payment_intents = "hyperswitch-payment-intent-events" refunds = "hyperswitch-refund-events" disputes = "hyperswitch-dispute-events" +# Configuration for the Key Manager Service +[key_manager] +url = "http://localhost:5000" # URL of the encryption service + # This section provides some secret values. [secrets] master_enc_key = "sample_key" # Master Encryption key used to encrypt merchant wise encryption key. Should be 32-byte long. diff --git a/config/development.toml b/config/development.toml index b3548b35d06..23682ab1542 100644 --- a/config/development.toml +++ b/config/development.toml @@ -12,6 +12,9 @@ metrics_enabled = false use_xray_generator = false bg_metrics_collection_interval_in_secs = 15 +[key_manager] +url = "http://localhost:5000" + # TODO: Update database credentials before running application [master_database] username = "db_user" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index b11ca005741..10e5545c1bd 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -90,6 +90,9 @@ default_command_timeout = 30 unresponsive_timeout = 10 max_feed_count = 200 +[key_manager] +url = "http://localhost:5000" + [cors] max_age = 30 # origins = "http://localhost:8080,http://localhost:9000" diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index e9b84285847..ec9172b7fdf 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -994,6 +994,12 @@ pub struct ToggleKVResponse { pub kv_enabled: bool, } +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct TransferKeyResponse { + /// The identifier for the Merchant Account + #[schema(example = 32)] + pub total_transferred: usize, +} #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ToggleKVRequest { #[serde(skip_deserializing)] diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 4dcf1a3896a..3757dd98d78 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -80,6 +80,7 @@ impl_misc_api_event_type!( ToggleKVRequest, ToggleAllKVRequest, ToggleAllKVResponse, + TransferKeyResponse, MerchantAccountDeleteResponse, MerchantAccountUpdate, CardInfoResponse, diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index b357a3389d9..b8c893ae25d 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -20,7 +20,7 @@ use crate::user::{ SsoSignInRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse, TwoFactorAuthStatusResponse, UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate, - VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, + UserTransferKeyResponse, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -85,6 +85,7 @@ common_utils::impl_misc_api_event_type!( UpdateUserAuthenticationMethodRequest, GetSsoAuthUrlRequest, SsoSignInRequest, + UserTransferKeyResponse, AuthSelectRequest ); diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 43b476c9f67..7c0b21f9679 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -379,3 +379,8 @@ pub struct AuthIdQueryParam { pub struct AuthSelectRequest { pub id: Option<String>, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct UserTransferKeyResponse { + pub total_transferred: usize, +} diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index 45953210701..f6c3d8b6d0d 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -8,6 +8,8 @@ readme = "README.md" license.workspace = true [features] +keymanager = ["dep:router_env"] +keymanager_mtls = ["reqwest/rustls-tls"] signals = ["dep:signal-hook-tokio", "dep:signal-hook", "dep:tokio", "dep:router_env", "dep:futures"] async_ext = ["dep:async-trait", "dep:futures"] logs = ["dep:router_env"] diff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rs index d5e86985041..23b4f2be4fe 100644 --- a/crates/common_utils/src/errors.rs +++ b/crates/common_utils/src/errors.rs @@ -145,6 +145,42 @@ where } } +#[allow(missing_docs)] +#[derive(Debug, thiserror::Error)] +pub enum KeyManagerClientError { + #[error("Failed to construct header from the given value")] + FailedtoConstructHeader, + #[error("Failed to send request to Keymanager")] + RequestNotSent(String), + #[error("URL encoding of request failed")] + UrlEncodingFailed, + #[error("Failed to build the reqwest client ")] + ClientConstructionFailed, + #[error("Failed to send the request to Keymanager")] + RequestSendFailed, + #[error("Internal Server Error Received {0:?}")] + InternalServerError(bytes::Bytes), + #[error("Bad request received {0:?}")] + BadRequest(bytes::Bytes), + #[error("Unexpected Error occurred while calling the KeyManager")] + Unexpected(bytes::Bytes), + #[error("Response Decoding failed")] + ResponseDecodingFailed, +} + +#[allow(missing_docs)] +#[derive(Debug, thiserror::Error)] +pub enum KeyManagerError { + #[error("Failed to add key to the KeyManager")] + KeyAddFailed, + #[error("Failed to transfer the key to the KeyManager")] + KeyTransferFailed, + #[error("Failed to Encrypt the data in the KeyManager")] + EncryptionFailed, + #[error("Failed to Decrypt the data in the KeyManager")] + DecryptionFailed, +} + /// Allow [error_stack::Report] to convert between error types /// This auto-implements [ReportSwitchExt] for the corresponding errors pub trait ErrorSwitch<T> { diff --git a/crates/common_utils/src/keymanager.rs b/crates/common_utils/src/keymanager.rs new file mode 100644 index 00000000000..ecdb9b63ad5 --- /dev/null +++ b/crates/common_utils/src/keymanager.rs @@ -0,0 +1,175 @@ +//! Consists of all the common functions to use the Keymanager. + +use core::fmt::Debug; +use std::str::FromStr; + +use error_stack::ResultExt; +use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; +#[cfg(feature = "keymanager_mtls")] +use masking::PeekInterface; +use once_cell::sync::OnceCell; +use router_env::{instrument, logger, tracing}; + +use crate::{ + errors, + types::keymanager::{ + DataKeyCreateResponse, EncryptionCreateRequest, EncryptionTransferRequest, KeyManagerState, + }, +}; + +const CONTENT_TYPE: &str = "Content-Type"; +static ENCRYPTION_API_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); + +/// Get keymanager client constructed from the url and state +#[instrument(skip_all)] +#[allow(unused_mut)] +fn get_api_encryption_client( + state: &KeyManagerState, +) -> errors::CustomResult<reqwest::Client, errors::KeyManagerClientError> { + let get_client = || { + let mut client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .pool_idle_timeout(std::time::Duration::from_secs( + state.client_idle_timeout.unwrap_or_default(), + )); + + #[cfg(feature = "keymanager_mtls")] + { + let cert = state.cert.clone(); + let ca = state.ca.clone(); + + let identity = reqwest::Identity::from_pem(cert.peek().as_ref()) + .change_context(errors::KeyManagerClientError::ClientConstructionFailed)?; + let ca_cert = reqwest::Certificate::from_pem(ca.peek().as_ref()) + .change_context(errors::KeyManagerClientError::ClientConstructionFailed)?; + + client = client + .use_rustls_tls() + .identity(identity) + .add_root_certificate(ca_cert) + .https_only(true); + } + + client + .build() + .change_context(errors::KeyManagerClientError::ClientConstructionFailed) + }; + + Ok(ENCRYPTION_API_CLIENT.get_or_try_init(get_client)?.clone()) +} + +/// Generic function to send the request to keymanager +#[instrument(skip_all)] +pub async fn send_encryption_request<T>( + state: &KeyManagerState, + headers: HeaderMap, + url: String, + method: Method, + request_body: T, +) -> errors::CustomResult<reqwest::Response, errors::KeyManagerClientError> +where + T: serde::Serialize, +{ + let client = get_api_encryption_client(state)?; + let url = reqwest::Url::parse(&url) + .change_context(errors::KeyManagerClientError::UrlEncodingFailed)?; + + client + .request(method, url) + .json(&request_body) + .headers(headers) + .send() + .await + .change_context(errors::KeyManagerClientError::RequestNotSent( + "Unable to send request to encryption service".to_string(), + )) +} + +/// Generic function to call the Keymanager and parse the response back +#[instrument(skip_all)] +pub async fn call_encryption_service<T, R>( + state: &KeyManagerState, + method: Method, + endpoint: &str, + request_body: T, +) -> errors::CustomResult<R, errors::KeyManagerClientError> +where + T: serde::Serialize + Send + Sync + 'static + Debug, + R: serde::de::DeserializeOwned, +{ + let url = format!("{}/{endpoint}", &state.url); + + logger::info!(key_manager_request=?request_body); + + let response = send_encryption_request( + state, + HeaderMap::from_iter( + vec![( + HeaderName::from_str(CONTENT_TYPE) + .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, + HeaderValue::from_str("application/json") + .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, + )] + .into_iter(), + ), + url, + method, + request_body, + ) + .await + .map_err(|err| err.change_context(errors::KeyManagerClientError::RequestSendFailed))?; + + logger::info!(key_manager_response=?response); + + match response.status() { + StatusCode::OK => response + .json::<R>() + .await + .change_context(errors::KeyManagerClientError::ResponseDecodingFailed), + StatusCode::INTERNAL_SERVER_ERROR => { + Err(errors::KeyManagerClientError::InternalServerError( + response + .bytes() + .await + .change_context(errors::KeyManagerClientError::ResponseDecodingFailed)?, + ) + .into()) + } + StatusCode::BAD_REQUEST => Err(errors::KeyManagerClientError::BadRequest( + response + .bytes() + .await + .change_context(errors::KeyManagerClientError::ResponseDecodingFailed)?, + ) + .into()), + _ => Err(errors::KeyManagerClientError::Unexpected( + response + .bytes() + .await + .change_context(errors::KeyManagerClientError::ResponseDecodingFailed)?, + ) + .into()), + } +} + +/// A function to create the key in keymanager +#[instrument(skip_all)] +pub async fn create_key_in_key_manager( + state: &KeyManagerState, + request_body: EncryptionCreateRequest, +) -> errors::CustomResult<DataKeyCreateResponse, errors::KeyManagerError> { + call_encryption_service(state, Method::POST, "key/create", request_body) + .await + .change_context(errors::KeyManagerError::KeyAddFailed) +} + +/// A function to transfer the key in keymanager +#[instrument(skip_all)] +pub async fn transfer_key_to_key_manager( + state: &KeyManagerState, + request_body: EncryptionTransferRequest, +) -> errors::CustomResult<DataKeyCreateResponse, errors::KeyManagerError> { + call_encryption_service(state, Method::POST, "key/transfer", request_body) + .await + .change_context(errors::KeyManagerError::KeyTransferFailed) +} diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index 39826944a1b..9b339fb956e 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -19,6 +19,8 @@ pub mod events; pub mod ext_traits; pub mod fp_utils; pub mod id_type; +#[cfg(feature = "keymanager")] +pub mod keymanager; pub mod link_utils; pub mod macros; pub mod new_type; diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index f469a0299ff..02b49f52730 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -1,4 +1,6 @@ //! Types that can be used in other crates +pub mod keymanager; + use std::{ fmt::Display, ops::{Add, Sub}, diff --git a/crates/common_utils/src/types/keymanager.rs b/crates/common_utils/src/types/keymanager.rs new file mode 100644 index 00000000000..356ccdd4832 --- /dev/null +++ b/crates/common_utils/src/types/keymanager.rs @@ -0,0 +1,41 @@ +#![allow(missing_docs)] + +#[cfg(feature = "keymanager_mtls")] +use masking::Secret; +use serde::{Deserialize, Serialize}; + +#[derive(Debug)] +pub struct KeyManagerState { + pub url: String, + pub client_idle_timeout: Option<u64>, + #[cfg(feature = "keymanager_mtls")] + pub ca: Secret<String>, + #[cfg(feature = "keymanager_mtls")] + pub cert: Secret<String>, +} +#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] +#[serde(tag = "data_identifier", content = "key_identifier")] +pub enum Identifier { + User(String), + Merchant(String), +} + +#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] +pub struct EncryptionCreateRequest { + #[serde(flatten)] + pub identifier: Identifier, +} + +#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] +pub struct EncryptionTransferRequest { + #[serde(flatten)] + pub identifier: Identifier, + pub key: String, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct DataKeyCreateResponse { + #[serde(flatten)] + pub identifier: Identifier, + pub key_version: String, +} diff --git a/crates/diesel_models/src/query/merchant_key_store.rs b/crates/diesel_models/src/query/merchant_key_store.rs index 1be82cb2c18..fc4d09c4989 100644 --- a/crates/diesel_models/src/query/merchant_key_store.rs +++ b/crates/diesel_models/src/query/merchant_key_store.rs @@ -54,4 +54,20 @@ impl MerchantKeyStore { ) .await } + + pub async fn list_all_key_stores(conn: &PgPooledConn) -> StorageResult<Vec<Self>> { + generics::generic_filter::< + <Self as HasTable>::Table, + _, + <<Self as HasTable>::Table as diesel::Table>::PrimaryKey, + _, + >( + conn, + dsl::merchant_id.ne_all(vec!["".to_string()]), + None, + None, + None, + ) + .await + } } diff --git a/crates/diesel_models/src/query/user_key_store.rs b/crates/diesel_models/src/query/user_key_store.rs index 42dfe223b1a..5aad28bb562 100644 --- a/crates/diesel_models/src/query/user_key_store.rs +++ b/crates/diesel_models/src/query/user_key_store.rs @@ -14,6 +14,22 @@ impl UserKeyStoreNew { } impl UserKeyStore { + pub async fn get_all_user_key_stores(conn: &PgPooledConn) -> StorageResult<Vec<Self>> { + generics::generic_filter::< + <Self as HasTable>::Table, + _, + <<Self as HasTable>::Table as diesel::Table>::PrimaryKey, + _, + >( + conn, + dsl::user_id.ne_all(vec!["".to_string()]), + None, + None, + None, + ) + .await + } + pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index f23029e36d6..4373c7fb169 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -11,10 +11,12 @@ 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", "tls"] tls = ["actix-web/rustls-0_22"] +keymanager_mtls = ["reqwest/rustls-tls","common_utils/keymanager_mtls"] email = ["external_services/email", "scheduler/email", "olap"] +keymanager_create = [] frm = ["api_models/frm", "hyperswitch_domain_models/frm"] stripe = ["dep:serde_qs"] -release = ["stripe", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3"] +release = ["stripe", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3","keymanager_mtls","keymanager_create"] olap = ["hyperswitch_domain_models/olap", "storage_impl/olap", "scheduler/olap", "api_models/olap", "dep:analytics"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"] @@ -107,7 +109,7 @@ api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] analytics = { version = "0.1.0", path = "../analytics", optional = true } cards = { version = "0.1.0", path = "../cards" } common_enums = { version = "0.1.0", path = "../common_enums" } -common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics"] } +common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics","keymanager"] } hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } currency_conversion = { version = "0.1.0", path = "../currency_conversion" } hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index bab567899f5..819a5a06cb4 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -8810,3 +8810,15 @@ impl Default for super::settings::ApiKeys { } } } + +impl Default for super::settings::KeyManagerConfig { + fn default() -> Self { + Self { + url: String::from("localhost:5000"), + #[cfg(feature = "keymanager_mtls")] + ca: String::default().into(), + #[cfg(feature = "keymanager_mtls")] + cert: String::default().into(), + } + } +} diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 1ab2e519b7a..884feee9124 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -197,6 +197,35 @@ impl SecretsHandler for settings::PaymentMethodAuth { } } +#[async_trait::async_trait] +impl SecretsHandler for settings::KeyManagerConfig { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + _secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + #[cfg(feature = "keymanager_mtls")] + let keyconfig = value.get_inner(); + + #[cfg(feature = "keymanager_mtls")] + let ca = _secret_management_client + .get_secret(keyconfig.ca.clone()) + .await?; + + #[cfg(feature = "keymanager_mtls")] + let cert = _secret_management_client + .get_secret(keyconfig.cert.clone()) + .await?; + + Ok(value.transition_state(|keyconfig| Self { + #[cfg(feature = "keymanager_mtls")] + ca, + #[cfg(feature = "keymanager_mtls")] + cert, + ..keyconfig + })) + } +} + #[async_trait::async_trait] impl SecretsHandler for settings::Secrets { async fn convert_to_raw_secret( @@ -318,6 +347,14 @@ pub(crate) async fn fetch_raw_secrets( .await .expect("Failed to decrypt payment method auth configs"); + #[allow(clippy::expect_used)] + let key_manager = settings::KeyManagerConfig::convert_to_raw_secret( + conf.key_manager, + secret_management_client, + ) + .await + .expect("Failed to decrypt keymanager configs"); + #[allow(clippy::expect_used)] let user_auth_methods = settings::UserAuthMethodSettings::convert_to_raw_secret( conf.user_auth_methods, @@ -337,6 +374,7 @@ pub(crate) async fn fetch_raw_secrets( secrets_management: conf.secrets_management, proxy: conf.proxy, env: conf.env, + key_manager, #[cfg(feature = "olap")] replica_database, secrets, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index a29d7e1502d..33024a6e112 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -69,6 +69,7 @@ pub struct Settings<S: SecretState> { pub log: Log, pub secrets: SecretStateContainer<Secrets, S>, pub locker: Locker, + pub key_manager: SecretStateContainer<KeyManagerConfig, S>, pub connectors: Connectors, pub forex_api: SecretStateContainer<ForexApi, S>, pub refund: Refund, @@ -213,6 +214,15 @@ pub struct KvConfig { pub soft_kill: Option<bool>, } +#[derive(Debug, Deserialize, Clone)] +pub struct KeyManagerConfig { + pub url: String, + #[cfg(feature = "keymanager_mtls")] + pub cert: Secret<String>, + #[cfg(feature = "keymanager_mtls")] + pub ca: Secret<String>, +} + #[derive(Debug, Deserialize, Clone, Default)] pub struct GenericLink { pub payment_method_collect: GenericLinkEnvConfig, diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 7402d9730fd..5dc4e295919 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -14,6 +14,7 @@ pub mod connector_onboarding; pub mod currency; pub mod customers; pub mod disputes; +pub mod encryption; pub mod errors; pub mod files; #[cfg(feature = "frm")] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index dc72ec2ba89..67b3a05adb7 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -9,6 +9,8 @@ use common_utils::{ ext_traits::{AsyncExt, ConfigExt, Encode, ValueExt}, pii, }; +#[cfg(all(feature = "keymanager_create", feature = "olap"))] +use common_utils::{keymanager, types::keymanager as km_types}; use diesel_models::configs; use error_stack::{report, FutureExt, ResultExt}; use futures::future::try_join_all; @@ -22,6 +24,7 @@ use crate::types::transformers::ForeignFrom; use crate::{ consts, core::{ + encryption::transfer_encryption_key, errors::{self, RouterResponse, RouterResult, StorageErrorExt}, payments::helpers, routing::helpers as routing_helpers, @@ -125,6 +128,19 @@ pub async fn create_merchant_account( .create_domain_model_from_request(db, key_store.clone()) .await?; + #[cfg(feature = "keymanager_create")] + { + keymanager::create_key_in_key_manager( + &(&state).into(), + km_types::EncryptionCreateRequest { + identifier: km_types::Identifier::Merchant(merchant_id.clone()), + }, + ) + .await + .change_context(errors::ApiErrorResponse::DuplicateMerchantAccount) + .attach_printable("Failed to insert key to KeyManager")?; + } + db.insert_merchant_key_store(key_store.clone(), &master_key.to_vec().into()) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; @@ -2491,6 +2507,18 @@ pub(crate) fn validate_connector_auth_type( } } +pub async fn transfer_key_store_to_key_manager( + state: SessionState, +) -> RouterResponse<admin_types::TransferKeyResponse> { + let resp = transfer_encryption_key(&state).await?; + + Ok(service_api::ApplicationResponse::Json( + admin_types::TransferKeyResponse { + total_transferred: resp, + }, + )) +} + #[cfg(feature = "dummy_connector")] pub async fn validate_dummy_connector_enabled( state: &SessionState, diff --git a/crates/router/src/core/encryption.rs b/crates/router/src/core/encryption.rs new file mode 100644 index 00000000000..7f7945bfd1c --- /dev/null +++ b/crates/router/src/core/encryption.rs @@ -0,0 +1,55 @@ +use base64::Engine; +use common_utils::{ + keymanager::transfer_key_to_key_manager, + types::keymanager::{EncryptionTransferRequest, Identifier}, +}; +use error_stack::ResultExt; +use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; +use masking::ExposeInterface; + +use crate::{consts::BASE64_ENGINE, errors, types::domain::UserKeyStore, SessionState}; + +pub async fn transfer_encryption_key( + state: &SessionState, +) -> errors::CustomResult<usize, errors::ApiErrorResponse> { + let db = &*state.store; + let key_stores = db + .get_all_key_stores(&db.get_master_key().to_vec().into()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + send_request_to_key_service_for_merchant(state, key_stores).await +} + +pub async fn send_request_to_key_service_for_merchant( + state: &SessionState, + keys: Vec<MerchantKeyStore>, +) -> errors::CustomResult<usize, errors::ApiErrorResponse> { + futures::future::try_join_all(keys.into_iter().map(|key| async move { + let key_encoded = BASE64_ENGINE.encode(key.key.clone().into_inner().expose()); + let req = EncryptionTransferRequest { + identifier: Identifier::Merchant(key.merchant_id.clone()), + key: key_encoded, + }; + transfer_key_to_key_manager(&state.into(), req).await + })) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .map(|v| v.len()) +} + +pub async fn send_request_to_key_service_for_user( + state: &SessionState, + keys: Vec<UserKeyStore>, +) -> errors::CustomResult<usize, errors::ApiErrorResponse> { + futures::future::try_join_all(keys.into_iter().map(|key| async move { + let key_encoded = BASE64_ENGINE.encode(key.key.clone().into_inner().expose()); + let req = EncryptionTransferRequest { + identifier: Identifier::User(key.user_id.clone()), + key: key_encoded, + }; + transfer_key_to_key_manager(&state.into(), req).await + })) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .map(|v| v.len()) +} diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 2abcb5ea78b..bbc0336abcf 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -27,6 +27,7 @@ use super::errors::{StorageErrorExt, UserErrors, UserResponse, UserResult}; use crate::services::email::types as email_types; use crate::{ consts, + core::encryption::send_request_to_key_service_for_user, db::domain::user_authentication_method::DEFAULT_USER_AUTH_METHOD, routes::{app::ReqState, SessionState}, services::{authentication as auth, authorization::roles, openidconnect, ApplicationResponse}, @@ -1911,6 +1912,25 @@ pub async fn generate_recovery_codes( })) } +pub async fn transfer_user_key_store_keymanager( + state: SessionState, +) -> UserResponse<user_api::UserTransferKeyResponse> { + let db = &state.global_store; + + let key_stores = db + .get_all_user_key_store(&state.store.get_master_key().to_vec().into()) + .await + .change_context(UserErrors::InternalServerError)?; + + Ok(ApplicationResponse::Json( + user_api::UserTransferKeyResponse { + total_transferred: send_request_to_key_service_for_user(&state, key_stores) + .await + .change_context(UserErrors::InternalServerError)?, + }, + )) +} + pub async fn verify_recovery_code( state: SessionState, user_token: auth::UserIdFromAuth, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index edf8a53346c..ce0821c6322 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -2096,6 +2096,12 @@ impl MerchantKeyStoreInterface for KafkaStore { .list_multiple_key_stores(merchant_ids, key) .await } + async fn get_all_key_stores( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { + self.diesel_store.get_all_key_stores(key).await + } } #[async_trait::async_trait] @@ -2958,6 +2964,13 @@ impl UserKeyStoreInterface for KafkaStore { .get_user_key_store_by_user_id(user_id, key) .await } + + async fn get_all_user_key_store( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { + self.diesel_store.get_all_user_key_store(key).await + } } #[async_trait::async_trait] diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs index 77eb2609835..42a862e2d3d 100644 --- a/crates/router/src/db/merchant_key_store.rs +++ b/crates/router/src/db/merchant_key_store.rs @@ -40,6 +40,11 @@ pub trait MerchantKeyStoreInterface { merchant_ids: Vec<String>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>; + + async fn get_all_key_stores( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>; } #[async_trait::async_trait] @@ -163,6 +168,26 @@ impl MerchantKeyStoreInterface for Store { })) .await } + + async fn get_all_key_stores( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + let fetch_func = || async { + diesel_models::merchant_key_store::MerchantKeyStore::list_all_key_stores(&conn) + .await + .map_err(|err| report!(errors::StorageError::from(err))) + }; + + futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { + key_store + .convert(key) + .await + .change_context(errors::StorageError::DecryptionError) + })) + .await + } } #[async_trait::async_trait] @@ -251,6 +276,21 @@ impl MerchantKeyStoreInterface for MockDb { ) .await } + async fn get_all_key_stores( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { + let merchant_key_stores = self.merchant_key_store.lock().await; + + futures::future::try_join_all(merchant_key_stores.iter().map(|merchant_key| async { + merchant_key + .to_owned() + .convert(key) + .await + .change_context(errors::StorageError::DecryptionError) + })) + .await + } } #[cfg(test)] diff --git a/crates/router/src/db/user_key_store.rs b/crates/router/src/db/user_key_store.rs index e08d17d280e..c7e48037e96 100644 --- a/crates/router/src/db/user_key_store.rs +++ b/crates/router/src/db/user_key_store.rs @@ -27,6 +27,11 @@ pub trait UserKeyStoreInterface { user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError>; + + async fn get_all_user_key_store( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError>; } #[async_trait::async_trait] @@ -65,6 +70,27 @@ impl UserKeyStoreInterface for Store { .await .change_context(errors::StorageError::DecryptionError) } + + async fn get_all_user_key_store( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + + let fetch_func = || async { + diesel_models::user_key_store::UserKeyStore::get_all_user_key_stores(&conn) + .await + .map_err(|err| report!(errors::StorageError::from(err))) + }; + + futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { + key_store + .convert(key) + .await + .change_context(errors::StorageError::DecryptionError) + })) + .await + } } #[async_trait::async_trait] @@ -98,6 +124,22 @@ impl UserKeyStoreInterface for MockDb { .change_context(errors::StorageError::DecryptionError) } + async fn get_all_user_key_store( + &self, + key: &Secret<Vec<u8>>, + ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { + let user_key_store = self.user_key_store.lock().await; + + futures::future::try_join_all(user_key_store.iter().map(|user_key| async { + user_key + .to_owned() + .convert(key) + .await + .change_context(errors::StorageError::DecryptionError) + })) + .await + } + #[instrument(skip_all)] async fn get_user_key_store_by_user_id( &self, diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 3f08834e441..da12c98c77e 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -446,16 +446,16 @@ pub async fn merchant_account_toggle_kv( .await } -/// Merchant Account - Toggle KV +/// Merchant Account - Transfer Keys /// -/// Toggle KV mode for all Merchant Accounts +/// Transfer Merchant Encryption key to keymanager #[instrument(skip_all)] pub async fn merchant_account_toggle_all_kv( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<admin::ToggleAllKVRequest>, ) -> HttpResponse { - let flow = Flow::ConfigKeyUpdate; + let flow = Flow::MerchantTransferKey; let payload = json_payload.into_inner(); api::server_wrap( @@ -651,6 +651,27 @@ pub async fn merchant_account_kv_status( .await } +/// Merchant Account - KV Status +/// +/// Toggle KV mode for the Merchant Account +#[instrument(skip_all)] +pub async fn merchant_account_transfer_keys( + state: web::Data<AppState>, + req: HttpRequest, +) -> HttpResponse { + let flow = Flow::ConfigKeyFetch; + api::server_wrap( + flow, + state, + &req, + (), + |state, _, _, _| transfer_key_store_to_key_manager(state), + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + ) + .await +} + #[instrument(skip_all, fields(flow = ?Flow::ToggleExtendedCardInfo))] pub async fn toggle_extended_card_info( state: web::Data<AppState>, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 797de75dfcf..d82f98f295d 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1028,6 +1028,9 @@ impl MerchantAccount { .route(web::post().to(merchant_account_toggle_kv)) .route(web::get().to(merchant_account_kv_status)), ) + .service( + web::resource("/transfer").route(web::post().to(merchant_account_transfer_keys)), + ) .service(web::resource("/kv").route(web::post().to(merchant_account_toggle_all_kv))) .service( web::resource("/{id}") @@ -1398,6 +1401,11 @@ impl User { .route(web::post().to(set_dashboard_metadata)), ); + route = route.service( + web::scope("/key") + .service(web::resource("/transfer").route(web::post().to(transfer_user_key))), + ); + // Two factor auth routes route = route.service( web::scope("/2fa") diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 56e8751a979..8f0c1aa804c 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -45,6 +45,7 @@ impl From<Flow> for ApiIdentifier { | Flow::MerchantsAccountRetrieve | Flow::MerchantsAccountUpdate | Flow::MerchantsAccountDelete + | Flow::MerchantTransferKey | Flow::MerchantAccountList => Self::MerchantAccount, Flow::RoutingCreateConfig @@ -233,6 +234,7 @@ impl From<Flow> for ApiIdentifier { | Flow::CreateUserAuthenticationMethod | Flow::UpdateUserAuthenticationMethod | Flow::ListUserAuthenticationMethods + | Flow::UserTransferKey | Flow::GetSsoAuthUrl | Flow::SignInWithSso | Flow::AuthSelect => Self::User, diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 7e55393cc57..29935bc8ab7 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -895,3 +895,18 @@ pub async fn terminate_auth_select( )) .await } + +pub async fn transfer_user_key(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { + let flow = Flow::UserTransferKey; + + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + (), + |state, _, _, _| user_core::transfer_user_key_store_keymanager(state), + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rs index 176b88b3f5b..151ae61f5fe 100644 --- a/crates/router/src/types/domain/types.rs +++ b/crates/router/src/types/domain/types.rs @@ -1,3 +1,18 @@ +use common_utils::types::keymanager::KeyManagerState; pub use hyperswitch_domain_models::type_encryption::{ decrypt, encrypt, encrypt_optional, AsyncLift, Lift, TypeEncryption, }; + +impl From<&crate::SessionState> for KeyManagerState { + fn from(state: &crate::SessionState) -> Self { + let conf = state.conf.key_manager.get_inner(); + Self { + url: conf.url.clone(), + client_idle_timeout: state.conf.proxy.idle_pool_connection_timeout, + #[cfg(feature = "keymanager_mtls")] + cert: conf.cert.clone(), + #[cfg(feature = "keymanager_mtls")] + ca: conf.ca.clone(), + } + } +} diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index d5100c89c19..c4c67796d46 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -6,6 +6,8 @@ use api_models::{ use common_enums::TokenPurpose; #[cfg(not(feature = "v2"))] use common_utils::id_type; +#[cfg(feature = "keymanager_create")] +use common_utils::types::keymanager::{EncryptionCreateRequest, Identifier}; use common_utils::{crypto::Encryptable, errors::CustomResult, new_type::MerchantName, pii}; use diesel_models::{ enums::{TotpStatus, UserStatus}, @@ -971,6 +973,19 @@ impl UserFromStorage { .change_context(UserErrors::InternalServerError)?, created_at: common_utils::date_time::now(), }; + + #[cfg(feature = "keymanager_create")] + { + common_utils::keymanager::create_key_in_key_manager( + &state.into(), + EncryptionCreateRequest { + identifier: Identifier::User(key_store.user_id.clone()), + }, + ) + .await + .change_context(UserErrors::InternalServerError)?; + } + state .global_store .insert_user_key_store(key_store, &master_key.to_vec().into()) diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 2fef21d420c..8ff019f9b5f 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -81,6 +81,8 @@ pub enum Flow { MerchantConnectorsDelete, /// Merchant Connectors list flow. MerchantConnectorsList, + /// Merchant Transfer Keys + MerchantTransferKey, /// ConfigKey create flow. ConfigKeyCreate, /// ConfigKey fetch flow. @@ -316,6 +318,8 @@ pub enum Flow { UserSignUpWithMerchantId, /// User Sign In UserSignIn, + /// User transfer key + UserTransferKey, /// User connect account UserConnectAccount, /// Upsert Decision Manager Config diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 2f1aa1dbbd8..f38cd05e7c4 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -9,6 +9,9 @@ traces_enabled = true metrics_enabled = true ignore_errors = false +[key_manager] +url = "http://localhost:5000" + [master_database] username = "postgres" password = "postgres" @@ -339,4 +342,4 @@ 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"} \ No newline at end of file +public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"}
2024-06-07T09:50:00Z
## Description <!-- Describe your changes in detail --> This PR adds support to - Create Key for every User and Merchant during User and Merchant Account Create. - Add an API to transfer Keys to KeyManager - Add MTLS for KeyManager Client ### Additional Changes - [x] This PR modifies application configuration/environment variables ## 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). --> - Create Key in Key Manager for every merchant ## 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)? --> ### Tests for Create a Merchant - ```bash curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "merchant_id": "merchant_1720435957", "locker_id": "m0010", "merchant_name": "NewAge Retailer", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "JohnTest@test.com", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "JohnTest2@test.com", "secondary_phone": "cillum do dolor id", "website": "www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` - Verify `/key/create` to Keymanager was succeeded. The response status of `keymanager_response` should be 200 <img width="1334" alt="Screenshot 2024-07-11 at 5 01 27 PM" src="https://github.com/juspay/hyperswitch/assets/43412619/95dcf641-0908-4f4d-8803-53e435906220"> ### Create Key for User - Signin with the account and password ``` curl --location 'http://localhost:8080/user/v2/signin?token_only=true' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "gagagagag@gagagagagag.com", "password": "gagagagag@1234" }' ``` - Begin TOTP flow ``` curl --location 'http://localhost:8080/user/2fa/totp/begin' \ --header 'Authorization: Bearer spt' ``` - Verify that call to `/key/create` is successful in the logs
998ce02ebc1eed10e426987d1af9c02d1f1735fe
### Tests for Create a Merchant - ```bash curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "merchant_id": "merchant_1720435957", "locker_id": "m0010", "merchant_name": "NewAge Retailer", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "JohnTest@test.com", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "JohnTest2@test.com", "secondary_phone": "cillum do dolor id", "website": "www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` - Verify `/key/create` to Keymanager was succeeded. The response status of `keymanager_response` should be 200 <img width="1334" alt="Screenshot 2024-07-11 at 5 01 27 PM" src="https://github.com/juspay/hyperswitch/assets/43412619/95dcf641-0908-4f4d-8803-53e435906220"> ### Create Key for User - Signin with the account and password ``` curl --location 'http://localhost:8080/user/v2/signin?token_only=true' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "gagagagag@gagagagagag.com", "password": "gagagagag@1234" }' ``` - Begin TOTP flow ``` curl --location 'http://localhost:8080/user/2fa/totp/begin' \ --header 'Authorization: Bearer spt' ``` - Verify that call to `/key/create` is successful in the logs
[ "config/config.example.toml", "config/deployments/env_specific.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/src/admin.rs", "crates/api_models/src/events.rs", "crates/api_models/src/events/user.rs", "crates/api_models/src/user.rs", "crates/common_utils/Cargo.toml...
juspay/hyperswitch
juspay__hyperswitch-5292
Bug: [REFACTOR] List the Payment Methods Based on the Connector Type ### Feature Description List the Payment Methods Based on the Connector Type being Payment Processor ### Possible Implementation List the Payment Methods Based on the Connector Type being Payment Processor ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
2024-06-07T09:14:30Z
## Description List the Payment Methods for Merchant , based on the connector type, to differentiate between Payments and Payouts Processors ### 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 - Create two MCA , one with the `connector_type : "payment_processor"` other with the connector type as `payout_processor` - Create a payment - Do a list of Pms for the Merchant Account, BOA would not be here as its connector_type is `payout_processor`, cause here only the PMs with `payment_processor` would get listed ``` { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "stripe" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": {}, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "stripe" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "JCB", "surcharge_details": null, "eligible_connectors": [ "stripe" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "new_mandate", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false } ```
37e34e3bfde9281b3a69b0769c901a887dcf400f
- Create a MA - Create two MCA , one with the `connector_type : "payment_processor"` other with the connector type as `payout_processor` - Create a payment - Do a list of Pms for the Merchant Account, BOA would not be here as its connector_type is `payout_processor`, cause here only the PMs with `payment_processor` would get listed ``` { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "stripe" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": {}, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "stripe" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "JCB", "surcharge_details": null, "eligible_connectors": [ "stripe" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "new_mandate", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false } ```
[]
juspay/hyperswitch
juspay__hyperswitch-4901
Bug: refactor(user): Make password nullable for `users` Currently `password` is required field in `users` table. This is causing us to create temporary passwords for `users` in some APIs which inserts `users` without password. So, we have to make password nullable to solve this.
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 15e662fe438..a7d5a8c02bc 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1223,7 +1223,7 @@ diesel::table! { #[max_length = 255] name -> Varchar, #[max_length = 255] - password -> Varchar, + password -> Nullable<Varchar>, is_verified -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs index 6a040e41468..b1bbb66256c 100644 --- a/crates/diesel_models/src/user.rs +++ b/crates/diesel_models/src/user.rs @@ -17,7 +17,7 @@ pub struct User { pub user_id: String, pub email: pii::Email, pub name: Secret<String>, - pub password: Secret<String>, + pub password: Option<Secret<String>>, pub is_verified: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, @@ -37,7 +37,7 @@ pub struct UserNew { pub user_id: String, pub email: pii::Email, pub name: Secret<String>, - pub password: Secret<String>, + pub password: Option<Secret<String>>, pub is_verified: bool, pub created_at: Option<PrimitiveDateTime>, pub last_modified_at: Option<PrimitiveDateTime>, @@ -76,7 +76,7 @@ pub enum UserUpdate { totp_recovery_codes: Option<Vec<Secret<String>>>, }, PasswordUpdate { - password: Option<Secret<String>>, + password: Secret<String>, }, } @@ -127,7 +127,7 @@ impl From<UserUpdate> for UserUpdateInternal { }, UserUpdate::PasswordUpdate { password } => Self { name: None, - password, + password: Some(password), is_verified: None, last_modified_at, preferred_merchant_id: None, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index a4bb4fb4b03..c78f2c8080f 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -368,7 +368,7 @@ pub async fn change_password( .update_user_by_user_id( user.get_user_id(), diesel_models::user::UserUpdate::PasswordUpdate { - password: Some(new_password_hash), + password: new_password_hash, }, ) .await @@ -459,7 +459,7 @@ pub async fn rotate_password( .update_user_by_user_id( &user_token.user_id, storage_user::UserUpdate::PasswordUpdate { - password: Some(hash_password), + password: hash_password, }, ) .await @@ -510,7 +510,7 @@ pub async fn reset_password_token_only_flow( .get_email() .change_context(UserErrors::InternalServerError)?, storage_user::UserUpdate::PasswordUpdate { - password: Some(hash_password), + password: hash_password, }, ) .await @@ -548,7 +548,7 @@ pub async fn reset_password( .get_email() .change_context(UserErrors::InternalServerError)?, storage_user::UserUpdate::PasswordUpdate { - password: Some(hash_password), + password: hash_password, }, ) .await @@ -838,11 +838,9 @@ async fn handle_new_user_invitation( Ok(InviteMultipleUserResponse { is_email_sent, - password: if cfg!(not(feature = "email")) { - Some(new_user.get_password().get_secret()) - } else { - None - }, + password: new_user + .get_password() + .map(|password| password.get_secret()), email: request.email.clone(), error: None, }) diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs index e8104e3a155..742944bd1e0 100644 --- a/crates/router/src/db/user.rs +++ b/crates/router/src/db/user.rs @@ -244,7 +244,7 @@ impl UserInterface for MockDb { ..user.to_owned() }, storage::UserUpdate::PasswordUpdate { password } => storage::User { - password: password.clone().unwrap_or(user.password.clone()), + password: Some(password.clone()), last_password_modified_at: Some(common_utils::date_time::now()), ..user.to_owned() }, @@ -299,7 +299,7 @@ impl UserInterface for MockDb { ..user.to_owned() }, storage::UserUpdate::PasswordUpdate { password } => storage::User { - password: password.clone().unwrap_or(user.password.clone()), + password: Some(password.clone()), last_password_modified_at: Some(common_utils::date_time::now()), ..user.to_owned() }, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index d9ef736347f..47f26ce04e5 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -1,8 +1,4 @@ -use std::{ - collections::HashSet, - ops::{self, Not}, - str::FromStr, -}; +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, @@ -517,9 +513,8 @@ pub struct NewUser { user_id: String, name: UserName, email: UserEmail, - password: UserPassword, + password: Option<UserPassword>, new_merchant: NewUserMerchant, - is_temporary_password: bool, } impl NewUser { @@ -539,7 +534,7 @@ impl NewUser { self.new_merchant.clone() } - pub fn get_password(&self) -> UserPassword { + pub fn get_password(&self) -> Option<UserPassword> { self.password.clone() } @@ -623,7 +618,12 @@ impl TryFrom<NewUser> for storage_user::UserNew { type Error = error_stack::Report<UserErrors>; fn try_from(value: NewUser) -> UserResult<Self> { - let hashed_password = password::generate_password_hash(value.password.get_secret())?; + let hashed_password = value + .password + .as_ref() + .map(|password| password::generate_password_hash(password.get_secret())) + .transpose()?; + let now = common_utils::date_time::now(); Ok(Self { user_id: value.get_user_id(), @@ -637,7 +637,7 @@ impl TryFrom<NewUser> for storage_user::UserNew { totp_status: TotpStatus::NotSet, totp_secret: None, totp_recovery_codes: None, - last_password_modified_at: value.is_temporary_password.not().then_some(now), + last_password_modified_at: value.password.is_some().then_some(now), }) } } @@ -655,10 +655,9 @@ impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUser { Ok(Self { name, email, - password, + password: Some(password), user_id, new_merchant, - is_temporary_password: false, }) } } @@ -677,9 +676,8 @@ impl TryFrom<user_api::SignUpRequest> for NewUser { user_id, name, email, - password, + password: Some(password), new_merchant, - is_temporary_password: false, }) } } @@ -691,16 +689,14 @@ impl TryFrom<user_api::ConnectAccountRequest> for NewUser { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.email.clone().try_into()?; let name = UserName::try_from(value.email.clone())?; - let password = UserPassword::new(password::get_temp_password())?; let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self { user_id, name, email, - password, + password: None, new_merchant, - is_temporary_password: true, }) } } @@ -721,9 +717,8 @@ impl TryFrom<(user_api::CreateInternalUserRequest, String)> for NewUser { user_id, name, email, - password, + password: Some(password), new_merchant, - is_temporary_password: false, }) } } @@ -739,11 +734,12 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUser { user_id: user.0.user_id, name: UserName::new(user.0.name)?, email: user.0.email.clone().try_into()?, - password: UserPassword::new_password_without_validation(user.0.password)?, + password: user + .0 + .password + .map(UserPassword::new_password_without_validation) + .transpose()?, new_merchant, - // This is true because we are not creating a user with this request. And if it is set - // to false, last_password_modified_at will be overwritten if this user is inserted. - is_temporary_password: true, }) } } @@ -754,7 +750,8 @@ impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.0.email.clone().try_into()?; let name = UserName::new(value.0.name.clone())?; - let password = UserPassword::new(password::get_temp_password())?; + let password = cfg!(not(feature = "email")) + .then_some(UserPassword::new(password::get_temp_password())?); let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self { @@ -763,7 +760,6 @@ impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser { email, password, new_merchant, - is_temporary_password: true, }) } } @@ -783,10 +779,14 @@ impl UserFromStorage { } pub fn compare_password(&self, candidate: &Secret<String>) -> UserResult<()> { - match password::is_correct_password(candidate, &self.0.password) { - Ok(true) => Ok(()), - Ok(false) => Err(UserErrors::InvalidCredentials.into()), - Err(e) => Err(e), + if let Some(password) = self.0.password.as_ref() { + match password::is_correct_password(candidate, password) { + Ok(true) => Ok(()), + Ok(false) => Err(UserErrors::InvalidCredentials.into()), + Err(e) => Err(e), + } + } else { + Err(UserErrors::InvalidCredentials.into()) } } diff --git a/migrations/2024-06-06-101812_user_optional_password/down.sql b/migrations/2024-06-06-101812_user_optional_password/down.sql new file mode 100644 index 00000000000..acd0b1efca3 --- /dev/null +++ b/migrations/2024-06-06-101812_user_optional_password/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE users ALTER COLUMN password SET NOT NULL; diff --git a/migrations/2024-06-06-101812_user_optional_password/up.sql b/migrations/2024-06-06-101812_user_optional_password/up.sql new file mode 100644 index 00000000000..e48b1b751ab --- /dev/null +++ b/migrations/2024-06-06-101812_user_optional_password/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE users ALTER COLUMN password DROP NOT NULL;
2024-06-06T14:12:11Z
## Description <!-- Describe your changes in detail --> This API will make the password column in the `users` table nullable. ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #4901. ## 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 user with `connect_account` API ``` curl --location 'http://localhost:8080/user/connect_account' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "unregistered email" }' ``` 2. Invite a unregistered user ``` curl --location 'http://localhost:8080/user/user/invite_multiple' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data-raw '[ { "email": "new user email", "name": "name", "role_id": "merchant_view_only" } ]' ``` 3. Check the DB entry for those users using the following query ```sql select * from users where email = 'email used in previous API' ``` Password should be null in all the cases.
2f12cca7ae5a4875b50ca5ff5068500b5004eb6f
1. Create user with `connect_account` API ``` curl --location 'http://localhost:8080/user/connect_account' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "unregistered email" }' ``` 2. Invite a unregistered user ``` curl --location 'http://localhost:8080/user/user/invite_multiple' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data-raw '[ { "email": "new user email", "name": "name", "role_id": "merchant_view_only" } ]' ``` 3. Check the DB entry for those users using the following query ```sql select * from users where email = 'email used in previous API' ``` Password should be null in all the cases.
[ "crates/diesel_models/src/schema.rs", "crates/diesel_models/src/user.rs", "crates/router/src/core/user.rs", "crates/router/src/db/user.rs", "crates/router/src/types/domain/user.rs", "migrations/2024-06-06-101812_user_optional_password/down.sql", "migrations/2024-06-06-101812_user_optional_password/up.sq...
juspay/hyperswitch
juspay__hyperswitch-4899
Bug: [BUG] : [BOA/CYBS] make AVS code optional ### Bug Description AVS code is mandatory, but in some cases it is not sent ### Expected Behavior AVS code must be optional ### Actual Behavior Incases where, AVS code is not sent results in a de serialization error ### 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/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 7446749e73c..edff5c251a5 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -835,7 +835,7 @@ pub struct ClientRiskInformationRules { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Avs { - code: String, + code: Option<String>, code_raw: Option<String>, } diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 3250cb1ba81..ceb0b4ad47f 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1766,7 +1766,7 @@ pub struct CardVerification { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Avs { - code: String, + code: Option<String>, code_raw: Option<String>, }
2024-06-06T10:39:31Z
## Description <!-- Describe your changes in detail --> Make AVS code optional ## 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. Do a non 3ds payment - Sanity ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_K5SsEmIckmis20oeONswdh8Cu58ZuXrNLCLIzyXNhhJLiHeeo600vhMovaKi81F0' \ --data-raw '{ "amount": 10000000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "CustomerX", "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": "HK", "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": "13.232.74.226" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "HK", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, }' ``` Response ``` { "payment_id": "pay_tLDEYk3yTxDzmriMmZpO", "merchant_id": "merchant_1717669788", "status": "succeeded", "amount": 10000000, "net_amount": 10000000, "amount_capturable": 0, "amount_received": 10000000, "connector": "bankofamerica", "client_secret": "pay_tLDEYk3yTxDzmriMmZpO_secret_Tq8g1rglsndzsxSbzAdy", "created": "2024-06-06T10:29:59.899Z", "currency": "USD", "customer_id": "CustomerX", "customer": { "id": "CustomerX", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": null, "approval_code": "831000", "consumer_authentication_response": null, "cavv": null, "eci": null, "eci_raw": null }, "authentication_data": { "retrieval_reference_number": null, "acs_transaction_id": null, "system_trace_audit_number": null } }, "billing": null }, "payment_token": "token_Pt4Kz5hHqT5uz2i73poe", "shipping": { "address": { "city": "San Fransico", "country": "HK", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "HK", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "CustomerX", "created_at": 1717669799, "expires": 1717673399, "secret": "epk_e476f9f1f32843a387e66335a9720879" }, "manual_retry_allowed": false, "connector_transaction_id": "7176698015826287804953", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pay_tLDEYk3yTxDzmriMmZpO_1", "payment_link": null, "profile_id": "pro_VeTh8fChUYxqqKXvsFPk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_WvNBAlqHk4oB7Ke89Rwq", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-06T10:44:59.899Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "13.232.74.226", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": "pm_bqI6UMJ2WNmu1j6aYuhZ", "payment_method_status": null, "updated": "2024-06-06T10:30:04.394Z", "charges": null, "frm_metadata": null } ``` _Note: Scenario when connector do not send avs code is random_
9903119e8b1f2c08ee99e630c1c64cdeb7c34df4
1. Do a non 3ds payment - Sanity ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_K5SsEmIckmis20oeONswdh8Cu58ZuXrNLCLIzyXNhhJLiHeeo600vhMovaKi81F0' \ --data-raw '{ "amount": 10000000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "CustomerX", "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": "HK", "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": "13.232.74.226" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "HK", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, }' ``` Response ``` { "payment_id": "pay_tLDEYk3yTxDzmriMmZpO", "merchant_id": "merchant_1717669788", "status": "succeeded", "amount": 10000000, "net_amount": 10000000, "amount_capturable": 0, "amount_received": 10000000, "connector": "bankofamerica", "client_secret": "pay_tLDEYk3yTxDzmriMmZpO_secret_Tq8g1rglsndzsxSbzAdy", "created": "2024-06-06T10:29:59.899Z", "currency": "USD", "customer_id": "CustomerX", "customer": { "id": "CustomerX", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": null, "approval_code": "831000", "consumer_authentication_response": null, "cavv": null, "eci": null, "eci_raw": null }, "authentication_data": { "retrieval_reference_number": null, "acs_transaction_id": null, "system_trace_audit_number": null } }, "billing": null }, "payment_token": "token_Pt4Kz5hHqT5uz2i73poe", "shipping": { "address": { "city": "San Fransico", "country": "HK", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "HK", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "CustomerX", "created_at": 1717669799, "expires": 1717673399, "secret": "epk_e476f9f1f32843a387e66335a9720879" }, "manual_retry_allowed": false, "connector_transaction_id": "7176698015826287804953", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pay_tLDEYk3yTxDzmriMmZpO_1", "payment_link": null, "profile_id": "pro_VeTh8fChUYxqqKXvsFPk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_WvNBAlqHk4oB7Ke89Rwq", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-06T10:44:59.899Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "13.232.74.226", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": "pm_bqI6UMJ2WNmu1j6aYuhZ", "payment_method_status": null, "updated": "2024-06-06T10:30:04.394Z", "charges": null, "frm_metadata": null } ``` _Note: Scenario when connector do not send avs code is random_
[ "crates/router/src/connector/bankofamerica/transformers.rs", "crates/router/src/connector/cybersource/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4896
Bug: ci(postman): add test collection for users Add testcases to test - Singnin flow - Singup flow (magic account) Also include token only cases for sign in signup.
diff --git a/Cargo.lock b/Cargo.lock index 228414c0194..77f9b33ddc4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7021,6 +7021,7 @@ dependencies = [ name = "test_utils" version = "0.1.0" dependencies = [ + "anyhow", "async-trait", "base64 0.22.0", "clap", diff --git a/crates/test_utils/Cargo.toml b/crates/test_utils/Cargo.toml index 3b0dfe2b91d..6d8663c0300 100644 --- a/crates/test_utils/Cargo.toml +++ b/crates/test_utils/Cargo.toml @@ -14,6 +14,7 @@ payouts = [] [dependencies] async-trait = "0.1.79" +anyhow = "1.0.81" base64 = "0.22.0" clap = { version = "4.4.18", default-features = false, features = ["std", "derive", "help", "usage"] } rand = "0.8.5" diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 3ba321c174e..4b41506fe2d 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -76,6 +76,7 @@ pub struct ConnectorAuthentication { pub zen: Option<HeaderKey>, pub zsl: Option<BodyKey>, pub automation_configs: Option<AutomationConfigs>, + pub users: Option<UsersConfigs>, } impl Default for ConnectorAuthentication { @@ -339,3 +340,12 @@ pub enum ConnectorAuthType { #[default] NoKey, } + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct UsersConfigs { + pub user_email: String, + pub user_password: String, + pub wrong_password: String, + pub user_base_email_for_signup: String, + pub user_domain_for_signup: String, +} diff --git a/crates/test_utils/src/main.rs b/crates/test_utils/src/main.rs index ba0d2eb358b..5b56b9a0d1c 100644 --- a/crates/test_utils/src/main.rs +++ b/crates/test_utils/src/main.rs @@ -1,9 +1,10 @@ use std::process::{exit, Command}; +use anyhow::Result; use test_utils::newman_runner; -fn main() { - let mut runner = newman_runner::generate_newman_command(); +fn main() -> Result<()> { + let mut runner = newman_runner::generate_runner()?; // Execute the newman command let output = runner.newman_command.spawn(); diff --git a/crates/test_utils/src/newman_runner.rs b/crates/test_utils/src/newman_runner.rs index c90292683ff..29c15789cce 100644 --- a/crates/test_utils/src/newman_runner.rs +++ b/crates/test_utils/src/newman_runner.rs @@ -6,14 +6,23 @@ use std::{ process::{exit, Command}, }; -use clap::{arg, command, Parser}; +use anyhow::{Context, Result}; +use clap::{arg, command, Parser, ValueEnum}; use masking::PeekInterface; use regex::Regex; -use crate::connector_auth::{ConnectorAuthType, ConnectorAuthenticationMap}; +use crate::connector_auth::{ + ConnectorAuthType, ConnectorAuthentication, ConnectorAuthenticationMap, +}; + +#[derive(ValueEnum, Clone, Copy)] +pub enum Module { + Connector, + Users, +} #[derive(Parser)] #[command(version, about = "Postman collection runner using newman!", long_about = None)] -struct Args { +pub struct Args { /// Admin API Key of the environment #[arg(short, long)] admin_api_key: String, @@ -22,7 +31,10 @@ struct Args { base_url: String, /// Name of the connector #[arg(short, long)] - connector_name: String, + connector_name: Option<String>, + /// Name of the module + #[arg(short, long)] + module_name: Option<Module>, /// Custom headers #[arg(short = 'H', long = "header")] custom_headers: Option<Vec<String>>, @@ -38,6 +50,13 @@ struct Args { verbose: bool, } +impl Args { + /// Getter for the `module_name` field + pub fn get_module_name(&self) -> Option<Module> { + self.module_name + } +} + pub struct ReturnArgs { pub newman_command: Command, pub modified_file_paths: Vec<Option<String>>, @@ -82,10 +101,93 @@ where Ok(()) } -pub fn generate_newman_command() -> ReturnArgs { +// This function gives runner for connector or a module +pub fn generate_runner() -> Result<ReturnArgs> { + let args = Args::parse(); + + match args.get_module_name() { + Some(Module::Users) => generate_newman_command_for_users(), + Some(Module::Connector) => generate_newman_command_for_connector(), + // Running connector tests when no module is passed to keep the previous test behavior same + None => generate_newman_command_for_connector(), + } +} + +pub fn generate_newman_command_for_users() -> Result<ReturnArgs> { + let args = Args::parse(); + let base_url = args.base_url; + let admin_api_key = args.admin_api_key; + + let path = env::var("CONNECTOR_AUTH_FILE_PATH") + .with_context(|| "connector authentication file path not set")?; + + let authentication: ConnectorAuthentication = toml::from_str( + &fs::read_to_string(path) + .with_context(|| "connector authentication config file not found")?, + ) + .with_context(|| "connector authentication file path not set")?; + + let users_configs = authentication + .users + .with_context(|| "user configs not found in authentication file")?; + let collection_path = get_collection_path("users"); + + let mut newman_command = Command::new("newman"); + newman_command.args(["run", &collection_path]); + newman_command.args(["--env-var", &format!("admin_api_key={admin_api_key}")]); + newman_command.args(["--env-var", &format!("baseUrl={base_url}")]); + newman_command.args([ + "--env-var", + &format!("user_email={}", users_configs.user_email), + ]); + newman_command.args([ + "--env-var", + &format!( + "user_base_email_for_signup={}", + users_configs.user_base_email_for_signup + ), + ]); + newman_command.args([ + "--env-var", + &format!( + "user_domain_for_signup={}", + users_configs.user_domain_for_signup + ), + ]); + newman_command.args([ + "--env-var", + &format!("user_password={}", users_configs.user_password), + ]); + newman_command.args([ + "--env-var", + &format!("wrong_password={}", users_configs.wrong_password), + ]); + + newman_command.args([ + "--delay-request", + format!("{}", &args.delay_request).as_str(), + ]); + + newman_command.arg("--color").arg("on"); + + if args.verbose { + newman_command.arg("--verbose"); + } + + Ok(ReturnArgs { + newman_command, + modified_file_paths: vec![], + collection_path, + }) +} + +pub fn generate_newman_command_for_connector() -> Result<ReturnArgs> { let args = Args::parse(); - let connector_name = args.connector_name; + let connector_name = args + .connector_name + .with_context(|| "invalid parameters: connector/module name not found in arguments")?; + let base_url = args.base_url; let admin_api_key = args.admin_api_key; @@ -216,11 +318,11 @@ pub fn generate_newman_command() -> ReturnArgs { newman_command.arg("--verbose"); } - ReturnArgs { + Ok(ReturnArgs { newman_command, modified_file_paths: vec![modified_collection_file_paths, custom_header_exist], collection_path, - } + }) } pub fn check_for_custom_headers(headers: Option<Vec<String>>, path: &str) -> Option<String> { diff --git a/postman/collection-dir/users/.event.meta.json b/postman/collection-dir/users/.event.meta.json new file mode 100644 index 00000000000..2df9d47d936 --- /dev/null +++ b/postman/collection-dir/users/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.prerequest.js", + "event.test.js" + ] +} diff --git a/postman/collection-dir/users/.info.json b/postman/collection-dir/users/.info.json new file mode 100644 index 00000000000..68f1e83b8ef --- /dev/null +++ b/postman/collection-dir/users/.info.json @@ -0,0 +1,9 @@ +{ + "info": { + "_postman_id": "b5b40c9a-7e58-42c7-8b89-0adb208c45c9", + "name": "users", + "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [support@juspay.in](mailto:support@juspay.in)", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "26710321" + } +} diff --git a/postman/collection-dir/users/.meta.json b/postman/collection-dir/users/.meta.json new file mode 100644 index 00000000000..91b6a65c5bc --- /dev/null +++ b/postman/collection-dir/users/.meta.json @@ -0,0 +1,6 @@ +{ + "childrenOrder": [ + "Health check", + "Flow Testcases" + ] +} diff --git a/postman/collection-dir/users/.variable.json b/postman/collection-dir/users/.variable.json new file mode 100644 index 00000000000..fba5b17b2fd --- /dev/null +++ b/postman/collection-dir/users/.variable.json @@ -0,0 +1,126 @@ +{ + "variable": [ + { + "key": "baseUrl", + "value": "", + "type": "string" + }, + { + "key": "admin_api_key", + "value": "", + "type": "string" + }, + { + "key": "api_key", + "value": "", + "type": "string" + }, + { + "key": "merchant_id", + "value": "" + }, + { + "key": "payment_id", + "value": "" + }, + { + "key": "customer_id", + "value": "" + }, + { + "key": "mandate_id", + "value": "" + }, + { + "key": "payment_method_id", + "value": "" + }, + { + "key": "refund_id", + "value": "" + }, + { + "key": "merchant_connector_id", + "value": "" + }, + { + "key": "client_secret", + "value": "", + "type": "string" + }, + { + "key": "connector_api_key", + "value": "", + "type": "string" + }, + { + "key": "publishable_key", + "value": "", + "type": "string" + }, + { + "key": "api_key_id", + "value": "", + "type": "string" + }, + { + "key": "payment_token", + "value": "" + }, + { + "key": "gateway_merchant_id", + "value": "", + "type": "string" + }, + { + "key": "certificate", + "value": "", + "type": "string" + }, + { + "key": "certificate_keys", + "value": "", + "type": "string" + }, + { + "key": "connector_api_secret", + "value": "", + "type": "string" + }, + { + "key": "connector_key1", + "value": "", + "type": "string" + }, + { + "key": "connector_key2", + "value": "", + "type": "string" + }, + { + "key": "user_email", + "value": "", + "type": "string" + }, + { + "key": "user_password", + "value": "", + "type": "string" + }, + { + "key": "wrong_password", + "value": "", + "type": "string" + }, + { + "key": "user_base_email_for_signup", + "value": "", + "type": "string" + }, + { + "key": "user_domain_for_signup", + "value": "", + "type": "string" + } + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/.meta.json b/postman/collection-dir/users/Flow Testcases/.meta.json new file mode 100644 index 00000000000..3e649dae4eb --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/.meta.json @@ -0,0 +1,6 @@ +{ + "childrenOrder": [ + "Sign Up", + "Sign In" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json new file mode 100644 index 00000000000..84ed2cb9494 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json @@ -0,0 +1,8 @@ +{ + "childrenOrder": [ + "Signin", + "Signin Wrong", + "Signin Token Only", + "Signin Token Only Wrong" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js new file mode 100644 index 00000000000..16fca64a141 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js @@ -0,0 +1,16 @@ +// Validate status 4xx +pm.test("[POST]::/user/v2/signin?token_only=true - Status code is 401", function () { + pm.response.to.have.status(401); +}); + +// Validate if response header has matching content-type +pm.test("[POST]::user/v2/signin?token_only=true - Content-Type is application/json", function () { + pm.expect(pm.response.headers.get("Content-Type")).to.include( + "application/json", + ); +}); + +// Validate if response has JSON Body +pm.test("[POST]::user/v2/signin?token_only=true - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); \ No newline at end of file diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/request.json new file mode 100644 index 00000000000..7fee4c465c8 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/request.json @@ -0,0 +1,37 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw_json_formatted": { + "email": "{{user_email}}", + "password": "{{wrong_password}}" + } + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin?token_only=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ], + "query": [ + { + "key": "token_only", + "value": "true" + } + ] + } +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js new file mode 100644 index 00000000000..a8b3658e5ff --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js @@ -0,0 +1,23 @@ +// Validate status 2xx +pm.test("[POST]::user/v2/signin?token_only=true - Status code is 2xx", function () { + pm.response.to.be.success; +}); + +// Validate if response header has matching content-type +pm.test("[POST]::user/v2/signin?token_only=true - Content-Type is application/json", function () { + pm.expect(pm.response.headers.get("Content-Type")).to.include( + "application/json", + ); +}); + +// Validate if response has JSON Body +pm.test("[POST]::user/v2/signin?token_only=true - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); + +// Validate specific JSON response content +pm.test("[POST]::user/v2/signin?token_only=true - Response contains token", function () { + var jsonData = pm.response.json(); + pm.expect(jsonData).to.have.property("token"); + pm.expect(jsonData.token).to.be.a("string").and.to.not.be.empty; +}); \ No newline at end of file diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/request.json new file mode 100644 index 00000000000..62028501a50 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/request.json @@ -0,0 +1,37 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw_json_formatted": { + "email": "{{user_email}}", + "password": "{{user_password}}" + } + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin?token_only=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ], + "query": [ + { + "key": "token_only", + "value": "true" + } + ] + } +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js new file mode 100644 index 00000000000..e0149290da6 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js @@ -0,0 +1,16 @@ +// Validate status code is 4xx Bad Request +pm.test("[POST]::/user/v2/signin - Status code is 401", function () { + pm.response.to.have.status(401); +}); + +// Validate if response header has matching content-type +pm.test("[POST]::/user/v2/signin - Content-Type is application/json", function () { + pm.expect(pm.response.headers.get("Content-Type")).to.include( + "application/json", + ); +}); + +// Validate if response has JSON Body +pm.test("[POST]::/user/v2/signin - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); \ No newline at end of file diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json new file mode 100644 index 00000000000..775b0972d57 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json @@ -0,0 +1,31 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw_json_formatted": { + "email": "{{user_email}}", + "password": "{{wrong_password}}" + } + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ] + } +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/.event.meta.json new file mode 100644 index 00000000000..4ac527d834a --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.test.js", + "event.prerequest.js" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.prerequest.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.prerequest.js new file mode 100644 index 00000000000..e69de29bb2d diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js new file mode 100644 index 00000000000..174cbd8e5e2 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js @@ -0,0 +1,23 @@ +// Validate status 2xx +pm.test("[POST]::/user/v2/signin - Status code is 2xx", function () { + pm.response.to.be.success; +}); + +// Validate if response header has matching content-type +pm.test("[POST]::/user/v2/signin - Content-Type is application/json", function () { + pm.expect(pm.response.headers.get("Content-Type")).to.include( + "application/json", + ); +}); + +// Validate if response has JSON Body +pm.test("[POST]::/user/v2/signin - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); + +// Validate specific JSON response content +pm.test("[POST]::/user/v2/signin - Response contains token", function () { + var jsonData = pm.response.json(); + pm.expect(jsonData).to.have.property("token"); + pm.expect(jsonData.token).to.be.a("string").and.to.not.be.empty; +}); \ No newline at end of file diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json new file mode 100644 index 00000000000..1d23f6e9652 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json @@ -0,0 +1,31 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw_json_formatted": { + "email": "{{user_email}}", + "password": "{{user_password}}" + } + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ] + } +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/.meta.json b/postman/collection-dir/users/Flow Testcases/Sign Up/.meta.json new file mode 100644 index 00000000000..07d803fb1ca --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign Up/.meta.json @@ -0,0 +1,5 @@ +{ + "childrenOrder": [ + "Connect Account" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/.event.meta.json new file mode 100644 index 00000000000..4ac527d834a --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/.event.meta.json @@ -0,0 +1,6 @@ +{ + "eventOrder": [ + "event.test.js", + "event.prerequest.js" + ] +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.prerequest.js b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.prerequest.js new file mode 100644 index 00000000000..7f16342a8ad --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.prerequest.js @@ -0,0 +1,8 @@ + +var baseEmail = pm.environment.get('user_base_email_for_signup'); +var emailDomain = pm.environment.get("user_domain_for_signup"); + +// Generate a unique email address +var uniqueEmail = baseEmail + new Date().getTime() + emailDomain; +// Set the unique email address as an environment variable +pm.environment.set('unique_email', uniqueEmail); diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js new file mode 100644 index 00000000000..6dbed06b0f6 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js @@ -0,0 +1,23 @@ +// Validate status 2xx +pm.test("[POST]::/user/connect_account - Status code is 2xx", function () { + pm.response.to.be.success; +}); + +// Validate if response header has matching content-type +pm.test("[POST]::/user/connect_account - Content-Type is application/json", function () { + pm.expect(pm.response.headers.get("Content-Type")).to.include( + "application/json", + ); +}); + +// Validate if response has JSON Body +pm.test("[POST]::/user/connect_account - Response has JSON Body", function () { + pm.response.to.have.jsonBody(); +}); + +// Validate specific JSON response content +pm.test("[POST]::/user/connect_account - Response contains is_email_sent", function () { + var jsonData = pm.response.json(); + pm.expect(jsonData).to.have.property("is_email_sent"); + pm.expect(jsonData.is_email_sent).to.be.true; +}); diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/request.json b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/request.json new file mode 100644 index 00000000000..d5f2433ad7a --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/request.json @@ -0,0 +1,29 @@ +{ + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw_json_formatted": { + "email": "{{unique_email}}" + } + }, + "url": { + "raw": "{{baseUrl}}/user/connect_account", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "connect_account" + ] + } +} diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/response.json b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/users/Health check/.meta.json b/postman/collection-dir/users/Health check/.meta.json new file mode 100644 index 00000000000..66ee7e50cab --- /dev/null +++ b/postman/collection-dir/users/Health check/.meta.json @@ -0,0 +1,5 @@ +{ + "childrenOrder": [ + "New Request" + ] +} diff --git a/postman/collection-dir/users/Health check/New Request/.event.meta.json b/postman/collection-dir/users/Health check/New Request/.event.meta.json new file mode 100644 index 00000000000..688c85746ef --- /dev/null +++ b/postman/collection-dir/users/Health check/New Request/.event.meta.json @@ -0,0 +1,5 @@ +{ + "eventOrder": [ + "event.test.js" + ] +} diff --git a/postman/collection-dir/users/Health check/New Request/event.test.js b/postman/collection-dir/users/Health check/New Request/event.test.js new file mode 100644 index 00000000000..5e5505dfa3b --- /dev/null +++ b/postman/collection-dir/users/Health check/New Request/event.test.js @@ -0,0 +1,4 @@ +// Validate status 2xx +pm.test("[POST]::/health - Status code is 2xx", function () { + pm.response.to.be.success; +}); diff --git a/postman/collection-dir/users/Health check/New Request/request.json b/postman/collection-dir/users/Health check/New Request/request.json new file mode 100644 index 00000000000..4e1e0a0d9e6 --- /dev/null +++ b/postman/collection-dir/users/Health check/New Request/request.json @@ -0,0 +1,13 @@ +{ + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/health", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "health" + ] + } +} diff --git a/postman/collection-dir/users/Health check/New Request/response.json b/postman/collection-dir/users/Health check/New Request/response.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/postman/collection-dir/users/Health check/New Request/response.json @@ -0,0 +1 @@ +[] diff --git a/postman/collection-dir/users/event.prerequest.js b/postman/collection-dir/users/event.prerequest.js new file mode 100644 index 00000000000..e69de29bb2d diff --git a/postman/collection-dir/users/event.test.js b/postman/collection-dir/users/event.test.js new file mode 100644 index 00000000000..e69de29bb2d diff --git a/postman/collection-json/users.postman_collection.json b/postman/collection-json/users.postman_collection.json new file mode 100644 index 00000000000..943d37d22d3 --- /dev/null +++ b/postman/collection-json/users.postman_collection.json @@ -0,0 +1,556 @@ +{ + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + } + ], + "item": [ + { + "name": "Health check", + "item": [ + { + "name": "New Request", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/health - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/health", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "health" + ] + } + }, + "response": [] + } + ] + }, + { + "name": "Flow Testcases", + "item": [ + { + "name": "Sign Up", + "item": [ + { + "name": "Connect Account", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/user/connect_account - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/user/connect_account - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/user/connect_account - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Validate specific JSON response content", + "pm.test(\"[POST]::/user/connect_account - Response contains is_email_sent\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData).to.have.property(\"is_email_sent\");", + " pm.expect(jsonData.is_email_sent).to.be.true;", + "});", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "", + "var baseEmail = pm.environment.get('user_base_email_for_signup');", + "var emailDomain = pm.environment.get(\"user_domain_for_signup\");", + "", + "// Generate a unique email address", + "var uniqueEmail = baseEmail + new Date().getTime() + emailDomain;", + "// Set the unique email address as an environment variable", + "pm.environment.set('unique_email', uniqueEmail);", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\"email\":\"{{unique_email}}\"}" + }, + "url": { + "raw": "{{baseUrl}}/user/connect_account", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "connect_account" + ] + } + }, + "response": [] + } + ] + }, + { + "name": "Sign In", + "item": [ + { + "name": "Signin", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::/user/v2/signin - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/user/v2/signin - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/user/v2/signin - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Validate specific JSON response content", + "pm.test(\"[POST]::/user/v2/signin - Response contains token\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData).to.have.property(\"token\");", + " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;", + "});" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{user_password}}\"}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ] + } + }, + "response": [] + }, + { + "name": "Signin Wrong", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status code is 4xx Bad Request", + "pm.test(\"[POST]::/user/v2/signin - Status code is 401\", function () {", + " pm.response.to.have.status(401);", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::/user/v2/signin - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::/user/v2/signin - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{wrong_password}}\"}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ] + } + }, + "response": [] + }, + { + "name": "Signin Token Only", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 2xx", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Status code is 2xx\", function () {", + " pm.response.to.be.success;", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});", + "", + "// Validate specific JSON response content", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Response contains token\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData).to.have.property(\"token\");", + " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{user_password}}\"}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin?token_only=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ], + "query": [ + { + "key": "token_only", + "value": "true" + } + ] + } + }, + "response": [] + }, + { + "name": "Signin Token Only Wrong", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Validate status 4xx", + "pm.test(\"[POST]::/user/v2/signin?token_only=true - Status code is 401\", function () {", + " pm.response.to.have.status(401);", + "});", + "", + "// Validate if response header has matching content-type", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Content-Type is application/json\", function () {", + " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(", + " \"application/json\",", + " );", + "});", + "", + "// Validate if response has JSON Body", + "pm.test(\"[POST]::user/v2/signin?token_only=true - Response has JSON Body\", function () {", + " pm.response.to.have.jsonBody();", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Cookie", + "value": "Cookie_1=value" + } + ], + "body": { + "mode": "raw", + "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{wrong_password}}\"}" + }, + "url": { + "raw": "{{baseUrl}}/user/v2/signin?token_only=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "user", + "v2", + "signin" + ], + "query": [ + { + "key": "token_only", + "value": "true" + } + ] + } + }, + "response": [] + } + ] + } + ] + } + ], + "info": { + "_postman_id": "b5b40c9a-7e58-42c7-8b89-0adb208c45c9", + "name": "users", + "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [support@juspay.in](mailto:support@juspay.in)", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "26710321" + }, + "variable": [ + { + "key": "baseUrl", + "value": "", + "type": "string" + }, + { + "key": "admin_api_key", + "value": "", + "type": "string" + }, + { + "key": "api_key", + "value": "", + "type": "string" + }, + { + "key": "merchant_id", + "value": "" + }, + { + "key": "payment_id", + "value": "" + }, + { + "key": "customer_id", + "value": "" + }, + { + "key": "mandate_id", + "value": "" + }, + { + "key": "payment_method_id", + "value": "" + }, + { + "key": "refund_id", + "value": "" + }, + { + "key": "merchant_connector_id", + "value": "" + }, + { + "key": "client_secret", + "value": "", + "type": "string" + }, + { + "key": "connector_api_key", + "value": "", + "type": "string" + }, + { + "key": "publishable_key", + "value": "", + "type": "string" + }, + { + "key": "api_key_id", + "value": "", + "type": "string" + }, + { + "key": "payment_token", + "value": "" + }, + { + "key": "gateway_merchant_id", + "value": "", + "type": "string" + }, + { + "key": "certificate", + "value": "", + "type": "string" + }, + { + "key": "certificate_keys", + "value": "", + "type": "string" + }, + { + "key": "connector_api_secret", + "value": "", + "type": "string" + }, + { + "key": "connector_key1", + "value": "", + "type": "string" + }, + { + "key": "connector_key2", + "value": "", + "type": "string" + }, + { + "key": "user_email", + "value": "", + "type": "string" + }, + { + "key": "user_password", + "value": "", + "type": "string" + }, + { + "key": "wrong_password", + "value": "", + "type": "string" + }, + { + "key": "user_base_email_for_signup", + "value": "", + "type": "string" + }, + { + "key": "user_domain_for_signup", + "value": "", + "type": "string" + } + ] +}
2024-06-06T09:29:26Z
## Description Added test for: **Health check** Health Check: expects 200 Ok Flow Check **Signup** Connect account - checks for 200 Ok, content type application/json, response has json body and is_email sent is true **SignIn** 1. SignIn with correct password: checks for 200 Ok, content type application/json, response has json body and contains token 2. SignIn with wrong password: checks for 401 bad request, content type application/json, response has json body 3. SignIn with correct password token only flow: checks for 200 Ok, content type application/json, response has json body and contains token 4. SignIn with wrong password token only flow: checks for 401 bad request, content type application/json, response has json body ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context closes [#4896](https://github.com/juspay/hyperswitch/issues/4896) ## How did you test it? Use command to test user module: ``` cargo run --bin test_utils -- --module-name="users" --base-url="http://localhost:8080" --admin-api-key="admin_api_key" ``` ![Screenshot 2024-06-07 at 2 42 51 PM](https://github.com/juspay/hyperswitch/assets/64925866/89e23626-a167-484d-bbb8-e99b83dfd5d3) ![Screenshot 2024-06-07 at 2 43 05 PM](https://github.com/juspay/hyperswitch/assets/64925866/ef68dd7c-455a-4706-8f7c-ca40fbe3acbe) The previous working for connector commands remains same, just use connector-name instead of module name: ``` cargo run --bin test_utils -- --connector-name="connector_name" --base-url="http://localhost:8080" --admin-api-key="admin_api_key" ``` The previous command is running test cases for connector mentioned. ![image](https://github.com/juspay/hyperswitch/assets/64925866/5e23f1f8-50b6-427b-9d62-809484fc1169)
ff93981ec776031af1de946cd6e9f90d2f410cd2
Use command to test user module: ``` cargo run --bin test_utils -- --module-name="users" --base-url="http://localhost:8080" --admin-api-key="admin_api_key" ``` ![Screenshot 2024-06-07 at 2 42 51 PM](https://github.com/juspay/hyperswitch/assets/64925866/89e23626-a167-484d-bbb8-e99b83dfd5d3) ![Screenshot 2024-06-07 at 2 43 05 PM](https://github.com/juspay/hyperswitch/assets/64925866/ef68dd7c-455a-4706-8f7c-ca40fbe3acbe) The previous working for connector commands remains same, just use connector-name instead of module name: ``` cargo run --bin test_utils -- --connector-name="connector_name" --base-url="http://localhost:8080" --admin-api-key="admin_api_key" ``` The previous command is running test cases for connector mentioned. ![image](https://github.com/juspay/hyperswitch/assets/64925866/5e23f1f8-50b6-427b-9d62-809484fc1169)
[ "Cargo.lock", "crates/test_utils/Cargo.toml", "crates/test_utils/src/connector_auth.rs", "crates/test_utils/src/main.rs", "crates/test_utils/src/newman_runner.rs", "postman/collection-dir/users/.event.meta.json", "postman/collection-dir/users/.info.json", "postman/collection-dir/users/.meta.json", "...
juspay/hyperswitch
juspay__hyperswitch-4893
Bug: Add `collect_shipping_details_from_wallet_connector` in the business profile response Add `collect_shipping_details_from_wallet_connector` in the business profile response
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index dc64947bf08..58cb6fbf3e2 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -936,7 +936,7 @@ pub struct BusinessProfileCreate { /// Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, - /// A boolean value to indicate if cusomter shipping details needs to be sent for wallets payments + /// A boolean value to indicate if customer shipping details needs to be sent for wallets payments pub collect_shipping_details_from_wallet_connector: Option<bool>, } @@ -1013,6 +1013,9 @@ pub struct BusinessProfileResponse { /// Merchant's config to support extended card info feature pub extended_card_info_config: Option<ExtendedCardInfoConfig>, + + /// A boolean value to indicate if customer shipping details needs to be sent for wallets payments + pub collect_shipping_details_from_wallet_connector: Option<bool>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] @@ -1081,7 +1084,7 @@ pub struct BusinessProfileUpdate { // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, - /// A boolean value to indicate if cusomter shipping details needs to be sent for wallets payments + /// A boolean value to indicate if customer shipping details needs to be sent for wallets payments pub collect_shipping_details_from_wallet_connector: Option<bool>, } diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 20083afb1c9..b79819ed634 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -85,6 +85,8 @@ impl ForeignTryFrom<storage::business_profile::BusinessProfile> for BusinessProf .extended_card_info_config .map(|config| config.expose().parse_value("ExtendedCardInfoConfig")) .transpose()?, + collect_shipping_details_from_wallet_connector: item + .collect_shipping_details_from_wallet_connector, }) } } diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 76cbda10a18..a12df1d916a 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -6824,7 +6824,7 @@ }, "collect_shipping_details_from_wallet_connector": { "type": "boolean", - "description": "A boolean value to indicate if cusomter shipping details needs to be sent for wallets payments", + "description": "A boolean value to indicate if customer shipping details needs to be sent for wallets payments", "nullable": true } }, @@ -6957,6 +6957,11 @@ } ], "nullable": true + }, + "collect_shipping_details_from_wallet_connector": { + "type": "boolean", + "description": "A boolean value to indicate if customer shipping details needs to be sent for wallets payments", + "nullable": true } } },
2024-06-05T13:36:45Z
## Description <!-- Describe your changes in detail --> add `collect_shipping_details_from_wallet_connector` in the business profile ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create merchant account -> update the business profile with the below curl ``` curl --location 'http://localhost:8080/account/merchant_1717593917/business_profile/pro_eqCDCAfX7AA2WudlMDYP' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "collect_shipping_details_from_wallet_connector": true }' ``` <img width="940" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/ece087a0-e378-4f3c-84eb-228d9402d56d">
c5e28f2670d51bf6529eb729167c97ad301217ef
-> Create merchant account -> update the business profile with the below curl ``` curl --location 'http://localhost:8080/account/merchant_1717593917/business_profile/pro_eqCDCAfX7AA2WudlMDYP' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "collect_shipping_details_from_wallet_connector": true }' ``` <img width="940" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/ece087a0-e378-4f3c-84eb-228d9402d56d">
[ "crates/api_models/src/admin.rs", "crates/router/src/types/api/admin.rs", "openapi/openapi_spec.json" ]
juspay/hyperswitch
juspay__hyperswitch-4889
Bug: feat(connector): [DATATRANS] add Connector Template Code
diff --git a/config/config.example.toml b/config/config.example.toml index 81516ee8b6b..7372f93044c 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -186,6 +186,7 @@ checkout.base_url = "https://api.sandbox.checkout.com/" coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" +datatrans.base_url = "https://api.sandbox.datatrans.com/" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" @@ -276,6 +277,7 @@ cards = [ "braintree", "checkout", "cybersource", + "datatrans", "globalpay", "globepay", "gocardless", diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 5abbc870fd0..f5f69568da6 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -40,6 +40,7 @@ checkout.base_url = "https://api.sandbox.checkout.com/" coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" +datatrans.base_url = "https://api.sandbox.datatrans.com/" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index b4e02172dfc..bbaf22067b5 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -44,6 +44,7 @@ checkout.base_url = "https://api.checkout.com/" coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business.cryptopay.me/" cybersource.base_url = "https://api.cybersource.com/" +datatrans.base_url = "https://api.datatrans.com/" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index a8ddbc55f5f..de274ad9411 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -44,6 +44,7 @@ checkout.base_url = "https://api.sandbox.checkout.com/" coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" +datatrans.base_url = "https://api.sandbox.datatrans.com/" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" diff --git a/config/development.toml b/config/development.toml index 9a40a99cfce..fcdc2dee136 100644 --- a/config/development.toml +++ b/config/development.toml @@ -109,6 +109,7 @@ cards = [ "coinbase", "cryptopay", "cybersource", + "datatrans", "dlocal", "dummyconnector", "ebanx", @@ -188,6 +189,7 @@ checkout.base_url = "https://api.sandbox.checkout.com/" coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" +datatrans.base_url = "https://api.sandbox.datatrans.com" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 2cd93eade01..e5075d4ea45 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -125,6 +125,7 @@ checkout.base_url = "https://api.sandbox.checkout.com/" coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" +datatrans.base_url = "https://api.sandbox.datatrans.com/" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" @@ -202,6 +203,7 @@ cards = [ "coinbase", "cryptopay", "cybersource", + "datatrans", "dlocal", "dummyconnector", "ebanx", diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 1b976d68a19..514e44337c1 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -89,6 +89,7 @@ pub enum Connector { Coinbase, Cryptopay, Cybersource, + // Datatrans, Dlocal, Ebanx, Fiserv, @@ -251,6 +252,7 @@ impl Connector { | Self::Plaid | Self::Riskified | Self::Threedsecureio + // | Self::Datatrans | Self::Netcetera | Self::Noon | Self::Stripe => false, diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 5d6b9c14895..f3a3b02155d 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -128,6 +128,7 @@ pub enum RoutableConnectors { Coinbase, Cryptopay, Cybersource, + // Datatrans, Dlocal, Ebanx, Fiserv, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index e99e216463a..ac8689d21b4 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -568,6 +568,7 @@ pub struct Connectors { pub coinbase: ConnectorParams, pub cryptopay: ConnectorParams, pub cybersource: ConnectorParams, + pub datatrans: ConnectorParams, pub dlocal: ConnectorParams, #[cfg(feature = "dummy_connector")] pub dummyconnector: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index a423decdb9b..4b89b12734e 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -15,6 +15,7 @@ pub mod checkout; pub mod coinbase; pub mod cryptopay; pub mod cybersource; +pub mod datatrans; pub mod dlocal; #[cfg(feature = "dummy_connector")] pub mod dummyconnector; @@ -71,12 +72,12 @@ pub use self::{ authorizedotnet::Authorizedotnet, bambora::Bambora, bankofamerica::Bankofamerica, billwerk::Billwerk, bitpay::Bitpay, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay, - cybersource::Cybersource, dlocal::Dlocal, ebanx::Ebanx, fiserv::Fiserv, forte::Forte, - globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, gpayments::Gpayments, - helcim::Helcim, iatapay::Iatapay, klarna::Klarna, mifinity::Mifinity, mollie::Mollie, - multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nmi::Nmi, noon::Noon, - nuvei::Nuvei, opayo::Opayo, opennode::Opennode, payeezy::Payeezy, payme::Payme, payone::Payone, - paypal::Paypal, payu::Payu, placetopay::Placetopay, powertranz::Powertranz, + cybersource::Cybersource, datatrans::Datatrans, dlocal::Dlocal, ebanx::Ebanx, fiserv::Fiserv, + forte::Forte, globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, + gpayments::Gpayments, helcim::Helcim, iatapay::Iatapay, klarna::Klarna, mifinity::Mifinity, + mollie::Mollie, multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nmi::Nmi, + noon::Noon, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, payeezy::Payeezy, payme::Payme, + payone::Payone, paypal::Paypal, payu::Payu, placetopay::Placetopay, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, riskified::Riskified, shift4::Shift4, signifyd::Signifyd, square::Square, stax::Stax, stripe::Stripe, threedsecureio::Threedsecureio, trustpay::Trustpay, tsys::Tsys, volt::Volt, wise::Wise, worldline::Worldline, worldpay::Worldpay, zen::Zen, diff --git a/crates/router/src/connector/datatrans.rs b/crates/router/src/connector/datatrans.rs new file mode 100644 index 00000000000..90c6b38d2fb --- /dev/null +++ b/crates/router/src/connector/datatrans.rs @@ -0,0 +1,563 @@ +pub mod transformers; + +use std::fmt::Debug; + +use error_stack::{report, ResultExt}; +use masking::ExposeInterface; +use transformers as datatrans; + +use crate::{ + configs::settings, + core::errors::{self, CustomResult}, + events::connector_api_logs::ConnectorEvent, + headers, + services::{ + self, + request::{self, Mask}, + ConnectorIntegration, ConnectorValidation, + }, + types::{ + self, + api::{self, ConnectorCommon, ConnectorCommonExt}, + ErrorResponse, RequestContent, Response, + }, + utils::BytesExt, +}; + +#[derive(Debug, Clone)] +pub struct Datatrans; + +impl api::Payment for Datatrans {} +impl api::PaymentSession for Datatrans {} +impl api::ConnectorAccessToken for Datatrans {} +impl api::MandateSetup for Datatrans {} +impl api::PaymentAuthorize for Datatrans {} +impl api::PaymentSync for Datatrans {} +impl api::PaymentCapture for Datatrans {} +impl api::PaymentVoid for Datatrans {} +impl api::Refund for Datatrans {} +impl api::RefundExecute for Datatrans {} +impl api::RefundSync for Datatrans {} +impl api::PaymentToken for Datatrans {} + +impl + ConnectorIntegration< + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + > for Datatrans +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Datatrans +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &types::RouterData<Flow, Request, Response>, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + +impl ConnectorCommon for Datatrans { + fn id(&self) -> &'static str { + "datatrans" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.datatrans.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + let auth = datatrans::DatatransAuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![( + headers::AUTHORIZATION.to_string(), + auth.api_key.expose().into_masked(), + )]) + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: datatrans::DatatransErrorResponse = res + .response + .parse_struct("DatatransErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + Ok(ErrorResponse { + status_code: res.status_code, + code: response.code, + message: response.message, + reason: response.reason, + attempt_status: None, + connector_transaction_id: None, + }) + } +} + +impl ConnectorValidation for Datatrans { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Datatrans +{ + //TODO: implement sessions flow +} + +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Datatrans +{ +} + +impl + ConnectorIntegration< + api::SetupMandate, + types::SetupMandateRequestData, + types::PaymentsResponseData, + > for Datatrans +{ +} + +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Datatrans +{ + fn get_headers( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = datatrans::DatatransRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = datatrans::DatatransPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: datatrans::DatatransPaymentsResponse = res + .response + .parse_struct("Datatrans PaymentsAuthorizeResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Datatrans +{ + fn get_headers( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::PaymentsSyncRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + let response: datatrans::DatatransPaymentsResponse = res + .response + .parse_struct("datatrans PaymentsSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for Datatrans +{ + fn get_headers( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::PaymentsCaptureRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + _req: &types::PaymentsCaptureRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + } + + fn build_request( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCaptureType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + let response: datatrans::DatatransPaymentsResponse = res + .response + .parse_struct("Datatrans PaymentsCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for Datatrans +{ +} + +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Datatrans +{ + fn get_headers( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::RefundsRouterData<api::Execute>, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &types::RefundsRouterData<api::Execute>, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = datatrans::DatatransRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let connector_req = datatrans::DatatransRefundRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .set_body(types::RefundExecuteType::get_request_body( + self, req, connectors, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::RefundsRouterData<api::Execute>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + let response: datatrans::RefundResponse = res + .response + .parse_struct("datatrans RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Datatrans +{ + fn get_headers( + &self, + req: &types::RefundSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::RefundSyncRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &types::RefundSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .set_body(types::RefundSyncType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + let response: datatrans::RefundResponse = res + .response + .parse_struct("datatrans RefundSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Datatrans { + fn get_webhook_object_reference_id( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_event_type( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_resource_object( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } +} diff --git a/crates/router/src/connector/datatrans/transformers.rs b/crates/router/src/connector/datatrans/transformers.rs new file mode 100644 index 00000000000..b079708e233 --- /dev/null +++ b/crates/router/src/connector/datatrans/transformers.rs @@ -0,0 +1,235 @@ +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + connector::utils::PaymentsAuthorizeRequestData, + core::errors, + types::{self, api, domain, storage::enums}, +}; + +//TODO: Fill the struct with respective fields +pub struct DatatransRouterData<T> { + pub amount: i64, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for DatatransRouterData<T> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), + ) -> Result<Self, Self::Error> { + //Todo : use utils to convert the amount to the type of amount that a connector accepts + Ok(Self { + amount, + router_data: item, + }) + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct DatatransPaymentsRequest { + amount: i64, + card: DatatransCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct DatatransCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>> + for DatatransPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + domain::PaymentMethodData::Card(req_card) => { + let card = DatatransCard { + number: req_card.card_number, + expiry_month: req_card.card_exp_month, + expiry_year: req_card.card_exp_year, + cvc: req_card.card_cvc, + complete: item.router_data.request.is_auto_capture()?, + }; + Ok(Self { + amount: item.amount.to_owned(), + card, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct DatatransAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&types::ConnectorAuthType> for DatatransAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + api_key: api_key.to_owned(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} +// PaymentsResponse +//TODO: Append the remaining status flags +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum DatatransPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<DatatransPaymentStatus> for enums::AttemptStatus { + fn from(item: DatatransPaymentStatus) -> Self { + match item { + DatatransPaymentStatus::Succeeded => Self::Charged, + DatatransPaymentStatus::Failed => Self::Failure, + DatatransPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct DatatransPaymentsResponse { + status: DatatransPaymentStatus, + id: String, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, DatatransPaymentsResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + DatatransPaymentsResponse, + T, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: enums::AttemptStatus::from(item.response.status), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charge_id: None, + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct DatatransRefundRequest { + pub amount: i64, +} + +impl<F> TryFrom<&DatatransRouterData<&types::RefundsRouterData<F>>> for DatatransRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &DatatransRouterData<&types::RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Serialize, Default, Deserialize, Clone)] +pub enum RefundStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Succeeded => Self::Success, + RefundStatus::Failed => Self::Failure, + RefundStatus::Processing => Self::Pending, + //TODO: Review mapping + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct RefundResponse { + id: String, + status: RefundStatus, +} + +impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> + for types::RefundsRouterData<api::Execute> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> + for types::RefundsRouterData<api::RSync> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct DatatransErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, +} diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 180852c8a37..71e91373454 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1900,6 +1900,11 @@ pub(crate) fn validate_auth_and_metadata_type_with_connector( cybersource::transformers::CybersourceAuthType::try_from(val)?; Ok(()) } + // api_enums::Connector::Datatrans => { + // datatrans::transformers::DatatransAuthType::try_from(val)?; + // Ok(()) + // } + // added for future use api_enums::Connector::Dlocal => { dlocal::transformers::DlocalAuthType::try_from(val)?; Ok(()) diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index bc5bc3ff0ef..4c55ebc359d 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -166,6 +166,7 @@ default_imp_for_complete_authorize!( connector::Checkout, connector::Coinbase, connector::Cryptopay, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -247,6 +248,7 @@ default_imp_for_webhook_source_verification!( connector::Coinbase, connector::Cryptopay, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -338,6 +340,7 @@ default_imp_for_create_customer!( connector::Coinbase, connector::Cryptopay, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -423,6 +426,7 @@ default_imp_for_connector_redirect_response!( connector::Coinbase, connector::Cryptopay, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -490,6 +494,7 @@ default_imp_for_connector_request_id!( connector::Coinbase, connector::Cryptopay, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -581,6 +586,7 @@ default_imp_for_accept_dispute!( connector::Coinbase, connector::Cryptopay, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -694,6 +700,7 @@ default_imp_for_file_upload!( connector::Coinbase, connector::Cryptopay, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -784,6 +791,7 @@ default_imp_for_submit_evidence!( connector::Cybersource, connector::Coinbase, connector::Cryptopay, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -874,6 +882,7 @@ default_imp_for_defend_dispute!( connector::Cybersource, connector::Coinbase, connector::Cryptopay, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -962,6 +971,7 @@ default_imp_for_pre_processing_steps!( connector::Checkout, connector::Coinbase, connector::Cryptopay, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Iatapay, @@ -1027,6 +1037,7 @@ default_imp_for_payouts!( connector::Checkout, connector::Cryptopay, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Fiserv, connector::Forte, @@ -1114,6 +1125,7 @@ default_imp_for_payouts_create!( connector::Cryptopay, connector::Cybersource, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Fiserv, connector::Forte, @@ -1205,6 +1217,7 @@ default_imp_for_payouts_eligibility!( connector::Cryptopay, connector::Cybersource, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Fiserv, connector::Forte, @@ -1293,6 +1306,7 @@ default_imp_for_payouts_fulfill!( connector::Checkout, connector::Cryptopay, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Fiserv, connector::Forte, @@ -1380,6 +1394,7 @@ default_imp_for_payouts_cancel!( connector::Cryptopay, connector::Cybersource, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Fiserv, connector::Forte, @@ -1470,6 +1485,7 @@ default_imp_for_payouts_quote!( connector::Cryptopay, connector::Cybersource, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Fiserv, connector::Forte, @@ -1561,6 +1577,7 @@ default_imp_for_payouts_recipient!( connector::Cryptopay, connector::Cybersource, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Fiserv, connector::Forte, @@ -1654,6 +1671,7 @@ default_imp_for_payouts_recipient_account!( connector::Cryptopay, connector::Cybersource, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1745,6 +1763,7 @@ default_imp_for_approve!( connector::Cryptopay, connector::Cybersource, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1837,6 +1856,7 @@ default_imp_for_reject!( connector::Cryptopay, connector::Cybersource, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1913,6 +1933,7 @@ default_imp_for_fraud_check!( connector::Cryptopay, connector::Cybersource, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2005,6 +2026,7 @@ default_imp_for_frm_sale!( connector::Cryptopay, connector::Cybersource, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2097,6 +2119,7 @@ default_imp_for_frm_checkout!( connector::Cryptopay, connector::Cybersource, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2189,6 +2212,7 @@ default_imp_for_frm_transaction!( connector::Cryptopay, connector::Cybersource, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2281,6 +2305,7 @@ default_imp_for_frm_fulfillment!( connector::Cryptopay, connector::Cybersource, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2373,6 +2398,7 @@ default_imp_for_frm_record_return!( connector::Cryptopay, connector::Cybersource, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2462,6 +2488,7 @@ default_imp_for_incremental_authorization!( connector::Checkout, connector::Cryptopay, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2551,6 +2578,7 @@ default_imp_for_revoking_mandates!( connector::Checkout, connector::Cryptopay, connector::Coinbase, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2701,6 +2729,7 @@ default_imp_for_connector_authentication!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2787,6 +2816,7 @@ default_imp_for_authorize_session_token!( connector::Cryptopay, connector::Coinbase, connector::Cybersource, + connector::Datatrans, connector::Dlocal, connector::Ebanx, connector::Fiserv, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index a40fb22e0b9..062d0b4da81 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -331,6 +331,7 @@ impl ConnectorData { enums::Connector::Coinbase => Ok(Box::new(&connector::Coinbase)), enums::Connector::Cryptopay => Ok(Box::new(connector::Cryptopay::new())), enums::Connector::Cybersource => Ok(Box::new(&connector::Cybersource)), + // enums::Connector::Datatrans => Ok(Box::new(&connector::Datatrans)), added as template code for future use enums::Connector::Dlocal => Ok(Box::new(&connector::Dlocal)), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector1 => Ok(Box::new(&connector::DummyConnector::<1>)), diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 94d84d8ccae..404297e4aad 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -224,6 +224,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Coinbase => Self::Coinbase, api_enums::Connector::Cryptopay => Self::Cryptopay, api_enums::Connector::Cybersource => Self::Cybersource, + // api_enums::Connector::Datatrans => Self::Datatrans, added as template code for future use api_enums::Connector::Dlocal => Self::Dlocal, api_enums::Connector::Ebanx => Self::Ebanx, api_enums::Connector::Fiserv => Self::Fiserv, diff --git a/crates/router/tests/connectors/datatrans.rs b/crates/router/tests/connectors/datatrans.rs new file mode 100644 index 00000000000..cc87b29d5bd --- /dev/null +++ b/crates/router/tests/connectors/datatrans.rs @@ -0,0 +1,420 @@ +use masking::Secret; +use router::types::{self, api, domain, storage::enums}; +use test_utils::connector_auth; + +use crate::utils::{self, ConnectorActions}; + +#[derive(Clone, Copy)] +struct DatatransTest; +impl ConnectorActions for DatatransTest {} +impl utils::Connector for DatatransTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Adyen; + api::ConnectorData { + connector: Box::new(&Adyen), + connector_name: types::Connector::Adyen, + get_token: api::GetToken::Connector, + merchant_connector_id: None, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .datatrans + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "datatrans".to_string() + } +} + +static CONNECTOR: DatatransTest = DatatransTest {}; + +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + None +} + +fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { + None +} + +// Cards Positive Tests +// Creates a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +// Captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Partially captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + payment_method_details(), + Some(types::PaymentsCaptureData { + amount_to_capture: 50, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +// Voids a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment( + payment_method_details(), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("Void payment response"); + assert_eq!(response.status, enums::AttemptStatus::Voided); +} + +// Refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Synchronizes a refund using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_manually_captured_refund() { + let refund_response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_make_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_auto_captured_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + capture_method: Some(enums::CaptureMethod::Automatic), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Charged,); +} + +// Refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_auto_captured_payment() { + let response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let refund_response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + CONNECTOR + .make_payment_and_multiple_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await; +} + +// Synchronizes a refund using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_refund() { + let refund_response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Cards Negative scenarios +// Creates a payment with incorrect CVC. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's security code is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry month. +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration month is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry year. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_expiry_year() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration year is invalid.".to_string(), + ); +} + +// Voids a payment using automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_fail_void_payment_for_auto_capture() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let void_response = CONNECTOR + .void_payment(txn_id.unwrap(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + void_response.response.unwrap_err().message, + "You cannot cancel this PaymentIntent because it has a status of succeeded." + ); +} + +// Captures a payment using invalid connector payment id. +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let capture_response = CONNECTOR + .capture_payment("123456789".to_string(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("No such payment_intent: '123456789'") + ); +} + +// Refunds a payment with refund amount higher than payment amount. +#[actix_web::test] +async fn should_fail_for_refund_amount_higher_than_payment_amount() { + let response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Refund amount (₹1.50) is greater than charge amount (₹1.00)", + ); +} + +// Connector dependent test cases goes here + +// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 892e1370ccc..ad19a54bbda 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -24,6 +24,7 @@ mod checkout; mod coinbase; mod cryptopay; mod cybersource; +mod datatrans; mod dlocal; #[cfg(feature = "dummy_connector")] mod dummyconnector; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 2d7b1974996..655e7c665ae 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -233,3 +233,6 @@ api_key="API Key" [adyenplatform] api_key="API Key" + +[datatrans] +api_key="API Key" diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 4b41506fe2d..aafccbff438 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -29,6 +29,7 @@ pub struct ConnectorAuthentication { pub coinbase: Option<HeaderKey>, pub cryptopay: Option<BodyKey>, pub cybersource: Option<SignatureKey>, + pub datatrans: Option<HeaderKey>, pub dlocal: Option<SignatureKey>, #[cfg(feature = "dummy_connector")] pub dummyconnector: Option<HeaderKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index d008ff3231c..d2dd483e9ad 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -91,6 +91,7 @@ checkout.base_url = "https://api.sandbox.checkout.com/" coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" +datatrans.base_url = "https://api.sandbox.datatrans.com/" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" @@ -168,6 +169,7 @@ cards = [ "coinbase", "cryptopay", "cybersource", + "datatrans", "dlocal", "dummyconnector", "ebanx", diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index f35d080bfe6..f4b4fc87578 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -6,7 +6,7 @@ function find_prev_connector() { git checkout $self cp $self $self.tmp # Add new connector to existing list and sort it - connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector ebanx fiserv forte globalpay globepay gocardless gpayments helcim iatapay klarna mifinity mollie multisafepay netcetera nexinets noon nuvei opayo opennode payeezy payme payone paypal payu placetopay powertranz prophetpay rapyd shift4 square stax stripe threedsecureio trustpay tsys volt wise worldline worldpay zsl "$1") + connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans dlocal dummyconnector ebanx fiserv forte globalpay globepay gocardless gpayments helcim iatapay klarna mifinity mollie multisafepay netcetera nexinets noon nuvei opayo opennode payeezy payme payone paypal payu placetopay powertranz prophetpay rapyd shift4 square stax stripe threedsecureio trustpay tsys volt wise worldline worldpay zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res=`echo ${sorted[@]}` sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
2024-06-05T13:30:31Z
## Description <!-- Describe your changes in detail --> Added Template code for Datatrans. Ran add_connector.sh script ### 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? <!-- No testing needed , Just added Template code for connector -->
0e059e7d847b0c15ed120c72bb4902ac60e6f955
[ "config/config.example.toml", "config/deployments/integration_test.toml", "config/deployments/production.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/src/enums.rs", "crates/common_enums/src/enums.rs", "crates/router/src/configs...
juspay/hyperswitch
juspay__hyperswitch-4887
Bug: bug(user): Wrong Internal user `org_id` Currently when an internal user is being created, a new user will be created and a `user_role` with `merchant_id` as `juspay000` will also be inserted. As the merchant `juspay000` already has a `org_id`, we should use that and insert that `org_id` in `user_role`, but currently a new `org_id` is being generated and inserted everytime when this API is hit.
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index cfc01afb91b..65d605b3862 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1046,11 +1046,6 @@ pub async fn create_internal_user( state: SessionState, request: user_api::CreateInternalUserRequest, ) -> UserResponse<()> { - let new_user = domain::NewUser::try_from(request)?; - - let mut store_user: storage_user::UserNew = new_user.clone().try_into()?; - store_user.set_is_verified(true); - let key_store = state .store .get_merchant_key_store_by_merchant_id( @@ -1066,7 +1061,7 @@ pub async fn create_internal_user( } })?; - state + let internal_merchant = state .store .find_merchant_account_by_merchant_id( consts::user_role::INTERNAL_USER_MERCHANT_ID, @@ -1081,6 +1076,11 @@ pub async fn create_internal_user( } })?; + let new_user = domain::NewUser::try_from((request, internal_merchant.organization_id))?; + + let mut store_user: storage_user::UserNew = new_user.clone().try_into()?; + store_user.set_is_verified(true); + state .store .insert_user(store_user) diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 60d75ce81d1..0ff9d651baf 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -284,9 +284,12 @@ impl From<user_api::ConnectAccountRequest> for NewUserOrganization { } } -impl From<user_api::CreateInternalUserRequest> for NewUserOrganization { - fn from(_value: user_api::CreateInternalUserRequest) -> Self { - let new_organization = api_org::OrganizationNew::new(None); +impl From<(user_api::CreateInternalUserRequest, String)> for NewUserOrganization { + fn from((_value, org_id): (user_api::CreateInternalUserRequest, String)) -> Self { + let new_organization = api_org::OrganizationNew { + org_id, + org_name: None, + }; let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } @@ -457,10 +460,10 @@ impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserMerchant { } } -impl TryFrom<user_api::CreateInternalUserRequest> for NewUserMerchant { +impl TryFrom<(user_api::CreateInternalUserRequest, String)> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; - fn try_from(value: user_api::CreateInternalUserRequest) -> UserResult<Self> { + fn try_from(value: (user_api::CreateInternalUserRequest, String)) -> UserResult<Self> { let merchant_id = MerchantId::new(consts::user_role::INTERNAL_USER_MERCHANT_ID.to_string())?; let new_organization = NewUserOrganization::from(value); @@ -702,15 +705,17 @@ impl TryFrom<user_api::ConnectAccountRequest> for NewUser { } } -impl TryFrom<user_api::CreateInternalUserRequest> for NewUser { +impl TryFrom<(user_api::CreateInternalUserRequest, String)> for NewUser { type Error = error_stack::Report<UserErrors>; - fn try_from(value: user_api::CreateInternalUserRequest) -> UserResult<Self> { + fn try_from( + (value, org_id): (user_api::CreateInternalUserRequest, String), + ) -> UserResult<Self> { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.email.clone().try_into()?; let name = UserName::new(value.name.clone())?; let password = UserPassword::new(value.password.clone())?; - let new_merchant = NewUserMerchant::try_from(value)?; + let new_merchant = NewUserMerchant::try_from((value, org_id))?; Ok(Self { user_id,
2024-06-05T11:40:33Z
## Description <!-- Describe your changes in detail --> Internal signup will now use the `org_id` of `juspay000` and insert it in `user_roles`. ### 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 #4887. ## 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/internal_signup' \ --header 'api-key: admin-api-key' \ --header 'Content-Type: application/json' \ --data-raw '{ "name" : "name", "email" : "email", "password": "password" }' ``` In `user_roles` table, the `org_id` is the correct one as the `juspay000` merchant account. These are the queries I've used to verify. ```sql select organization_id from merchant_account where merchant_id = 'juspay000' ``` ```sql select org_id from user_roles where merchant_id = 'juspay000' ``` In both cases, `org_id` should be same for newly created user.
7ab65ac8834f47c4448b64899ce3e3656132fb63
``` curl --location 'http://localhost:8080/user/internal_signup' \ --header 'api-key: admin-api-key' \ --header 'Content-Type: application/json' \ --data-raw '{ "name" : "name", "email" : "email", "password": "password" }' ``` In `user_roles` table, the `org_id` is the correct one as the `juspay000` merchant account. These are the queries I've used to verify. ```sql select organization_id from merchant_account where merchant_id = 'juspay000' ``` ```sql select org_id from user_roles where merchant_id = 'juspay000' ``` In both cases, `org_id` should be same for newly created user.
[ "crates/router/src/core/user.rs", "crates/router/src/types/domain/user.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4881
Bug: FRM Analytics Add FRM analytics and corresponding endpoints
diff --git a/Cargo.lock b/Cargo.lock index 557504d98b9..cfd0da1eed2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -340,6 +340,7 @@ dependencies = [ "aws-sdk-lambda", "aws-smithy-types 1.1.8", "bigdecimal", + "common_enums", "common_utils", "diesel_models", "error-stack", @@ -1943,6 +1944,8 @@ name = "common_enums" version = "0.1.0" dependencies = [ "diesel", + "frunk", + "frunk_core", "router_derive", "serde", "serde_json", diff --git a/config/config.example.toml b/config/config.example.toml index 4e3747eb8f7..d3f7771934b 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -623,6 +623,7 @@ source = "logs" # The event sink to push events supports kafka or logs (stdout) [events.kafka] brokers = [] # Kafka broker urls for bootstrapping the client +fraud_check_analytics_topic = "topic" # Kafka topic to be used for FraudCheck events intent_analytics_topic = "topic" # Kafka topic to be used for PaymentIntent events attempt_analytics_topic = "topic" # Kafka topic to be used for PaymentAttempt events refund_analytics_topic = "topic" # Kafka topic to be used for Refund events diff --git a/config/development.toml b/config/development.toml index 2aaf0e69922..c66ce39224d 100644 --- a/config/development.toml +++ b/config/development.toml @@ -615,6 +615,7 @@ source = "logs" [events.kafka] brokers = ["localhost:9092"] +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" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 2b934ceb20f..6d7414d6abd 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -435,6 +435,7 @@ delay_between_retries_in_milliseconds = 500 [events.kafka] brokers = ["localhost:9092"] +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" diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml index 52680df5c49..8cf4b9b911c 100644 --- a/crates/analytics/Cargo.toml +++ b/crates/analytics/Cargo.toml @@ -15,6 +15,7 @@ api_models = { version = "0.1.0", path = "../api_models", features = [ "errors", ] } storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false } +common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils" } external_services = { version = "0.1.0", path = "../external_services", default-features = false } hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" } diff --git a/crates/analytics/docs/clickhouse/scripts/fraud_check.sql b/crates/analytics/docs/clickhouse/scripts/fraud_check.sql new file mode 100644 index 00000000000..19e535981b6 --- /dev/null +++ b/crates/analytics/docs/clickhouse/scripts/fraud_check.sql @@ -0,0 +1,132 @@ +CREATE TABLE fraud_check_queue ( + `frm_id` String, + `payment_id` String, + `merchant_id` String, + `attempt_id` String, + `created_at` DateTime CODEC(T64, LZ4), + `frm_name` LowCardinality(String), + `frm_transaction_id` String, + `frm_transaction_type` LowCardinality(String), + `frm_status` LowCardinality(String), + `frm_score` Int32, + `frm_reason` LowCardinality(String), + `frm_error` Nullable(String), + `amount` UInt32, + `currency` LowCardinality(String), + `payment_method` LowCardinality(String), + `payment_method_type` LowCardinality(String), + `refund_transaction_id` Nullable(String), + `metadata` Nullable(String), + `modified_at` DateTime CODEC(T64, LZ4), + `last_step` LowCardinality(String), + `payment_capture_method` LowCardinality(String), + `sign_flag` Int8 +) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', +kafka_topic_list = 'hyperswitch-fraud-check-events', +kafka_group_name = 'hyper', +kafka_format = 'JSONEachRow', +kafka_handle_error_mode = 'stream'; + +CREATE TABLE fraud_check ( + `frm_id` String, + `payment_id` String, + `merchant_id` LowCardinality(String), + `attempt_id` String, + `created_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `frm_name` LowCardinality(String), + `frm_transaction_id` String, + `frm_transaction_type` LowCardinality(String), + `frm_status` LowCardinality(String), + `frm_score` Int32, + `frm_reason` LowCardinality(String), + `frm_error` Nullable(String), + `amount` UInt32, + `currency` LowCardinality(String), + `payment_method` LowCardinality(String), + `payment_method_type` LowCardinality(String), + `refund_transaction_id` Nullable(String), + `metadata` Nullable(String), + `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `last_step` LowCardinality(String), + `payment_capture_method` LowCardinality(String), + `sign_flag` Int8 + INDEX frmNameIndex frm_name TYPE bloom_filter GRANULARITY 1, + INDEX frmStatusIndex frm_status TYPE bloom_filter GRANULARITY 1, + INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1, + INDEX paymentMethodTypeIndex payment_method_type TYPE bloom_filter GRANULARITY 1, + INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1 +) ENGINE = CollapsingMergeTree(sign_flag) PARTITION BY toStartOfDay(created_at) +ORDER BY + (created_at, merchant_id, attempt_id, frm_id) TTL created_at + toIntervalMonth(18) SETTINGS index_granularity = 8192; + +CREATE MATERIALIZED VIEW fraud_check_mv TO fraud_check ( + `frm_id` String, + `payment_id` String, + `merchant_id` String, + `attempt_id` String, + `created_at` DateTime64(3), + `frm_name` LowCardinality(String), + `frm_transaction_id` String, + `frm_transaction_type` LowCardinality(String), + `frm_status` LowCardinality(String), + `frm_score` Int32, + `frm_reason` LowCardinality(String), + `frm_error` Nullable(String), + `amount` UInt32, + `currency` LowCardinality(String), + `payment_method` LowCardinality(String), + `payment_method_type` LowCardinality(String), + `refund_transaction_id` Nullable(String), + `metadata` Nullable(String), + `modified_at` DateTime64(3), + `last_step` LowCardinality(String), + `payment_capture_method` LowCardinality(String), + `sign_flag` Int8 +) AS +SELECT + frm_id, + payment_id, + merchant_id, + attempt_id, + created_at, + frm_name, + frm_transaction_id, + frm_transaction_type, + frm_status, + frm_score, + frm_reason, + frm_error, + amount, + currency, + payment_method, + payment_method_type, + refund_transaction_id, + metadata, + modified_at, + last_step, + payment_capture_method, + sign_flag +FROM + fraud_check_queue +WHERE + length(_error) = 0; + +CREATE MATERIALIZED VIEW fraud_check_parse_errors ( + `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 + fraud_check_queue +WHERE + length(_error) > 0; \ No newline at end of file diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index b455e79b253..ffca5487137 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -9,6 +9,7 @@ use time::PrimitiveDateTime; use super::{ active_payments::metrics::ActivePaymentsMetricRow, auth_events::metrics::AuthEventMetricRow, + frm::{filters::FrmFilterRow, metrics::FrmMetricRow}, health_check::HealthCheck, payment_intents::{filters::PaymentIntentFilterRow, metrics::PaymentIntentMetricRow}, payments::{ @@ -130,6 +131,7 @@ impl AnalyticsDataSource for ClickhouseClient { match table { AnalyticsCollection::Payment | AnalyticsCollection::Refund + | AnalyticsCollection::FraudCheck | AnalyticsCollection::PaymentIntent | AnalyticsCollection::Dispute => { TableEngine::CollapsingMergeTree { sign: "sign_flag" } @@ -162,6 +164,8 @@ impl super::payment_intents::filters::PaymentIntentFilterAnalytics for Clickhous impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for ClickhouseClient {} impl super::refunds::metrics::RefundMetricAnalytics for ClickhouseClient {} impl super::refunds::filters::RefundFilterAnalytics for ClickhouseClient {} +impl super::frm::metrics::FrmMetricAnalytics for ClickhouseClient {} +impl super::frm::filters::FrmFilterAnalytics for ClickhouseClient {} impl super::sdk_events::filters::SdkEventFilterAnalytics for ClickhouseClient {} impl super::sdk_events::metrics::SdkEventMetricAnalytics for ClickhouseClient {} impl super::sdk_events::events::SdkEventsFilterAnalytics for ClickhouseClient {} @@ -290,6 +294,25 @@ impl TryInto<RefundFilterRow> for serde_json::Value { } } +impl TryInto<FrmMetricRow> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<FrmMetricRow, Self::Error> { + serde_json::from_value(self).change_context(ParsingError::StructParseFailure( + "Failed to parse FrmMetricRow in clickhouse results", + )) + } +} + +impl TryInto<FrmFilterRow> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<FrmFilterRow, Self::Error> { + serde_json::from_value(self).change_context(ParsingError::StructParseFailure( + "Failed to parse FrmFilterRow in clickhouse results", + )) + } +} impl TryInto<DisputeMetricRow> for serde_json::Value { type Error = Report<ParsingError>; @@ -409,6 +432,7 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection { match self { Self::Payment => Ok("payment_attempts".to_string()), Self::Refund => Ok("refunds".to_string()), + Self::FraudCheck => Ok("fraud_check".to_string()), Self::SdkEvents => Ok("sdk_events_audit".to_string()), Self::SdkEventsAnalytics => Ok("sdk_events".to_string()), Self::ApiEvents => Ok("api_events_audit".to_string()), diff --git a/crates/analytics/src/core.rs b/crates/analytics/src/core.rs index 2c5945f75b5..0e3ced7993d 100644 --- a/crates/analytics/src/core.rs +++ b/crates/analytics/src/core.rs @@ -21,6 +21,11 @@ pub async fn get_domain_info( download_dimensions: None, dimensions: utils::get_refund_dimensions(), }, + AnalyticsDomain::Frm => GetInfoResponse { + metrics: utils::get_frm_metrics_info(), + download_dimensions: None, + dimensions: utils::get_frm_dimensions(), + }, AnalyticsDomain::SdkEvents => GetInfoResponse { metrics: utils::get_sdk_event_metrics_info(), download_dimensions: None, diff --git a/crates/analytics/src/frm.rs b/crates/analytics/src/frm.rs new file mode 100644 index 00000000000..7598bddaaef --- /dev/null +++ b/crates/analytics/src/frm.rs @@ -0,0 +1,9 @@ +pub mod accumulator; +mod core; + +pub mod filters; +pub mod metrics; +pub mod types; +pub use accumulator::{FrmMetricAccumulator, FrmMetricsAccumulator}; + +pub use self::core::{get_filters, get_metrics}; diff --git a/crates/analytics/src/frm/accumulator.rs b/crates/analytics/src/frm/accumulator.rs new file mode 100644 index 00000000000..04b60beb98e --- /dev/null +++ b/crates/analytics/src/frm/accumulator.rs @@ -0,0 +1,78 @@ +use api_models::analytics::frm::FrmMetricsBucketValue; +use common_enums::enums as storage_enums; + +use super::metrics::FrmMetricRow; +#[derive(Debug, Default)] +pub struct FrmMetricsAccumulator { + pub frm_triggered_attempts: TriggeredAttemptsAccumulator, + pub frm_blocked_rate: BlockedRateAccumulator, +} + +#[derive(Debug, Default)] +#[repr(transparent)] +pub struct TriggeredAttemptsAccumulator { + pub count: Option<i64>, +} + +#[derive(Debug, Default)] +pub struct BlockedRateAccumulator { + pub fraud: i64, + pub total: i64, +} + +pub trait FrmMetricAccumulator { + type MetricOutput; + + fn add_metrics_bucket(&mut self, metrics: &FrmMetricRow); + + fn collect(self) -> Self::MetricOutput; +} + +impl FrmMetricAccumulator for TriggeredAttemptsAccumulator { + type MetricOutput = Option<u64>; + #[inline] + fn add_metrics_bucket(&mut self, metrics: &FrmMetricRow) { + self.count = match (self.count, metrics.count) { + (None, None) => None, + (None, i @ Some(_)) | (i @ Some(_), None) => i, + (Some(a), Some(b)) => Some(a + b), + } + } + #[inline] + fn collect(self) -> Self::MetricOutput { + self.count.and_then(|i| u64::try_from(i).ok()) + } +} + +impl FrmMetricAccumulator for BlockedRateAccumulator { + type MetricOutput = Option<f64>; + + fn add_metrics_bucket(&mut self, metrics: &FrmMetricRow) { + if let Some(ref frm_status) = metrics.frm_status { + if frm_status.as_ref() == &storage_enums::FraudCheckStatus::Fraud { + self.fraud += metrics.count.unwrap_or_default(); + } + }; + self.total += metrics.count.unwrap_or_default(); + } + + fn collect(self) -> Self::MetricOutput { + if self.total <= 0 { + None + } else { + Some( + f64::from(u32::try_from(self.fraud).ok()?) * 100.0 + / f64::from(u32::try_from(self.total).ok()?), + ) + } + } +} + +impl FrmMetricsAccumulator { + pub fn collect(self) -> FrmMetricsBucketValue { + FrmMetricsBucketValue { + frm_blocked_rate: self.frm_blocked_rate.collect(), + frm_triggered_attempts: self.frm_triggered_attempts.collect(), + } + } +} diff --git a/crates/analytics/src/frm/core.rs b/crates/analytics/src/frm/core.rs new file mode 100644 index 00000000000..9c9e73b49a8 --- /dev/null +++ b/crates/analytics/src/frm/core.rs @@ -0,0 +1,193 @@ +#![allow(dead_code)] +use std::collections::HashMap; + +use api_models::analytics::{ + frm::{FrmDimensions, FrmMetrics, FrmMetricsBucketIdentifier, FrmMetricsBucketResponse}, + AnalyticsMetadata, FrmFilterValue, FrmFiltersResponse, GetFrmFilterRequest, + GetFrmMetricRequest, MetricsResponse, +}; +use error_stack::ResultExt; +use router_env::{ + logger, + metrics::add_attributes, + tracing::{self, Instrument}, +}; + +use super::{ + filters::{get_frm_filter_for_dimension, FrmFilterRow}, + FrmMetricsAccumulator, +}; +use crate::{ + errors::{AnalyticsError, AnalyticsResult}, + frm::FrmMetricAccumulator, + metrics, AnalyticsProvider, +}; + +pub async fn get_metrics( + pool: &AnalyticsProvider, + merchant_id: &String, + req: GetFrmMetricRequest, +) -> AnalyticsResult<MetricsResponse<FrmMetricsBucketResponse>> { + let mut metrics_accumulator: HashMap<FrmMetricsBucketIdentifier, FrmMetricsAccumulator> = + HashMap::new(); + let mut set = tokio::task::JoinSet::new(); + for metric_type in req.metrics.iter().cloned() { + let req = req.clone(); + let pool = pool.clone(); + let task_span = + tracing::debug_span!("analytics_frm_query", frm_metric = metric_type.as_ref()); + // Currently JoinSet works with only static lifetime references even if the task pool does not outlive the given reference + // We can optimize away this clone once that is fixed + let merchant_id_scoped = merchant_id.to_owned(); + set.spawn( + async move { + let data = pool + .get_frm_metrics( + &metric_type, + &req.group_by_names.clone(), + &merchant_id_scoped, + &req.filters, + &req.time_series.map(|t| t.granularity), + &req.time_range, + ) + .await + .change_context(AnalyticsError::UnknownError); + (metric_type, data) + } + .instrument(task_span), + ); + } + + while let Some((metric, data)) = set + .join_next() + .await + .transpose() + .change_context(AnalyticsError::UnknownError)? + { + let data = data?; + + let attributes = &add_attributes([ + ("metric_type", metric.to_string()), + ("source", pool.to_string()), + ]); + let value = u64::try_from(data.len()); + if let Ok(val) = value { + metrics::BUCKETS_FETCHED.record(&metrics::CONTEXT, val, attributes); + logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val); + } + + for (id, value) in data { + logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}"); + let metrics_builder = metrics_accumulator.entry(id).or_default(); + match metric { + FrmMetrics::FrmBlockedRate => { + metrics_builder.frm_blocked_rate.add_metrics_bucket(&value) + } + FrmMetrics::FrmTriggeredAttempts => metrics_builder + .frm_triggered_attempts + .add_metrics_bucket(&value), + } + } + + logger::debug!( + "Analytics Accumulated Results: metric: {}, results: {:#?}", + metric, + metrics_accumulator + ); + } + let query_data: Vec<FrmMetricsBucketResponse> = metrics_accumulator + .into_iter() + .map(|(id, val)| FrmMetricsBucketResponse { + values: val.collect(), + dimensions: id, + }) + .collect(); + + Ok(MetricsResponse { + query_data, + meta_data: [AnalyticsMetadata { + current_time_range: req.time_range, + }], + }) +} + +pub async fn get_filters( + pool: &AnalyticsProvider, + req: GetFrmFilterRequest, + merchant_id: &String, +) -> AnalyticsResult<FrmFiltersResponse> { + let mut res = FrmFiltersResponse::default(); + for dim in req.group_by_names { + let values = match pool { + AnalyticsProvider::Sqlx(pool) => { + get_frm_filter_for_dimension(dim, merchant_id, &req.time_range, pool) + .await +} + AnalyticsProvider::Clickhouse(pool) => { + get_frm_filter_for_dimension(dim, merchant_id, &req.time_range, pool) + .await +} + AnalyticsProvider::CombinedCkh(sqlx_pool, ckh_pool) => { + let ckh_result = get_frm_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + ckh_pool, + ) + .await; + let sqlx_result = get_frm_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 => { + logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres frm analytics filters") + }, + _ => {} + }; + ckh_result +} + AnalyticsProvider::CombinedSqlx(sqlx_pool, ckh_pool) => { + let ckh_result = get_frm_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + ckh_pool, + ) + .await; + let sqlx_result = get_frm_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 => { + logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres frm analytics filters") + }, + _ => {} + }; + sqlx_result +} +} + .change_context(AnalyticsError::UnknownError)? + .into_iter() + .filter_map(|fil: FrmFilterRow| match dim { + FrmDimensions::FrmStatus => fil.frm_status.map(|i| i.as_ref().to_string()), + FrmDimensions::FrmName => fil.frm_name, + FrmDimensions::FrmTransactionType => { + fil.frm_transaction_type.map(|i| i.as_ref().to_string()) + } + }) + .collect::<Vec<String>>(); + res.query_data.push(FrmFilterValue { + dimension: dim, + values, + }) + } + Ok(res) +} diff --git a/crates/analytics/src/frm/filters.rs b/crates/analytics/src/frm/filters.rs new file mode 100644 index 00000000000..c019f61d427 --- /dev/null +++ b/crates/analytics/src/frm/filters.rs @@ -0,0 +1,59 @@ +use api_models::analytics::{ + frm::{FrmDimensions, FrmTransactionType}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use diesel_models::enums::FraudCheckStatus; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + types::{ + AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult, + LoadRow, + }, +}; +pub trait FrmFilterAnalytics: LoadRow<FrmFilterRow> {} + +pub async fn get_frm_filter_for_dimension<T>( + dimension: FrmDimensions, + merchant: &String, + time_range: &TimeRange, + pool: &T, +) -> FiltersResult<Vec<FrmFilterRow>> +where + T: AnalyticsDataSource + FrmFilterAnalytics, + 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::FraudCheck); + + 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::<FrmFilterRow, _>(pool) + .await + .change_context(FiltersError::QueryBuildingError)? + .change_context(FiltersError::QueryExecutionFailure) +} + +#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] +pub struct FrmFilterRow { + pub frm_status: Option<DBEnumWrapper<FraudCheckStatus>>, + pub frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>>, + pub frm_name: Option<String>, +} diff --git a/crates/analytics/src/frm/metrics.rs b/crates/analytics/src/frm/metrics.rs new file mode 100644 index 00000000000..8f904090983 --- /dev/null +++ b/crates/analytics/src/frm/metrics.rs @@ -0,0 +1,99 @@ +use api_models::analytics::{ + frm::{FrmDimensions, FrmFilters, FrmMetrics, FrmMetricsBucketIdentifier, FrmTransactionType}, + Granularity, TimeRange, +}; +use diesel_models::enums as storage_enums; +use time::PrimitiveDateTime; +mod frm_blocked_rate; +mod frm_triggered_attempts; + +use frm_blocked_rate::FrmBlockedRate; +use frm_triggered_attempts::FrmTriggeredAttempts; + +use crate::{ + query::{Aggregate, GroupByClause, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, +}; +#[derive(Debug, Eq, PartialEq, serde::Deserialize)] +pub struct FrmMetricRow { + pub frm_name: Option<String>, + pub frm_status: Option<DBEnumWrapper<storage_enums::FraudCheckStatus>>, + pub frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>>, + pub total: Option<bigdecimal::BigDecimal>, + pub count: Option<i64>, + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub start_bucket: Option<PrimitiveDateTime>, + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub end_bucket: Option<PrimitiveDateTime>, +} + +pub trait FrmMetricAnalytics: LoadRow<FrmMetricRow> {} + +#[async_trait::async_trait] +pub trait FrmMetric<T> +where + T: AnalyticsDataSource + FrmMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[FrmDimensions], + merchant_id: &str, + filters: &FrmFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>>; +} + +#[async_trait::async_trait] +impl<T> FrmMetric<T> for FrmMetrics +where + T: AnalyticsDataSource + FrmMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[FrmDimensions], + merchant_id: &str, + filters: &FrmFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>> { + match self { + Self::FrmTriggeredAttempts => { + FrmTriggeredAttempts::default() + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::FrmBlockedRate => { + FrmBlockedRate::default() + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + } + } +} diff --git a/crates/analytics/src/frm/metrics/frm_blocked_rate.rs b/crates/analytics/src/frm/metrics/frm_blocked_rate.rs new file mode 100644 index 00000000000..5f331feab6c --- /dev/null +++ b/crates/analytics/src/frm/metrics/frm_blocked_rate.rs @@ -0,0 +1,117 @@ +use api_models::analytics::{ + frm::{FrmDimensions, FrmFilters, FrmMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::FrmMetricRow; +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; +#[derive(Default)] +pub(super) struct FrmBlockedRate {} + +#[async_trait::async_trait] +impl<T> super::FrmMetric<T> for FrmBlockedRate +where + T: AnalyticsDataSource + super::FrmMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[FrmDimensions], + merchant_id: &str, + filters: &FrmFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>> + where + T: AnalyticsDataSource + super::FrmMetricAnalytics, + { + let mut query_builder = QueryBuilder::new(AnalyticsCollection::FraudCheck); + let mut dimensions = dimensions.to_vec(); + + dimensions.push(FrmDimensions::FrmStatus); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + + time_range.set_filter_clause(&mut query_builder).switch()?; + + for dim in dimensions.iter() { + query_builder.add_group_by_clause(dim).switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .switch()?; + } + + query_builder + .execute_query::<FrmMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + FrmMetricsBucketIdentifier::new( + i.frm_name.as_ref().map(|i| i.to_string()), + None, + i.frm_transaction_type.as_ref().map(|i| i.0.to_string()), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/frm/metrics/frm_triggered_attempts.rs b/crates/analytics/src/frm/metrics/frm_triggered_attempts.rs new file mode 100644 index 00000000000..b72345c4e3a --- /dev/null +++ b/crates/analytics/src/frm/metrics/frm_triggered_attempts.rs @@ -0,0 +1,116 @@ +use api_models::analytics::{ + frm::{FrmDimensions, FrmFilters, FrmMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::FrmMetricRow; +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct FrmTriggeredAttempts {} + +#[async_trait::async_trait] +impl<T> super::FrmMetric<T> for FrmTriggeredAttempts +where + T: AnalyticsDataSource + super::FrmMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[FrmDimensions], + merchant_id: &str, + filters: &FrmFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>> { + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::FraudCheck); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<FrmMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + FrmMetricsBucketIdentifier::new( + i.frm_name.as_ref().map(|i| i.to_string()), + i.frm_status.as_ref().map(|i| i.0.to_string()), + i.frm_transaction_type.as_ref().map(|i| i.0.to_string()), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result<Vec<_>, crate::query::PostProcessingError>>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/frm/types.rs b/crates/analytics/src/frm/types.rs new file mode 100644 index 00000000000..72fc65098bd --- /dev/null +++ b/crates/analytics/src/frm/types.rs @@ -0,0 +1,38 @@ +use api_models::analytics::frm::{FrmDimensions, FrmFilters}; +use error_stack::ResultExt; + +use crate::{ + query::{QueryBuilder, QueryFilter, QueryResult, ToSql}, + types::{AnalyticsCollection, AnalyticsDataSource}, +}; + +impl<T> QueryFilter<T> for FrmFilters +where + T: AnalyticsDataSource, + AnalyticsCollection: ToSql<T>, +{ + fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> { + if !self.frm_status.is_empty() { + builder + .add_filter_in_range_clause(FrmDimensions::FrmStatus, &self.frm_status) + .attach_printable("Error adding frm status filter")?; + } + + if !self.frm_name.is_empty() { + builder + .add_filter_in_range_clause(FrmDimensions::FrmName, &self.frm_name) + .attach_printable("Error adding frm name filter")?; + } + + if !self.frm_transaction_type.is_empty() { + builder + .add_filter_in_range_clause( + FrmDimensions::FrmTransactionType, + &self.frm_transaction_type, + ) + .attach_printable("Error adding frm transaction type filter")?; + } + + Ok(()) + } +} diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 10e628475e8..69afcec5524 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -2,6 +2,7 @@ mod clickhouse; pub mod core; pub mod disputes; pub mod errors; +pub mod frm; pub mod metrics; pub mod payment_intents; pub mod payments; @@ -40,6 +41,7 @@ use api_models::analytics::{ }, auth_events::{AuthEventMetrics, AuthEventMetricsBucketIdentifier}, disputes::{DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier}, + frm::{FrmDimensions, FrmFilters, FrmMetrics, FrmMetricsBucketIdentifier}, payment_intents::{ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetrics, PaymentIntentMetricsBucketIdentifier, @@ -65,6 +67,7 @@ use strum::Display; use self::{ active_payments::metrics::{ActivePaymentsMetric, ActivePaymentsMetricRow}, auth_events::metrics::{AuthEventMetric, AuthEventMetricRow}, + frm::metrics::{FrmMetric, FrmMetricRow}, payment_intents::metrics::{PaymentIntentMetric, PaymentIntentMetricRow}, payments::{ distribution::{PaymentDistribution, PaymentDistributionRow}, @@ -524,6 +527,106 @@ impl AnalyticsProvider { .await } + pub async fn get_frm_metrics( + &self, + metric: &FrmMetrics, + dimensions: &[FrmDimensions], + merchant_id: &str, + filters: &FrmFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + ) -> types::MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>> { + // Metrics to get the fetch time for each refund metric + metrics::request::record_operation_time( + async { + match self { + Self::Sqlx(pool) => { + metric + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::Clickhouse(pool) => { + metric + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::CombinedCkh(sqlx_pool, ckh_pool) => { + let (ckh_result, sqlx_result) = tokio::join!( + metric.load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + ckh_pool, + ), + metric.load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + sqlx_pool, + ) + ); + match (&sqlx_result, &ckh_result) { + (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { + logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres frm analytics metrics") + } + _ => {} + }; + ckh_result + } + Self::CombinedSqlx(sqlx_pool, ckh_pool) => { + let (ckh_result, sqlx_result) = tokio::join!( + metric.load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + ckh_pool, + ), + metric.load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + sqlx_pool, + ) + ); + match (&sqlx_result, &ckh_result) { + (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { + logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres frm analytics metrics") + } + _ => {} + }; + sqlx_result + } + } + }, + &metrics::METRIC_FETCH_TIME, + metric, + self, + ) + .await + } + pub async fn get_dispute_metrics( &self, metric: &DisputeMetrics, @@ -869,12 +972,14 @@ pub enum AnalyticsFlow { GetPaymentMetrics, GetPaymentIntentMetrics, GetRefundsMetrics, + GetFrmMetrics, GetSdkMetrics, GetAuthMetrics, GetActivePaymentsMetrics, GetPaymentFilters, GetPaymentIntentFilters, GetRefundFilters, + GetFrmFilters, GetSdkEventFilters, GetApiEvents, GetSdkEvents, diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index a257fedc09d..381deb60b80 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -6,6 +6,7 @@ use api_models::{ api_event::ApiEventDimensions, auth_events::AuthEventFlows, disputes::DisputeDimensions, + frm::{FrmDimensions, FrmTransactionType}, payment_intents::PaymentIntentDimensions, payments::{PaymentDimensions, PaymentDistributions}, refunds::{RefundDimensions, RefundType}, @@ -19,7 +20,7 @@ use api_models::{ refunds::RefundStatus, }; use common_utils::errors::{CustomResult, ParsingError}; -use diesel_models::enums as storage_enums; +use diesel_models::{enums as storage_enums, enums::FraudCheckStatus}; use error_stack::ResultExt; use router_env::{logger, Flow}; @@ -372,10 +373,12 @@ impl_to_sql_for_to_string!( &PaymentDimensions, &PaymentIntentDimensions, &RefundDimensions, + &FrmDimensions, PaymentDimensions, PaymentIntentDimensions, &PaymentDistributions, RefundDimensions, + FrmDimensions, PaymentMethod, PaymentMethodType, AuthenticationType, @@ -383,9 +386,11 @@ impl_to_sql_for_to_string!( AttemptStatus, IntentStatus, RefundStatus, + FraudCheckStatus, storage_enums::RefundStatus, Currency, RefundType, + FrmTransactionType, Flow, &String, &bool, diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 6a4faf50eb8..656a2448a44 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -1,7 +1,7 @@ use std::{fmt::Display, str::FromStr}; use api_models::{ - analytics::refunds::RefundType, + analytics::{frm::FrmTransactionType, refunds::RefundType}, enums::{DisputeStage, DisputeStatus}, }; use common_utils::{ @@ -9,7 +9,8 @@ use common_utils::{ DbConnectionParams, }; use diesel_models::enums::{ - AttemptStatus, AuthenticationType, Currency, IntentStatus, PaymentMethod, RefundStatus, + AttemptStatus, AuthenticationType, Currency, FraudCheckStatus, IntentStatus, PaymentMethod, + RefundStatus, }; use error_stack::ResultExt; use sqlx::{ @@ -91,6 +92,8 @@ db_type!(IntentStatus); db_type!(PaymentMethod, TEXT); db_type!(RefundStatus); db_type!(RefundType); +db_type!(FraudCheckStatus); +db_type!(FrmTransactionType); db_type!(DisputeStage); db_type!(DisputeStatus); @@ -150,6 +153,8 @@ impl super::refunds::metrics::RefundMetricAnalytics for SqlxClient {} impl super::refunds::filters::RefundFilterAnalytics for SqlxClient {} impl super::disputes::filters::DisputeFilterAnalytics for SqlxClient {} impl super::disputes::metrics::DisputeMetricAnalytics for SqlxClient {} +impl super::frm::metrics::FrmMetricAnalytics for SqlxClient {} +impl super::frm::filters::FrmFilterAnalytics for SqlxClient {} #[async_trait::async_trait] impl AnalyticsDataSource for SqlxClient { @@ -230,6 +235,49 @@ impl<'a> FromRow<'a, PgRow> for super::refunds::metrics::RefundMetricRow { } } +impl<'a> FromRow<'a, PgRow> for super::frm::metrics::FrmMetricRow { + fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { + let frm_name: Option<String> = row.try_get("frm_name").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let frm_status: Option<DBEnumWrapper<FraudCheckStatus>> = + row.try_get("frm_status").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>> = + row.try_get("frm_transaction_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let count: Option<i64> = row.try_get("count").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + // Removing millisecond precision to get accurate diffs against clickhouse + let start_bucket: Option<PrimitiveDateTime> = row + .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? + .and_then(|dt| dt.replace_millisecond(0).ok()); + let end_bucket: Option<PrimitiveDateTime> = row + .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? + .and_then(|dt| dt.replace_millisecond(0).ok()); + Ok(Self { + frm_name, + frm_status, + frm_transaction_type, + total, + count, + start_bucket, + end_bucket, + }) + } +} + impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = @@ -516,6 +564,30 @@ impl<'a> FromRow<'a, PgRow> for super::refunds::filters::RefundFilterRow { } } +impl<'a> FromRow<'a, PgRow> for super::frm::filters::FrmFilterRow { + fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { + let frm_name: Option<String> = row.try_get("frm_name").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let frm_status: Option<DBEnumWrapper<FraudCheckStatus>> = + row.try_get("frm_status").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>> = + row.try_get("frm_transaction_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + Ok(Self { + frm_name, + frm_status, + frm_transaction_type, + }) + } +} + 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 { @@ -604,6 +676,7 @@ impl ToSql<SqlxClient> for AnalyticsCollection { .attach_printable("SdkEvents table is not implemented for Sqlx"))?, Self::ApiEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ApiEvents table is not implemented for Sqlx"))?, + Self::FraudCheck => Ok("fraud_check".to_string()), Self::PaymentIntent => Ok("payment_intent".to_string()), Self::ConnectorEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ConnectorEvents table is not implemented for Sqlx"))?, diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs index 816c77fd304..12a82801d54 100644 --- a/crates/analytics/src/types.rs +++ b/crates/analytics/src/types.rs @@ -15,6 +15,7 @@ use crate::errors::AnalyticsError; pub enum AnalyticsDomain { Payments, Refunds, + Frm, PaymentIntents, AuthEvents, SdkEvents, @@ -26,6 +27,7 @@ pub enum AnalyticsDomain { pub enum AnalyticsCollection { Payment, Refund, + FraudCheck, SdkEvents, SdkEventsAnalytics, ApiEvents, diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs index 3955a8c1dfe..7b73f5a1c1d 100644 --- a/crates/analytics/src/utils.rs +++ b/crates/analytics/src/utils.rs @@ -2,6 +2,7 @@ use api_models::analytics::{ api_event::{ApiEventDimensions, ApiEventMetrics}, auth_events::AuthEventMetrics, disputes::{DisputeDimensions, DisputeMetrics}, + frm::{FrmDimensions, FrmMetrics}, payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics}, payments::{PaymentDimensions, PaymentMetrics}, refunds::{RefundDimensions, RefundMetrics}, @@ -22,6 +23,10 @@ pub fn get_refund_dimensions() -> Vec<NameDescription> { RefundDimensions::iter().map(Into::into).collect() } +pub fn get_frm_dimensions() -> Vec<NameDescription> { + FrmDimensions::iter().map(Into::into).collect() +} + pub fn get_sdk_event_dimensions() -> Vec<NameDescription> { SdkEventDimensions::iter().map(Into::into).collect() } @@ -42,6 +47,10 @@ pub fn get_refund_metrics_info() -> Vec<NameDescription> { RefundMetrics::iter().map(Into::into).collect() } +pub fn get_frm_metrics_info() -> Vec<NameDescription> { + FrmMetrics::iter().map(Into::into).collect() +} + pub fn get_sdk_event_metrics_info() -> Vec<NameDescription> { SdkEventMetrics::iter().map(Into::into).collect() } diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index 0bd0b01a278..80737cfbc41 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -35,7 +35,6 @@ url = { version = "2.5.0", features = ["serde"] } utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] } frunk = "0.4.2" frunk_core = "0.4.2" - # First party crates cards = { version = "0.1.0", path = "../cards" } common_enums = { version = "0.1.0", path = "../common_enums" } diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 85a9c3ded09..ca10d7ce599 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -1,6 +1,6 @@ use std::collections::HashSet; -use common_utils::pii::EmailStrategy; +use common_utils::{events::ApiEventMetric, pii::EmailStrategy}; use masking::Secret; use self::{ @@ -8,6 +8,7 @@ use self::{ api_event::{ApiEventDimensions, ApiEventMetrics}, auth_events::AuthEventMetrics, disputes::{DisputeDimensions, DisputeMetrics}, + frm::{FrmDimensions, FrmMetrics}, payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics}, payments::{PaymentDimensions, PaymentDistributions, PaymentMetrics}, refunds::{RefundDimensions, RefundMetrics}, @@ -20,6 +21,7 @@ pub mod api_event; pub mod auth_events; pub mod connector_events; pub mod disputes; +pub mod frm; pub mod outgoing_webhook_event; pub mod payment_intents; pub mod payments; @@ -144,6 +146,22 @@ pub struct GetRefundMetricRequest { pub delta: bool, } +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GetFrmMetricRequest { + pub time_series: Option<TimeSeries>, + pub time_range: TimeRange, + #[serde(default)] + pub group_by_names: Vec<FrmDimensions>, + #[serde(default)] + pub filters: frm::FrmFilters, + pub metrics: HashSet<FrmMetrics>, + #[serde(default)] + pub delta: bool, +} + +impl ApiEventMetric for GetFrmMetricRequest {} + #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetSdkEventMetricRequest { @@ -247,6 +265,33 @@ pub struct RefundFilterValue { pub values: Vec<String>, } +#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GetFrmFilterRequest { + pub time_range: TimeRange, + #[serde(default)] + pub group_by_names: Vec<FrmDimensions>, +} + +impl ApiEventMetric for GetFrmFilterRequest {} + +#[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct FrmFiltersResponse { + pub query_data: Vec<FrmFilterValue>, +} + +impl ApiEventMetric for FrmFiltersResponse {} + +#[derive(Debug, serde::Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct FrmFilterValue { + pub dimension: FrmDimensions, + pub values: Vec<String>, +} + +impl ApiEventMetric for FrmFilterValue {} + #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetSdkEventFiltersRequest { diff --git a/crates/api_models/src/analytics/frm.rs b/crates/api_models/src/analytics/frm.rs new file mode 100644 index 00000000000..3ac45e75894 --- /dev/null +++ b/crates/api_models/src/analytics/frm.rs @@ -0,0 +1,163 @@ +use std::{ + collections::hash_map::DefaultHasher, + hash::{Hash, Hasher}, +}; + +use common_enums::enums::FraudCheckStatus; + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialEq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumString, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum FrmTransactionType { + #[default] + PreFrm, + PostFrm, +} + +use super::{NameDescription, TimeRange}; +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] +pub struct FrmFilters { + #[serde(default)] + pub frm_status: Vec<FraudCheckStatus>, + #[serde(default)] + pub frm_name: Vec<String>, + #[serde(default)] + pub frm_transaction_type: Vec<FrmTransactionType>, +} + +#[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 FrmDimensions { + FrmStatus, + FrmName, + FrmTransactionType, +} + +#[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 FrmMetrics { + FrmTriggeredAttempts, + FrmBlockedRate, +} + +pub mod metric_behaviour { + pub struct FrmTriggeredAttempts; + pub struct FrmBlockRate; +} + +impl From<FrmMetrics> for NameDescription { + fn from(value: FrmMetrics) -> Self { + Self { + name: value.to_string(), + desc: String::new(), + } + } +} + +impl From<FrmDimensions> for NameDescription { + fn from(value: FrmDimensions) -> Self { + Self { + name: value.to_string(), + desc: String::new(), + } + } +} + +#[derive(Debug, serde::Serialize, Eq)] +pub struct FrmMetricsBucketIdentifier { + pub frm_status: Option<String>, + pub frm_name: Option<String>, + pub frm_transaction_type: Option<String>, + #[serde(rename = "time_range")] + pub time_bucket: TimeRange, + #[serde(rename = "time_bucket")] + #[serde(with = "common_utils::custom_serde::iso8601custom")] + pub start_time: time::PrimitiveDateTime, +} + +impl Hash for FrmMetricsBucketIdentifier { + fn hash<H: Hasher>(&self, state: &mut H) { + self.frm_status.hash(state); + self.frm_name.hash(state); + self.frm_transaction_type.hash(state); + self.time_bucket.hash(state); + } +} + +impl PartialEq for FrmMetricsBucketIdentifier { + fn eq(&self, other: &Self) -> bool { + let mut left = DefaultHasher::new(); + self.hash(&mut left); + let mut right = DefaultHasher::new(); + other.hash(&mut right); + left.finish() == right.finish() + } +} + +impl FrmMetricsBucketIdentifier { + pub fn new( + frm_status: Option<String>, + frm_name: Option<String>, + frm_transaction_type: Option<String>, + normalized_time_range: TimeRange, + ) -> Self { + Self { + frm_status, + frm_name, + frm_transaction_type, + time_bucket: normalized_time_range, + start_time: normalized_time_range.start_time, + } + } +} + +#[derive(Debug, serde::Serialize)] +pub struct FrmMetricsBucketValue { + pub frm_triggered_attempts: Option<u64>, + pub frm_blocked_rate: Option<f64>, +} + +#[derive(Debug, serde::Serialize)] +pub struct FrmMetricsBucketResponse { + #[serde(flatten)] + pub values: FrmMetricsBucketValue, + #[serde(flatten)] + pub dimensions: FrmMetricsBucketIdentifier, +} diff --git a/crates/common_enums/Cargo.toml b/crates/common_enums/Cargo.toml index 5c88236b8ae..e364af0407d 100644 --- a/crates/common_enums/Cargo.toml +++ b/crates/common_enums/Cargo.toml @@ -18,6 +18,8 @@ serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" strum = { version = "0.26", features = ["derive"] } utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] } +frunk = "0.4.2" +frunk_core = "0.4.2" # First party crates router_derive = { version = "0.1.0", path = "../router_derive" } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 2ad0ad35cb3..492aed35797 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -10,7 +10,8 @@ pub mod diesel_exports { DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDisputeStage as DisputeStage, - DbDisputeStatus as DisputeStatus, DbEventType as EventType, DbFutureUsage as FutureUsage, + DbDisputeStatus as DisputeStatus, DbEventType as EventType, + DbFraudCheckStatus as FraudCheckStatus, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, DbRefundStatus as RefundStatus, @@ -236,6 +237,30 @@ pub enum AuthenticationType { } /// The status of the capture +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialEq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumString, + frunk::LabelledGeneric, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[strum(serialize_all = "snake_case")] +pub enum FraudCheckStatus { + Fraud, + ManualReview, + #[default] + Pending, + Legit, + TransactionFailure, +} + #[derive( Clone, Copy, @@ -1556,6 +1581,28 @@ pub enum RefundStatus { TransactionFailure, } +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + Hash, + PartialEq, + strum::Display, + strum::EnumString, + strum::EnumIter, + serde::Serialize, + serde::Deserialize, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[strum(serialize_all = "snake_case")] +pub enum FrmTransactionType { + #[default] + PreFrm, + PostFrm, +} + /// The status of the mandate, which indicates whether it can be used to initiate a payment. #[derive( Clone, diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index e95116f99a4..5eeed2990af 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -194,30 +194,6 @@ pub enum FraudCheckType { PostFrm, } -#[derive( - Clone, - Copy, - Debug, - Default, - Eq, - PartialEq, - serde::Serialize, - serde::Deserialize, - strum::Display, - strum::EnumString, - frunk::LabelledGeneric, -)] -#[diesel_enum(storage_type = "db_enum")] -#[strum(serialize_all = "snake_case")] -pub enum FraudCheckStatus { - Fraud, - ManualReview, - #[default] - Pending, - Legit, - TransactionFailure, -} - #[derive( Clone, Copy, diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 64f62f48762..cf98748048d 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -14,9 +14,10 @@ pub mod routes { }, GenerateReportRequest, GetActivePaymentsMetricRequest, GetApiEventFiltersRequest, GetApiEventMetricRequest, GetAuthEventMetricRequest, GetDisputeMetricRequest, - GetPaymentFiltersRequest, GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, - GetPaymentMetricRequest, GetRefundFilterRequest, GetRefundMetricRequest, - GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest, + GetFrmFilterRequest, GetFrmMetricRequest, GetPaymentFiltersRequest, + GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, GetPaymentMetricRequest, + GetRefundFilterRequest, GetRefundMetricRequest, GetSdkEventFiltersRequest, + GetSdkEventMetricRequest, ReportRequest, }; use error_stack::ResultExt; @@ -54,6 +55,9 @@ pub mod routes { web::resource("filters/payments") .route(web::post().to(get_payment_filters)), ) + .service( + web::resource("filters/frm").route(web::post().to(get_frm_filters)), + ) .service( web::resource("filters/refunds") .route(web::post().to(get_refund_filters)), @@ -87,6 +91,9 @@ pub mod routes { web::resource("metrics/auth_events") .route(web::post().to(get_auth_event_metrics)), ) + .service( + web::resource("metrics/frm").route(web::post().to(get_frm_metrics)), + ) .service( web::resource("api_event_logs").route(web::get().to(get_api_events)), ) @@ -270,6 +277,38 @@ pub mod routes { .await } + /// # Panics + /// + /// Panics if `json_payload` array does not contain one `GetFrmMetricRequest` element. + pub async fn get_frm_metrics( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<[GetFrmMetricRequest; 1]>, + ) -> impl Responder { + #[allow(clippy::expect_used)] + // safety: This shouldn't panic owing to the data type + let payload = json_payload + .into_inner() + .to_vec() + .pop() + .expect("Couldn't get GetFrmMetricRequest"); + let flow = AnalyticsFlow::GetFrmMetrics; + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: AuthenticationData, req, _| async move { + analytics::frm::get_metrics(&state.pool, &auth.merchant_account.merchant_id, req) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + /// # Panics /// /// Panics if `json_payload` array does not contain one `GetSdkEventMetricRequest` element. @@ -458,6 +497,28 @@ pub mod routes { .await } + pub async fn get_frm_filters( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<GetFrmFilterRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetFrmFilters; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req: GetFrmFilterRequest, _| async move { + analytics::frm::get_filters(&state.pool, req, &auth.merchant_account.merchant_id) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + pub async fn get_sdk_event_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 2a00e7adbb6..34210cf6de6 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -36,9 +36,8 @@ pub mod user; pub mod user_authentication_method; pub mod user_key_store; pub mod user_role; - use diesel_models::{ - fraud_check::{FraudCheck, FraudCheckNew, FraudCheckUpdate}, + fraud_check::{FraudCheck, FraudCheckUpdate}, organization::{Organization, OrganizationNew, OrganizationUpdate}, }; use error_stack::ResultExt; @@ -53,16 +52,23 @@ use hyperswitch_domain_models::payouts::{ use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; use masking::PeekInterface; use redis_interface::errors::RedisError; +use router_env::logger; use storage_impl::{errors::StorageError, redis::kv_store::RedisConnInterface, MockDb}; pub use self::kafka_store::KafkaStore; use self::{fraud_check::FraudCheckInterface, organization::OrganizationInterface}; pub use crate::{ + core::errors::{self, ProcessTrackerError}, errors::CustomResult, services::{ kafka::{KafkaError, KafkaProducer, MQResult}, Store, }, + types::{ + domain, + storage::{self}, + AccessToken, + }, }; #[derive(PartialEq, Eq)] @@ -259,36 +265,74 @@ impl RequestIdStore for KafkaStore { impl FraudCheckInterface for KafkaStore { async fn insert_fraud_check_response( &self, - new: FraudCheckNew, + new: storage::FraudCheckNew, ) -> CustomResult<FraudCheck, StorageError> { - self.diesel_store.insert_fraud_check_response(new).await + let frm = self.diesel_store.insert_fraud_check_response(new).await?; + if let Err(er) = self + .kafka_producer + .log_fraud_check(&frm, None, self.tenant_id.clone()) + .await + { + logger::error!(message = "Failed to log analytics event for fraud check", error_message = ?er); + } + Ok(frm) } async fn update_fraud_check_response_with_attempt_id( &self, - fraud_check: FraudCheck, - fraud_check_update: FraudCheckUpdate, + this: FraudCheck, + fraud_check: FraudCheckUpdate, ) -> CustomResult<FraudCheck, StorageError> { - self.diesel_store - .update_fraud_check_response_with_attempt_id(fraud_check, fraud_check_update) + let frm = self + .diesel_store + .update_fraud_check_response_with_attempt_id(this, fraud_check) + .await?; + if let Err(er) = self + .kafka_producer + .log_fraud_check(&frm, None, self.tenant_id.clone()) .await + { + logger::error!(message="Failed to log analytics event for fraud check {frm:?}", error_message=?er) + } + Ok(frm) } async fn find_fraud_check_by_payment_id( &self, payment_id: String, merchant_id: String, ) -> CustomResult<FraudCheck, StorageError> { - self.diesel_store + let frm = self + .diesel_store .find_fraud_check_by_payment_id(payment_id, merchant_id) + .await?; + if let Err(er) = self + .kafka_producer + .log_fraud_check(&frm, None, self.tenant_id.clone()) .await + { + logger::error!(message="Failed to log analytics event for fraud check {frm:?}", error_message=?er) + } + Ok(frm) } async fn find_fraud_check_by_payment_id_if_present( &self, payment_id: String, merchant_id: String, ) -> CustomResult<Option<FraudCheck>, StorageError> { - self.diesel_store + let frm = self + .diesel_store .find_fraud_check_by_payment_id_if_present(payment_id, merchant_id) - .await + .await?; + + if let Some(fraud_check) = frm.clone() { + if let Err(er) = self + .kafka_producer + .log_fraud_check(&fraud_check, None, self.tenant_id.clone()) + .await + { + logger::error!(message="Failed to log analytics event for frm {frm:?}", error_message=?er); + } + } + Ok(frm) } } diff --git a/crates/router/src/db/fraud_check.rs b/crates/router/src/db/fraud_check.rs index 34818260364..9e27f451019 100644 --- a/crates/router/src/db/fraud_check.rs +++ b/crates/router/src/db/fraud_check.rs @@ -116,33 +116,3 @@ impl FraudCheckInterface for MockDb { Err(errors::StorageError::MockDbError)? } } - -#[cfg(feature = "kafka_events")] -#[async_trait::async_trait] -impl FraudCheckInterface for super::KafkaStore { - #[instrument(skip_all)] - async fn insert_fraud_check_response( - &self, - _new: storage::FraudCheckNew, - ) -> CustomResult<FraudCheck, errors::StorageError> { - Err(errors::StorageError::MockDbError)? - } - - #[instrument(skip_all)] - async fn update_fraud_check_response_with_attempt_id( - &self, - _this: FraudCheck, - _fraud_check: FraudCheckUpdate, - ) -> CustomResult<FraudCheck, errors::StorageError> { - Err(errors::StorageError::MockDbError)? - } - - #[instrument(skip_all)] - async fn find_fraud_check_by_payment_id( - &self, - _payment_id: String, - _merchant_id: String, - ) -> CustomResult<FraudCheck, errors::StorageError> { - Err(errors::StorageError::MockDbError)? - } -} diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index e5686d616d4..edf8a53346c 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -83,7 +83,7 @@ pub struct TenantID(pub String); #[derive(Clone)] pub struct KafkaStore { - kafka_producer: KafkaProducer, + pub kafka_producer: KafkaProducer, pub diesel_store: Store, pub tenant_id: TenantID, } diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs index 1bdd9016c49..b7ab4ebaa1e 100644 --- a/crates/router/src/events.rs +++ b/crates/router/src/events.rs @@ -23,6 +23,7 @@ pub mod outgoing_webhook_logs; #[serde(rename_all = "snake_case")] pub enum EventType { PaymentIntent, + FraudCheck, PaymentAttempt, Refund, ApiLogs, diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index b245eb3fe74..d1abda2105d 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -11,11 +11,15 @@ use rdkafka::{ }; #[cfg(feature = "payouts")] pub mod payout; -use crate::events::EventType; +use diesel_models::fraud_check::FraudCheck; + +use crate::{events::EventType, services::kafka::fraud_check_event::KafkaFraudCheckEvent}; mod authentication; mod authentication_event; mod dispute; mod dispute_event; +mod fraud_check; +mod fraud_check_event; mod payment_attempt; mod payment_attempt_event; mod payment_intent; @@ -36,7 +40,7 @@ use self::{ payment_intent_event::KafkaPaymentIntentEvent, refund::KafkaRefund, refund_event::KafkaRefundEvent, }; -use crate::types::storage::Dispute; +use crate::{services::kafka::fraud_check::KafkaFraudCheck, types::storage::Dispute}; // Using message queue result here to avoid confusion with Kafka result provided by library pub type MQResult<T> = CustomResult<T, KafkaError>; @@ -139,6 +143,7 @@ impl<'a, T: KafkaMessage> KafkaMessage for KafkaConsolidatedEvent<'a, T> { #[serde(default)] pub struct KafkaSettings { brokers: Vec<String>, + fraud_check_analytics_topic: String, intent_analytics_topic: String, attempt_analytics_topic: String, refund_analytics_topic: String, @@ -246,6 +251,7 @@ impl KafkaSettings { pub struct KafkaProducer { producer: Arc<RdKafkaProducer>, intent_analytics_topic: String, + fraud_check_analytics_topic: String, attempt_analytics_topic: String, refund_analytics_topic: String, api_logs_topic: String, @@ -288,6 +294,7 @@ impl KafkaProducer { .change_context(KafkaError::InitializationError)?, )), + fraud_check_analytics_topic: conf.fraud_check_analytics_topic.clone(), intent_analytics_topic: conf.intent_analytics_topic.clone(), attempt_analytics_topic: conf.attempt_analytics_topic.clone(), refund_analytics_topic: conf.refund_analytics_topic.clone(), @@ -321,6 +328,38 @@ impl KafkaProducer { .map_err(|(error, record)| report!(error).attach_printable(format!("{record:?}"))) .change_context(KafkaError::GenericError) } + pub async fn log_fraud_check( + &self, + attempt: &FraudCheck, + old_attempt: Option<FraudCheck>, + tenant_id: TenantID, + ) -> MQResult<()> { + if let Some(negative_event) = old_attempt { + self.log_event(&KafkaEvent::old( + &KafkaFraudCheck::from_storage(&negative_event), + tenant_id.clone(), + )) + .attach_printable_lazy(|| { + format!("Failed to add negative fraud check event {negative_event:?}") + })?; + }; + + self.log_event(&KafkaEvent::new( + &KafkaFraudCheck::from_storage(attempt), + tenant_id.clone(), + )) + .attach_printable_lazy(|| { + format!("Failed to add positive fraud check event {attempt:?}") + })?; + + self.log_event(&KafkaConsolidatedEvent::new( + &KafkaFraudCheckEvent::from_storage(attempt), + tenant_id.clone(), + )) + .attach_printable_lazy(|| { + format!("Failed to add consolidated fraud check event {attempt:?}") + }) + } pub async fn log_payment_attempt( &self, @@ -544,6 +583,7 @@ impl KafkaProducer { pub fn get_topic(&self, event: EventType) -> &str { match event { + EventType::FraudCheck => &self.fraud_check_analytics_topic, EventType::ApiLogs => &self.api_logs_topic, EventType::PaymentAttempt => &self.attempt_analytics_topic, EventType::PaymentIntent => &self.intent_analytics_topic, diff --git a/crates/router/src/services/kafka/fraud_check.rs b/crates/router/src/services/kafka/fraud_check.rs new file mode 100644 index 00000000000..e52fbbbc9ac --- /dev/null +++ b/crates/router/src/services/kafka/fraud_check.rs @@ -0,0 +1,67 @@ +// use diesel_models::enums as storage_enums; +use diesel_models::{ + enums as storage_enums, + enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType}, + fraud_check::FraudCheck, +}; +use time::OffsetDateTime; + +#[derive(serde::Serialize, Debug)] +pub struct KafkaFraudCheck<'a> { + pub frm_id: &'a String, + pub payment_id: &'a String, + pub merchant_id: &'a String, + pub attempt_id: &'a String, + #[serde(with = "time::serde::timestamp")] + pub created_at: OffsetDateTime, + pub frm_name: &'a String, + pub frm_transaction_id: Option<&'a String>, + pub frm_transaction_type: FraudCheckType, + pub frm_status: FraudCheckStatus, + pub frm_score: Option<i32>, + pub frm_reason: Option<serde_json::Value>, + pub frm_error: Option<&'a String>, + pub payment_details: Option<serde_json::Value>, + pub metadata: Option<serde_json::Value>, + #[serde(with = "time::serde::timestamp")] + pub modified_at: OffsetDateTime, + pub last_step: FraudCheckLastStep, + pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision. +} + +impl<'a> KafkaFraudCheck<'a> { + pub fn from_storage(check: &'a FraudCheck) -> Self { + Self { + frm_id: &check.frm_id, + payment_id: &check.payment_id, + merchant_id: &check.merchant_id, + attempt_id: &check.attempt_id, + created_at: check.created_at.assume_utc(), + frm_name: &check.frm_name, + frm_transaction_id: check.frm_transaction_id.as_ref(), + frm_transaction_type: check.frm_transaction_type, + frm_status: check.frm_status, + frm_score: check.frm_score, + frm_reason: check.frm_reason.clone(), + frm_error: check.frm_error.as_ref(), + payment_details: check.payment_details.clone(), + metadata: check.metadata.clone(), + modified_at: check.modified_at.assume_utc(), + last_step: check.last_step, + payment_capture_method: check.payment_capture_method, + } + } +} + +impl<'a> super::KafkaMessage for KafkaFraudCheck<'a> { + fn key(&self) -> String { + format!( + "{}_{}_{}_{}", + self.merchant_id, self.payment_id, self.attempt_id, self.frm_id + ) + } + + fn event_type(&self) -> crate::events::EventType { + crate::events::EventType::FraudCheck + } +} diff --git a/crates/router/src/services/kafka/fraud_check_event.rs b/crates/router/src/services/kafka/fraud_check_event.rs new file mode 100644 index 00000000000..57dc4d20876 --- /dev/null +++ b/crates/router/src/services/kafka/fraud_check_event.rs @@ -0,0 +1,66 @@ +use diesel_models::{ + enums as storage_enums, + enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType}, + fraud_check::FraudCheck, +}; +use time::OffsetDateTime; + +#[derive(serde::Serialize, Debug)] +pub struct KafkaFraudCheckEvent<'a> { + pub frm_id: &'a String, + pub payment_id: &'a String, + pub merchant_id: &'a String, + pub attempt_id: &'a String, + #[serde(default, with = "time::serde::timestamp::milliseconds")] + pub created_at: OffsetDateTime, + pub frm_name: &'a String, + pub frm_transaction_id: Option<&'a String>, + pub frm_transaction_type: FraudCheckType, + pub frm_status: FraudCheckStatus, + pub frm_score: Option<i32>, + pub frm_reason: Option<serde_json::Value>, + pub frm_error: Option<&'a String>, + pub payment_details: Option<serde_json::Value>, + pub metadata: Option<serde_json::Value>, + #[serde(default, with = "time::serde::timestamp::milliseconds")] + pub modified_at: OffsetDateTime, + pub last_step: FraudCheckLastStep, + pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision. +} + +impl<'a> KafkaFraudCheckEvent<'a> { + pub fn from_storage(check: &'a FraudCheck) -> Self { + Self { + frm_id: &check.frm_id, + payment_id: &check.payment_id, + merchant_id: &check.merchant_id, + attempt_id: &check.attempt_id, + created_at: check.created_at.assume_utc(), + frm_name: &check.frm_name, + frm_transaction_id: check.frm_transaction_id.as_ref(), + frm_transaction_type: check.frm_transaction_type, + frm_status: check.frm_status, + frm_score: check.frm_score, + frm_reason: check.frm_reason.clone(), + frm_error: check.frm_error.as_ref(), + payment_details: check.payment_details.clone(), + metadata: check.metadata.clone(), + modified_at: check.modified_at.assume_utc(), + last_step: check.last_step, + payment_capture_method: check.payment_capture_method, + } + } +} + +impl<'a> super::KafkaMessage for KafkaFraudCheckEvent<'a> { + fn key(&self) -> String { + format!( + "{}_{}_{}_{}", + self.merchant_id, self.payment_id, self.attempt_id, self.frm_id + ) + } + + fn event_type(&self) -> crate::events::EventType { + crate::events::EventType::FraudCheck + } +}
2024-06-05T06:39:40Z
## Description <!-- Describe your changes in detail --> Added frm dashboard metrics and filters. Filters based on: - frm_status - frm_name - frm_transaction_type Metrics calculated: - frm_triggered_attempts - frm_blocked_rate ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Can get analytics insights based on frm ## How did you test it? Below is the collection for testing : [frms.postman_collection.json](https://github.com/user-attachments/files/15897457/frms.postman_collection.json) <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested using local data by sending cURL requests through Postman. <img width="1287" alt="Screenshot 2024-06-05 at 11 57 32 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/3ef62a2a-62f0-4235-8ae9-c7de11b08675"> <img width="1278" alt="Screenshot 2024-06-05 at 11 57 49 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/b1c5131a-0a9d-4999-82f6-09cd70dd25d0"> <img width="1285" alt="Screenshot 2024-06-05 at 11 58 01 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/b4bdb5bf-deb0-4723-8b01-bf236ae5aa0f"> <img width="952" alt="Screenshot 2024-06-05 at 11 58 35 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/b271cd09-eac4-42c5-96b7-05fcab9067aa">
7004a802de2d30b97ecd37f57ba0e9c3aa962993
Below is the collection for testing : [frms.postman_collection.json](https://github.com/user-attachments/files/15897457/frms.postman_collection.json) Tested using local data by sending cURL requests through Postman. <img width="1287" alt="Screenshot 2024-06-05 at 11 57 32 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/3ef62a2a-62f0-4235-8ae9-c7de11b08675"> <img width="1278" alt="Screenshot 2024-06-05 at 11 57 49 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/b1c5131a-0a9d-4999-82f6-09cd70dd25d0"> <img width="1285" alt="Screenshot 2024-06-05 at 11 58 01 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/b4bdb5bf-deb0-4723-8b01-bf236ae5aa0f"> <img width="952" alt="Screenshot 2024-06-05 at 11 58 35 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/b271cd09-eac4-42c5-96b7-05fcab9067aa">
[ "Cargo.lock", "config/config.example.toml", "config/development.toml", "config/docker_compose.toml", "crates/analytics/Cargo.toml", "crates/analytics/docs/clickhouse/scripts/fraud_check.sql", "crates/analytics/src/clickhouse.rs", "crates/analytics/src/core.rs", "crates/analytics/src/frm.rs", "crat...
juspay/hyperswitch
juspay__hyperswitch-4589
Bug: [Feature] Add a cargo binary for running diesel migrations locally ### Objective Add a new binary in the `router` crate that would run migrations locally via cli i.e `cargo run migrations`. ### Context Currently migrations are managed via the diesel_cli which rely on explicitly providing the database username/password & host, This is a bit cumbersome when you have to provide the variables over & over again. ```bash diesel migration --database-url postgres://$DB_USER:$DB_PASS@localhost:5432/$DB_NAME run ``` It would be somewhat easier if we could leverage [`diesel_migrations`](https://docs.rs/diesel_migrations/latest/diesel_migrations/) to read the credentials from config file / env & apply migrations. (Open to alternative approaches as well for this) ### Outcomes - A new rust binary that can be used for running local db migrations from file - Updates to the local setup documentation outlining the usage of this cli tool
diff --git a/Cargo.lock b/Cargo.lock index 1d6d0fc7511..8249ae4f70b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -384,12 +384,55 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" +[[package]] +name = "anstream" +version = "0.6.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + [[package]] name = "anstyle" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8901269c6307e8d93993578286ac0edf7f195079ffff5ebdeea6a59ffb7e36bc" +[[package]] +name = "anstyle-parse" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad186efb764318d35165f1758e7dcef3b10628e26d41a44bc5550652e6804391" +dependencies = [ + "windows-sys 0.52.0", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19" +dependencies = [ + "anstyle", + "windows-sys 0.52.0", +] + [[package]] name = "anyhow" version = "1.0.81" @@ -1909,8 +1952,10 @@ version = "4.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4df4df40ec50c46000231c914968278b1eb05098cf8f1b3a518a95030e71d1c7" dependencies = [ + "anstream", "anstyle", "clap_lex", + "strsim", ] [[package]] @@ -1940,6 +1985,12 @@ dependencies = [ "bitflags 1.3.2", ] +[[package]] +name = "colorchoice" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422" + [[package]] name = "common_enums" version = "0.1.0" @@ -2016,7 +2067,7 @@ dependencies = [ "rust-ini", "serde", "serde_json", - "toml", + "toml 0.8.12", "yaml-rust", ] @@ -2029,7 +2080,7 @@ dependencies = [ "indexmap 2.2.6", "serde", "serde_json", - "toml", + "toml 0.8.12", ] [[package]] @@ -2039,7 +2090,7 @@ dependencies = [ "api_models", "serde", "serde_with", - "toml", + "toml 0.8.12", "utoipa", ] @@ -2588,9 +2639,9 @@ checksum = "b6e854126756c496b8c81dec88f9a706b15b875c5849d4097a3854476b9fdf94" [[package]] name = "diesel" -version = "2.1.5" +version = "2.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03fc05c17098f21b89bc7d98fe1dd3cce2c11c2ad8e145f2a44fe08ed28eb559" +checksum = "ff236accb9a5069572099f0b350a92e9560e8e63a9b8d546162f4a5e03026bb2" dependencies = [ "bitflags 2.5.0", "byteorder", @@ -2604,9 +2655,9 @@ dependencies = [ [[package]] name = "diesel_derives" -version = "2.1.3" +version = "2.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d02eecb814ae714ffe61ddc2db2dd03e6c49a42e269b5001355500d431cce0c" +checksum = "14701062d6bed917b5c7103bdffaee1e4609279e240488ad24e7bd979ca6866c" dependencies = [ "diesel_table_macro_syntax", "proc-macro2", @@ -2614,6 +2665,17 @@ dependencies = [ "syn 2.0.57", ] +[[package]] +name = "diesel_migrations" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6036b3f0120c5961381b570ee20a02432d7e2d27ea60de9578799cf9156914ac" +dependencies = [ + "diesel", + "migrations_internals", + "migrations_macros", +] + [[package]] name = "diesel_models" version = "0.1.0" @@ -3584,6 +3646,17 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "hsdev" +version = "0.1.0" +dependencies = [ + "clap", + "diesel", + "diesel_migrations", + "serde", + "toml 0.5.11", +] + [[package]] name = "http" version = "0.2.12" @@ -4020,6 +4093,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800" + [[package]] name = "iso_country" version = "0.1.4" @@ -4396,6 +4475,27 @@ dependencies = [ "autocfg", ] +[[package]] +name = "migrations_internals" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f23f71580015254b020e856feac3df5878c2c7a8812297edd6c0a485ac9dada" +dependencies = [ + "serde", + "toml 0.7.8", +] + +[[package]] +name = "migrations_macros" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cce3325ac70e67bbab5bd837a31cae01f1a6db64e0e744a33cb03a543469ef08" +dependencies = [ + "migrations_internals", + "proc-macro2", + "quote", +] + [[package]] name = "mimalloc" version = "0.1.39" @@ -7370,7 +7470,7 @@ dependencies = [ "thirtyfour", "time", "tokio 1.37.0", - "toml", + "toml 0.8.12", ] [[package]] @@ -7798,6 +7898,27 @@ dependencies = [ "tracing", ] +[[package]] +name = "toml" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" +dependencies = [ + "serde", +] + +[[package]] +name = "toml" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd79e69d3b627db300ff956027cc6c3798cef26d22526befdfcd12feeb6d2257" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit 0.19.15", +] + [[package]] name = "toml" version = "0.8.12" @@ -7827,6 +7948,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ "indexmap 2.2.6", + "serde", + "serde_spanned", "toml_datetime", "winnow 0.5.40", ] @@ -8243,6 +8366,12 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "110352d4e9076c67839003c7788d8604e24dcded13e0b375af3efaa8cf468517" +[[package]] +name = "utf8parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" + [[package]] name = "utoipa" version = "4.2.0" diff --git a/crates/hsdev/Cargo.toml b/crates/hsdev/Cargo.toml new file mode 100644 index 00000000000..6600d41d9fc --- /dev/null +++ b/crates/hsdev/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "hsdev" +version = "0.1.0" +license.workspace = true +edition.workspace = true +rust-version.workspace = true +description = "A simple diesel postgres migrator that uses TOML files" +repository = "https://github.com/juspay/hyperswitch.git" +readme = "README.md" + +[dependencies] +diesel = { version = "2.1.6", features = ["postgres"] } +diesel_migrations = "2.1.0" +toml = "0.5" +clap = { version = "4.1.8", features = ["derive"] } +serde = { version = "1.0", features = ["derive"] } diff --git a/crates/hsdev/README.md b/crates/hsdev/README.md new file mode 100644 index 00000000000..926d9b9056f --- /dev/null +++ b/crates/hsdev/README.md @@ -0,0 +1,24 @@ +# HSDEV + +`hsdev` is a simple diesel Postgres migration tool. It is designed to simply running a Postgres database migration with diesel. + +## Installing hsdev +`hsdev` can be installed using `cargo` +```shell +cargo install --force --path crates/hsdev +``` + +## Using hsdev +Using `hsdev` is simple. All you need to do is run the following command. +```shell +hsdev --toml-file [path/to/TOML/file] +``` + +provide `hsdev` with a TOML file containing the following keys: +```toml +username = "your_username" +password = "your_password" +dbname = "your_db_name" +``` + +Simply run the command and let `hsdev` handle the rest. diff --git a/crates/hsdev/src/input_file.rs b/crates/hsdev/src/input_file.rs new file mode 100644 index 00000000000..0d5d0a2eb0c --- /dev/null +++ b/crates/hsdev/src/input_file.rs @@ -0,0 +1,26 @@ +use std::string::String; + +use serde::Deserialize; +use toml::Value; + +#[derive(Deserialize)] +pub struct InputData { + username: String, + password: String, + dbname: String, + host: String, + port: u16, +} + +impl InputData { + pub fn read(db_table: &Value) -> Result<Self, toml::de::Error> { + db_table.clone().try_into() + } + + pub fn postgres_url(&self) -> String { + format!( + "postgres://{}:{}@{}:{}/{}", + self.username, self.password, self.host, self.port, self.dbname + ) + } +} diff --git a/crates/hsdev/src/main.rs b/crates/hsdev/src/main.rs new file mode 100644 index 00000000000..e6ee9e17d44 --- /dev/null +++ b/crates/hsdev/src/main.rs @@ -0,0 +1,139 @@ +use clap::{Parser, ValueHint}; +use diesel::{pg::PgConnection, Connection}; +use diesel_migrations::{FileBasedMigrations, HarnessWithOutput, MigrationHarness}; +use toml::Value; + +mod input_file; + +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +struct Args { + #[arg(short, long, value_hint = ValueHint::FilePath)] + toml_file: std::path::PathBuf, + + #[arg(long, default_value_t = String::from(""))] + toml_table: String, +} + +fn main() { + let args = Args::parse(); + + let toml_file = &args.toml_file; + let table_name = &args.toml_table; + let toml_contents = match std::fs::read_to_string(toml_file) { + Ok(contents) => contents, + Err(e) => { + eprintln!("Error reading TOML file: {}", e); + return; + } + }; + let toml_data: Value = match toml_contents.parse() { + Ok(data) => data, + Err(e) => { + eprintln!("Error parsing TOML file: {}", e); + return; + } + }; + + let table = get_toml_table(table_name, &toml_data); + + let input = match input_file::InputData::read(table) { + Ok(data) => data, + Err(e) => { + eprintln!("Error loading TOML file: {}", e); + return; + } + }; + + let db_url = input.postgres_url(); + + println!("Attempting to connect to {}", db_url); + + let mut conn = match PgConnection::establish(&db_url) { + Ok(value) => value, + Err(_) => { + eprintln!("Unable to establish database connection"); + return; + } + }; + + let migrations = match FileBasedMigrations::find_migrations_directory() { + Ok(value) => value, + Err(_) => { + eprintln!("Could not find migrations directory"); + return; + } + }; + + let mut harness = HarnessWithOutput::write_to_stdout(&mut conn); + + match harness.run_pending_migrations(migrations) { + Ok(_) => println!("Successfully ran migrations"), + Err(_) => eprintln!("Couldn't run migrations"), + }; +} + +pub fn get_toml_table<'a>(table_name: &'a str, toml_data: &'a Value) -> &'a Value { + if !table_name.is_empty() { + match toml_data.get(table_name) { + Some(value) => value, + None => { + eprintln!("Unable to find toml table: \"{}\"", &table_name); + std::process::abort() + } + } + } else { + toml_data + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use std::str::FromStr; + + use toml::Value; + + use crate::{get_toml_table, input_file::InputData}; + + #[test] + fn test_input_file() { + let toml_str = r#"username = "db_user" + password = "db_pass" + dbname = "db_name" + host = "localhost" + port = 5432"#; + + let toml_value = Value::from_str(toml_str); + assert!(toml_value.is_ok()); + let toml_value = toml_value.unwrap(); + + let toml_table = InputData::read(&toml_value); + assert!(toml_table.is_ok()); + let toml_table = toml_table.unwrap(); + + let db_url = toml_table.postgres_url(); + assert_eq!("postgres://db_user:db_pass@localhost:5432/db_name", db_url); + } + + #[test] + fn test_given_toml() { + let toml_str_table = r#"[database] + username = "db_user" + password = "db_pass" + dbname = "db_name" + host = "localhost" + port = 5432"#; + + let table_name = "database"; + let toml_value = Value::from_str(toml_str_table).unwrap(); + let table = get_toml_table(table_name, &toml_value); + + assert!(table.is_table()); + + let table_name = ""; + let table = get_toml_table(table_name, &toml_value); + assert!(table.is_table()); + } +}
2024-06-04T20:18:52Z
## Description This PR closes #4589 Created a new Rust binary in the `crates` directory which automates the Diesel migrations with Postgres. The new tool is a CLI tool that takes a path to a TOML file as an argument along with the name of a TOML table to extract Postgres database credentials from. The tool then automatically performs the migrations by utilizing `diesel_migrations` library. From our testing, we were able to set up Hyperswitch locally without using `diesel_cli` and Bash variables on WSL2 Ubuntu. I worked on this Issue with @JamesM25 @ind1goDusk The example below shows the application running using `cargo run` in the `hsdev` crate. ```sh cargo run -- --toml-file ~/hyperswitch/config/development.toml --toml-table master_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 Before our tool, Hyperswitch needed to be set up on local machines using a long `diesel_cli` command with Bash variables for the Postgres migration. Now we have provided a simpler and easily repeatable solution to Postgres and Diesel migrations that allows for greater modularity as you can select specific TOML files and tables to select database credentials from. ## How did you test it? We wrote two units test on the core functionality. We tested it both on a dummy TOML file as well as in Hyperswitch repository. We were able to set up Hyperswitch locally using `hsdev` instead of `diesel_cli`.
2d31d38c1e35be99e9b0297b197bab81fa5f5030
We wrote two units test on the core functionality. We tested it both on a dummy TOML file as well as in Hyperswitch repository. We were able to set up Hyperswitch locally using `hsdev` instead of `diesel_cli`.
[ "Cargo.lock", "crates/hsdev/Cargo.toml", "crates/hsdev/README.md", "crates/hsdev/src/input_file.rs", "crates/hsdev/src/main.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4472
Bug: [FEATURE] Add support for sending additional metadata in the `MessagingInterface` ### Feature Description In the current implementation of message interface I can only send a Message & a timestamp associated with the message, There is no accomodation to send additional metadata about the message which isn't part of the data but could be propogated to the downstream implementations, These could be used downstream as kafka headers or redis hashes or partition keys. ### Possible Implementation metadata can be a simplistic `HashMap<String, String>` and can be either accomodated as a new param in the [`MessagingInterface`](https://github.com/juspay/hyperswitch/blob/cc1051da99c1b4e007d7f730e2fe3cb08b078d80/crates/events/src/lib.rs#L239) or a new method on the [`Message`](https://github.com/juspay/hyperswitch/blob/cc1051da99c1b4e007d7f730e2fe3cb08b078d80/crates/events/src/lib.rs#L239) Interface. The implementers of MessageInterface can handle it as follows 1. Kafka Send the metadata as headers 2. EventLogger Log the metadata as a separate key along with the raw data ### 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/events/src/lib.rs b/crates/events/src/lib.rs index 0136b64a0f6..cef0c8894de 100644 --- a/crates/events/src/lib.rs +++ b/crates/events/src/lib.rs @@ -49,6 +49,11 @@ pub trait Event: EventInfo { /// The class/type of the event. This is used to group/categorize events together. fn class(&self) -> Self::EventType; + + /// Metadata associated with the event + fn metadata(&self) -> HashMap<String, String> { + HashMap::new() + } } /// Hold the context information for any events @@ -73,7 +78,8 @@ where event: E, } -struct RawEvent<T, A: Event<EventType = T>>(HashMap<String, Value>, A); +/// A flattened event that flattens the context provided to it along with the actual event. +struct FlatMapEvent<T, A: Event<EventType = T>>(HashMap<String, Value>, A); impl<T, A, E, D> EventBuilder<T, A, E, D> where @@ -109,12 +115,13 @@ where /// Emit the event. pub fn try_emit(self) -> Result<(), EventsError> { let ts = self.event.timestamp(); + let metadata = self.event.metadata(); self.message_sink - .send_message(RawEvent(self.metadata, self.event), ts) + .send_message(FlatMapEvent(self.metadata, self.event), metadata, ts) } } -impl<T, A> Serialize for RawEvent<T, A> +impl<T, A> Serialize for FlatMapEvent<T, A> where A: Event<EventType = T>, { @@ -236,7 +243,12 @@ pub trait MessagingInterface { /// The type of the event used for categorization by the event publisher. type MessageClass; /// Send a message that follows the defined message class. - fn send_message<T>(&self, data: T, timestamp: PrimitiveDateTime) -> Result<(), EventsError> + fn send_message<T>( + &self, + data: T, + metadata: HashMap<String, String>, + timestamp: PrimitiveDateTime, + ) -> Result<(), EventsError> where T: Message<Class = Self::MessageClass> + ErasedMaskSerialize; } @@ -252,7 +264,7 @@ pub trait Message { fn identifier(&self) -> String; } -impl<T, A> Message for RawEvent<T, A> +impl<T, A> Message for FlatMapEvent<T, A> where A: Event<EventType = T>, { diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs index e1ecd09804c..1af515b8c22 100644 --- a/crates/router/src/events.rs +++ b/crates/router/src/events.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use error_stack::ResultExt; use events::{EventsError, Message, MessagingInterface}; use hyperswitch_domain_models::errors::{StorageError, StorageResult}; @@ -94,14 +96,15 @@ impl MessagingInterface for EventsHandler { fn send_message<T>( &self, data: T, + metadata: HashMap<String, String>, timestamp: PrimitiveDateTime, ) -> error_stack::Result<(), EventsError> where T: Message<Class = Self::MessageClass> + ErasedMaskSerialize, { match self { - Self::Kafka(a) => a.send_message(data, timestamp), - Self::Logs(a) => a.send_message(data, timestamp), + Self::Kafka(a) => a.send_message(data, metadata, timestamp), + Self::Logs(a) => a.send_message(data, metadata, timestamp), } } } diff --git a/crates/router/src/events/event_logger.rs b/crates/router/src/events/event_logger.rs index 235ee4a3e3c..004f94942d2 100644 --- a/crates/router/src/events/event_logger.rs +++ b/crates/router/src/events/event_logger.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use events::{EventsError, Message, MessagingInterface}; use masking::ErasedMaskSerialize; use time::PrimitiveDateTime; @@ -21,12 +23,13 @@ impl MessagingInterface for EventLogger { fn send_message<T>( &self, data: T, + metadata: HashMap<String, String>, _timestamp: PrimitiveDateTime, ) -> error_stack::Result<(), EventsError> where T: Message<Class = Self::MessageClass> + ErasedMaskSerialize, { - logger::info!(event =? data.masked_serialize().unwrap_or_else(|e| serde_json::json!({"error": e.to_string()})), event_type =? data.get_message_class(), event_id =? data.identifier(), log_type =? "event"); + logger::info!(event =? data.masked_serialize().unwrap_or_else(|e| serde_json::json!({"error": e.to_string()})), event_type =? data.get_message_class(), event_id =? data.identifier(), log_type =? "event", metadata = ?metadata); Ok(()) } } diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs index e0a4f80908d..e1601f8bbbe 100644 --- a/crates/router/src/middleware.rs +++ b/crates/router/src/middleware.rs @@ -157,7 +157,8 @@ where payment_method = Empty, status_code = Empty, flow = "UNKNOWN", - golden_log_line = Empty + golden_log_line = Empty, + tenant_id = "ta" ) .or_current(), ), diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index 3523ab9261f..9c38917424e 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -1,4 +1,4 @@ -use std::sync::Arc; +use std::{collections::HashMap, sync::Arc}; use bigdecimal::ToPrimitive; use common_utils::errors::CustomResult; @@ -6,6 +6,7 @@ use error_stack::{report, ResultExt}; use events::{EventsError, Message, MessagingInterface}; use rdkafka::{ config::FromClientConfig, + message::{Header, OwnedHeaders}, producer::{BaseRecord, DefaultProducerContext, Producer, ThreadedProducer}, }; #[cfg(feature = "payouts")] @@ -528,6 +529,7 @@ impl MessagingInterface for KafkaProducer { fn send_message<T>( &self, data: T, + metadata: HashMap<String, String>, timestamp: PrimitiveDateTime, ) -> error_stack::Result<(), EventsError> where @@ -538,12 +540,20 @@ impl MessagingInterface for KafkaProducer { .masked_serialize() .and_then(|i| serde_json::to_vec(&i)) .change_context(EventsError::SerializationError)?; + let mut headers = OwnedHeaders::new(); + for (k, v) in metadata.iter() { + headers = headers.insert(Header { + key: k.as_str(), + value: Some(v), + }); + } self.producer .0 .send( BaseRecord::to(topic) .key(&data.identifier()) .payload(&json_data) + .headers(headers) .timestamp( (timestamp.assume_utc().unix_timestamp_nanos() / 1_000_000) .to_i64()
2024-06-04T14:21:27Z
## Description <!-- Describe your changes in detail --> - Allow setting kafka headers in message ### 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)? --> <img width="1597" alt="image" src="https://github.com/juspay/hyperswitch/assets/21202349/67529c15-c762-465d-a02a-fab090676c3a">
a2ea0ed19c075fb0e23b16ddc24b5230dc70369b
<img width="1597" alt="image" src="https://github.com/juspay/hyperswitch/assets/21202349/67529c15-c762-465d-a02a-fab090676c3a">
[ "crates/events/src/lib.rs", "crates/router/src/events.rs", "crates/router/src/events/event_logger.rs", "crates/router/src/middleware.rs", "crates/router/src/services/kafka.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4869
Bug: [BUG] Paypal payment experience ### Bug Description Paypal payment experience is getting duplicated <img width="1721" alt="image" src="https://github.com/juspay/hyperswitch/assets/120017870/ec53d1fd-596c-4be3-90c3-3c0f0c06dc50"> ### Expected Behavior Paypal payment experience shouldn't get duplicated ### Actual Behavior Paypal payment experience shouldn't get duplicated ### 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? None
diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs index 87d1e3e810b..976068c98b6 100644 --- a/crates/connector_configs/src/transformer.rs +++ b/crates/connector_configs/src/transformer.rs @@ -71,24 +71,27 @@ impl DashboardRequestPayload { api_models::enums::PaymentExperience::RedirectToUrl, api_models::enums::PaymentExperience::InvokeSdkClient, ]; - + let default_provider = Provider { + payment_method_type: Paypal, + accepted_currencies: None, + accepted_countries: None, + }; + let provider = providers.first().unwrap_or(&default_provider); let mut payment_method_types = Vec::new(); for experience in payment_experiences { - for provider in &providers { - let data = payment_methods::RequestPaymentMethodTypes { - payment_method_type: provider.payment_method_type, - card_networks: None, - minimum_amount: Some(0), - maximum_amount: Some(68607706), - recurring_enabled: true, - installment_payment_enabled: false, - accepted_currencies: provider.accepted_currencies.clone(), - accepted_countries: provider.accepted_countries.clone(), - payment_experience: Some(experience), - }; - payment_method_types.push(data); - } + let data = payment_methods::RequestPaymentMethodTypes { + payment_method_type: provider.payment_method_type, + card_networks: None, + minimum_amount: Some(0), + maximum_amount: Some(68607706), + recurring_enabled: true, + installment_payment_enabled: false, + accepted_currencies: provider.accepted_currencies.clone(), + accepted_countries: provider.accepted_countries.clone(), + payment_experience: Some(experience), + }; + payment_method_types.push(data); } payment_method_types
2024-06-04T12:22:52Z
## Description <!-- Describe your changes in detail --> <img width="1382" alt="image" src="https://github.com/juspay/hyperswitch/assets/120017870/28dcf3da-317f-4e40-b91f-0197d0db3410"> ### 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)? -->
1d36798399c118f7cb7af93935123634e1afd6a0
[ "crates/connector_configs/src/transformer.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4521
Bug: [REFACTOR] Update AnalyticsPool to hold variables for tenant ID Update the [AnalyticsProvider](https://github.com/juspay/hyperswitch/blob/be44447c09ea8814dc8b88aa971e08cc749db5f3/crates/analytics/src/lib.rs#L67-L72) (or [`AnalyticsConfig`](https://github.com/juspay/hyperswitch/blob/be44447c09ea8814dc8b88aa971e08cc749db5f3/crates/analytics/src/lib.rs#L593-L608)) to hold a variable for tenant-ID. This can be achieved by simply adding a new field in the underlying structs for SqlxClient & ClickhouseClient. Update the AnalyticsPool constructor method to accept a Tenant-ID. Tenant-ID can be a new type field backed by a string; pub struct TenantID(String); For now the AnalyticsPool can be initialized with a fixed tenantID "default"
diff --git a/config/config.example.toml b/config/config.example.toml index 81516ee8b6b..30f33430378 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -639,6 +639,7 @@ sdk_eligible_payment_methods = "card" [multitenancy] enabled = false +global_tenant = { schema = "public", redis_key_prefix = "" } [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = ""} # schema -> Postgres db schema, redis_key_prefix -> redis key distinguisher, base_url -> url of the tenant \ No newline at end of file +public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} # schema -> Postgres db schema, redis_key_prefix -> redis key distinguisher, base_url -> url of the tenant \ No newline at end of file diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 9ab790b8ee8..162444c9098 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -256,6 +256,7 @@ region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. [multitenancy] enabled = false +global_tenant = { schema = "public", redis_key_prefix = "" } [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = ""} \ No newline at end of file +public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} \ No newline at end of file diff --git a/config/development.toml b/config/development.toml index 9a40a99cfce..b986a66d845 100644 --- a/config/development.toml +++ b/config/development.toml @@ -648,6 +648,7 @@ sdk_eligible_payment_methods = "card" [multitenancy] enabled = false +global_tenant = { schema = "public", redis_key_prefix = "" } [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = ""} +public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 2cd93eade01..a9d37995728 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -502,6 +502,7 @@ sdk_eligible_payment_methods = "card" [multitenancy] enabled = false +global_tenant = { schema = "public", redis_key_prefix = "" } [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = ""} \ No newline at end of file +public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} \ No newline at end of file diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index 64064c09c88..fd1746c4b9e 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -35,6 +35,7 @@ pub type ClickhouseResult<T> = error_stack::Result<T, ClickhouseError>; #[derive(Clone, Debug)] pub struct ClickhouseClient { pub config: Arc<ClickhouseConfig>, + pub database: String, } #[derive(Clone, Debug, serde::Deserialize)] @@ -42,7 +43,6 @@ pub struct ClickhouseConfig { username: String, password: Option<String>, host: String, - database_name: String, } impl Default for ClickhouseConfig { @@ -51,7 +51,6 @@ impl Default for ClickhouseConfig { username: "default".to_string(), password: None, host: "http://localhost:8123".to_string(), - database_name: "default".to_string(), } } } @@ -63,7 +62,7 @@ impl ClickhouseClient { let params = CkhQuery { date_time_output_format: String::from("iso"), output_format_json_quote_64bit_integers: 0, - database: self.config.database_name.clone(), + database: self.database.clone(), }; let response = client .post(&self.config.host) diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index f658f679097..5c269a4bb18 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -601,22 +601,30 @@ impl AnalyticsProvider { } } - pub async fn from_conf(config: &AnalyticsConfig, tenant: &str) -> Self { + pub async fn from_conf( + config: &AnalyticsConfig, + tenant: &dyn storage_impl::config::ClickHouseConfig, + ) -> Self { match config { - AnalyticsConfig::Sqlx { sqlx } => Self::Sqlx(SqlxClient::from_conf(sqlx, tenant).await), + AnalyticsConfig::Sqlx { sqlx } => { + Self::Sqlx(SqlxClient::from_conf(sqlx, tenant.get_schema()).await) + } AnalyticsConfig::Clickhouse { clickhouse } => Self::Clickhouse(ClickhouseClient { config: Arc::new(clickhouse.clone()), + database: tenant.get_clickhouse_database().to_string(), }), AnalyticsConfig::CombinedCkh { sqlx, clickhouse } => Self::CombinedCkh( - SqlxClient::from_conf(sqlx, tenant).await, + SqlxClient::from_conf(sqlx, tenant.get_schema()).await, ClickhouseClient { config: Arc::new(clickhouse.clone()), + database: tenant.get_clickhouse_database().to_string(), }, ), AnalyticsConfig::CombinedSqlx { sqlx, clickhouse } => Self::CombinedSqlx( - SqlxClient::from_conf(sqlx, tenant).await, + SqlxClient::from_conf(sqlx, tenant.get_schema()).await, ClickhouseClient { config: Arc::new(clickhouse.clone()), + database: tenant.get_clickhouse_database().to_string(), }, ), } diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index 968ef22bf97..38c8997358d 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -87,8 +87,8 @@ pub const MAX_TTL_FOR_EXTENDED_CARD_INFO: u16 = 60 * 60 * 2; /// Default tenant to be used when multitenancy is disabled pub const DEFAULT_TENANT: &str = "public"; -/// Global tenant to be used when multitenancy is enabled -pub const GLOBAL_TENANT: &str = "global"; +/// Default tenant to be used when multitenancy is disabled +pub const TENANT_HEADER: &str = "x-tenant-id"; /// Max Length for MerchantReferenceId pub const MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 64; diff --git a/crates/diesel_models/src/query/user.rs b/crates/diesel_models/src/query/user.rs index dac515cb279..2bd403a847b 100644 --- a/crates/diesel_models/src/query/user.rs +++ b/crates/diesel_models/src/query/user.rs @@ -1,23 +1,9 @@ -use async_bb8_diesel::AsyncRunQueryDsl; use common_utils::pii; -use diesel::{ - associations::HasTable, debug_query, result::Error as DieselError, ExpressionMethods, - JoinOnDsl, QueryDsl, -}; -use error_stack::report; -use router_env::logger; +use diesel::{associations::HasTable, ExpressionMethods}; pub mod sample_data; use crate::{ - errors::{self}, - query::generics, - schema::{ - user_roles::{self, dsl as user_roles_dsl}, - users::dsl as users_dsl, - }, - user::*, - user_role::UserRole, - PgPooledConn, StorageResult, + query::generics, schema::users::dsl as users_dsl, user::*, PgPooledConn, StorageResult, }; impl UserNew { @@ -90,27 +76,6 @@ impl User { .await } - pub async fn find_joined_users_and_roles_by_merchant_id( - conn: &PgPooledConn, - mid: &str, - ) -> StorageResult<Vec<(Self, UserRole)>> { - let query = Self::table() - .inner_join(user_roles::table.on(user_roles_dsl::user_id.eq(users_dsl::user_id))) - .filter(user_roles_dsl::merchant_id.eq(mid.to_owned())); - - logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); - - query - .get_results_async::<(Self, UserRole)>(conn) - .await - .map_err(|err| match err { - DieselError::NotFound => { - report!(err).change_context(errors::DatabaseError::NotFound) - } - _ => report!(err).change_context(errors::DatabaseError::Others), - }) - } - pub async fn find_users_by_user_ids( conn: &PgPooledConn, user_ids: Vec<String>, diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs index e64b5dbd4ad..57c17f577b1 100644 --- a/crates/drainer/src/settings.rs +++ b/crates/drainer/src/settings.rs @@ -143,6 +143,7 @@ pub struct Tenant { pub base_url: String, pub schema: String, pub redis_key_prefix: String, + pub clickhouse_database: String, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index e99e216463a..f3f70cf42bd 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 struct Multitenancy { pub tenants: TenantConfig, pub enabled: bool, + pub global_tenant: GlobalTenant, } impl Multitenancy { @@ -152,6 +153,7 @@ pub struct Tenant { pub base_url: String, pub schema: String, pub redis_key_prefix: String, + pub clickhouse_database: String, } impl storage_impl::config::TenantConfig for Tenant { @@ -163,6 +165,12 @@ impl storage_impl::config::TenantConfig for Tenant { } } +impl storage_impl::config::ClickHouseConfig for Tenant { + fn get_clickhouse_database(&self) -> &str { + self.clickhouse_database.as_str() + } +} + #[derive(Debug, Deserialize, Clone, Default)] pub struct GlobalTenant { pub schema: String, diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs index e1601f8bbbe..7b9919d3afa 100644 --- a/crates/router/src/middleware.rs +++ b/crates/router/src/middleware.rs @@ -1,3 +1,4 @@ +use common_utils::consts::TENANT_HEADER; use futures::StreamExt; use router_env::{ logger, @@ -140,10 +141,17 @@ where // TODO: have a common source of truth for the list of top level fields // /crates/router_env/src/logger/storage.rs also has a list of fields called PERSISTENT_KEYS fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future { + let tenant_id = req + .headers() + .get(TENANT_HEADER) + .and_then(|i| i.to_str().ok()) + .map(|s| s.to_owned()); let response_fut = self.service.call(req); - Box::pin( async move { + if let Some(tenant_id) = tenant_id { + router_env::tracing::Span::current().record("tenant_id", &tenant_id); + } let response = response_fut.await; router_env::tracing::Span::current().record("golden_log_line", true); response diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 92ca3c264fe..2e7a6c4f61e 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -5,7 +5,6 @@ use actix_web::{web, Scope}; use api_models::routing::RoutingRetrieveQuery; #[cfg(feature = "olap")] use common_enums::TransactionType; -use common_utils::consts::{DEFAULT_TENANT, GLOBAL_TENANT}; #[cfg(feature = "email")] use external_services::email::{ses::AwsSes, EmailService}; use external_services::file_storage::FileStorageInterface; @@ -257,19 +256,11 @@ impl AppState { let cache_store = get_cache_store(&conf.clone(), shut_down_signal, testable) .await .expect("Failed to create store"); - let global_tenant = if conf.multitenancy.enabled { - GLOBAL_TENANT - } else { - DEFAULT_TENANT - }; let global_store: Box<dyn GlobalStorageInterface> = Self::get_store_interface( &storage_impl, &event_handler, &conf, - &settings::GlobalTenant { - schema: global_tenant.to_string(), - redis_key_prefix: String::default(), - }, + &conf.multitenancy.global_tenant, Arc::clone(&cache_store), testable, ) @@ -288,9 +279,7 @@ impl AppState { .get_storage_interface(); stores.insert(tenant_name.clone(), store); #[cfg(feature = "olap")] - let pool = - AnalyticsProvider::from_conf(conf.analytics.get_inner(), tenant_name.as_str()) - .await; + let pool = AnalyticsProvider::from_conf(conf.analytics.get_inner(), tenant).await; #[cfg(feature = "olap")] pools.insert(tenant_name.clone(), pool); } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index baa824ced3f..7408f379489 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -19,7 +19,7 @@ use api_models::enums::{CaptureMethod, PaymentMethodType}; pub use client::{proxy_bypass_urls, ApiClient, MockApiClient, ProxyClient}; pub use common_utils::request::{ContentType, Method, Request, RequestBuilder}; use common_utils::{ - consts::X_HS_LATENCY, + consts::{DEFAULT_TENANT, TENANT_HEADER, X_HS_LATENCY}, errors::{ErrorSwitch, ReportSwitchExt}, request::RequestContent, }; @@ -941,10 +941,10 @@ where .into_iter() .collect(); let tenant_id = if !state.conf.multitenancy.enabled { - common_utils::consts::DEFAULT_TENANT.to_string() + DEFAULT_TENANT.to_string() } else { incoming_request_header - .get("x-tenant-id") + .get(TENANT_HEADER) .and_then(|value| value.to_str().ok()) .ok_or_else(|| errors::ApiErrorResponse::MissingTenantId.switch()) .map(|req_tenant_id| { diff --git a/crates/storage_impl/src/config.rs b/crates/storage_impl/src/config.rs index e371936a04d..bb006b6a9e5 100644 --- a/crates/storage_impl/src/config.rs +++ b/crates/storage_impl/src/config.rs @@ -38,6 +38,10 @@ pub trait TenantConfig: Send + Sync { fn get_redis_key_prefix(&self) -> &str; } +pub trait ClickHouseConfig: TenantConfig + Send + Sync { + fn get_clickhouse_database(&self) -> &str; +} + #[derive(Debug, serde::Deserialize, Clone, Copy, Default)] #[serde(rename_all = "PascalCase")] pub enum QueueStrategy { diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index d008ff3231c..ad97ef6d404 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -328,6 +328,7 @@ keys = "user-agent" [multitenancy] enabled = false +global_tenant = { schema = "public", redis_key_prefix = "" } [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = ""} \ No newline at end of file +public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} \ No newline at end of file
2024-06-04T11:18:49Z
## Description <!-- Describe your changes in detail --> Add Tenant_id as a field for all logs Add Tenant_id action for Kafka messages as well , headers to be a combination of ( tenant_id, merchant_id, payment_id ) Make logical databases and physical tables in clickhouse for different tenants ### 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 establish tenancy in our application and start using the default tenant as 'Hyperswitch' and also offer a 'test' tenant in all environments https://github.com/juspay/hyperswitch-product/issues/50 ## 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)? --> Since there is no new changes involved, sanity testing is enough, Check if the payments are going fine and able to see analytics in dashboard
18493bd8f03b933b15bc3c40b3501222587fc59f
Since there is no new changes involved, sanity testing is enough, Check if the payments are going fine and able to see analytics in dashboard
[ "config/config.example.toml", "config/deployments/env_specific.toml", "config/development.toml", "config/docker_compose.toml", "crates/analytics/src/clickhouse.rs", "crates/analytics/src/lib.rs", "crates/common_utils/src/consts.rs", "crates/diesel_models/src/query/user.rs", "crates/drainer/src/setti...
juspay/hyperswitch
juspay__hyperswitch-4860
Bug: [BUG] Avoid overrides in auto generated OpenAPI specification ### Bug Description If there are types defined with duplicate names, the entry which is specified at the end overrides any previous entries with the same name. This is identified for payments and payouts - Card struct. This is being overriden for payments as it's specified earlier in the list. This is inconsistent and leads to incorrect generation of the OpenAPI spec. ### Expected Behavior There should not be any duplicate types specified in OpenAPI spec. ### Actual Behavior There are duplicate types (Card) specified in OpenAPI spec. ### Steps To Reproduce Check `payment_method_data.card` https://api-reference.hyperswitch.io/api-reference/payments/payments--create ### 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/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs index 69c50da79c2..2df40bd6757 100644 --- a/crates/api_models/src/payouts.rs +++ b/crates/api_models/src/payouts.rs @@ -153,19 +153,19 @@ pub struct PayoutCreateRequest { #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodData { - Card(Card), + Card(CardPayout), Bank(Bank), Wallet(Wallet), } impl Default for PayoutMethodData { fn default() -> Self { - Self::Card(Card::default()) + Self::Card(CardPayout::default()) } } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] -pub struct Card { +pub struct CardPayout { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 237cddcf94e..c15704afa3b 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -440,7 +440,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::GiftCardData, api_models::payments::GiftCardDetails, api_models::payments::Address, - api_models::payouts::Card, + api_models::payouts::CardPayout, api_models::payouts::Wallet, api_models::payouts::Paypal, api_models::payouts::Venmo, diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 6737bbf3af0..873e6f18d23 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -1202,7 +1202,7 @@ pub trait CardData { } #[cfg(feature = "payouts")] -impl CardData for payouts::Card { +impl CardData for payouts::CardPayout { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.expiry_year.clone(); let year = binding.peek(); diff --git a/crates/router/src/types/api/payouts.rs b/crates/router/src/types/api/payouts.rs index d4417c5f1cc..dfe7e949aa1 100644 --- a/crates/router/src/types/api/payouts.rs +++ b/crates/router/src/types/api/payouts.rs @@ -1,5 +1,5 @@ pub use api_models::payouts::{ - AchBankTransfer, BacsBankTransfer, Bank as BankPayout, Card as CardPayout, PayoutActionRequest, + AchBankTransfer, BacsBankTransfer, Bank as BankPayout, CardPayout, PayoutActionRequest, PayoutCreateRequest, PayoutCreateResponse, PayoutListConstraints, PayoutListFilterConstraints, PayoutListFilters, PayoutListResponse, PayoutMethodData, PayoutRequest, PayoutRetrieveBody, PayoutRetrieveRequest, PixBankTransfer, SepaBankTransfer, Wallet as WalletPayout, diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index f42481798a4..195fb7ed00e 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -7054,9 +7054,10 @@ "type": "object", "required": [ "card_number", - "expiry_month", - "expiry_year", - "card_holder_name" + "card_exp_month", + "card_exp_year", + "card_holder_name", + "card_cvc" ], "properties": { "card_number": { @@ -7064,18 +7065,60 @@ "description": "The card number", "example": "4242424242424242" }, - "expiry_month": { + "card_exp_month": { "type": "string", - "description": "The card's expiry month" + "description": "The card's expiry month", + "example": "24" }, - "expiry_year": { + "card_exp_year": { "type": "string", - "description": "The card's expiry year" + "description": "The card's expiry year", + "example": "24" }, "card_holder_name": { "type": "string", "description": "The card holder's name", - "example": "John Doe" + "example": "John Test" + }, + "card_cvc": { + "type": "string", + "description": "The CVC number for the card", + "example": "242" + }, + "card_issuer": { + "type": "string", + "description": "The name of the issuer of card", + "example": "chase", + "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_type": { + "type": "string", + "example": "CREDIT", + "nullable": true + }, + "card_issuing_country": { + "type": "string", + "example": "INDIA", + "nullable": true + }, + "bank_code": { + "type": "string", + "example": "JP_AMEX", + "nullable": true + }, + "nick_name": { + "type": "string", + "description": "The card holder's nick name", + "example": "John Test", + "nullable": true } } }, @@ -7256,6 +7299,35 @@ "Maestro" ] }, + "CardPayout": { + "type": "object", + "required": [ + "card_number", + "expiry_month", + "expiry_year", + "card_holder_name" + ], + "properties": { + "card_number": { + "type": "string", + "description": "The card number", + "example": "4242424242424242" + }, + "expiry_month": { + "type": "string", + "description": "The card's expiry month" + }, + "expiry_year": { + "type": "string", + "description": "The card's expiry year" + }, + "card_holder_name": { + "type": "string", + "description": "The card holder's name", + "example": "John Doe" + } + } + }, "CardRedirectData": { "oneOf": [ { @@ -16752,7 +16824,7 @@ ], "properties": { "card": { - "$ref": "#/components/schemas/Card" + "$ref": "#/components/schemas/CardPayout" } } },
2024-06-04T06:12:38Z
## Description Fixes https://github.com/juspay/hyperswitch/issues/4860 ### 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)? -->
e9be4e22411d218009e6cd6c1a5ef9dc8fc430b7
[ "crates/api_models/src/payouts.rs", "crates/openapi/src/openapi.rs", "crates/router/src/connector/utils.rs", "crates/router/src/types/api/payouts.rs", "openapi/openapi_spec.json" ]
juspay/hyperswitch
juspay__hyperswitch-4805
Bug: Refactor Customers Payment Method List to support Client as well as S2S calls ### Feature Description For Payment Methods v2, the customers payment method list will be supporting client based as well as S2S calls. We are moving it under two distinct endpoints. ### Possible Implementation The customers Payment method list will be moved under two distinct endpoints: - For Client (with payment tokens) - `/payments/:id:/saved_payment_methods` - For Server (without payment token) - `/customers/:cust_id:/saved_payment_methods` Payment tokens for the listed payment methods would be generated only in case of client calls in a payments context.
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index f829d2e48fe..e2b9e2d3a55 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -24,6 +24,7 @@ customer_v2 = [] merchant_account_v2 = [] merchant_connector_account_v2 = [] payment_v2 = [] +payment_methods_v2 = [] routing_v2 = [] [dependencies] diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index ad2e2546f37..589dcd8d10b 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -1,12 +1,19 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; +#[cfg(all( + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2") +))] +use crate::payment_methods::CustomerPaymentMethodsListResponse; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +use crate::payment_methods::CustomerPaymentMethodsListResponse; use crate::{ payment_methods::{ - CustomerDefaultPaymentMethodResponse, CustomerPaymentMethodsListResponse, - DefaultPaymentMethod, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse, - PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, - PaymentMethodCollectLinkResponse, PaymentMethodDeleteResponse, PaymentMethodListRequest, - PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate, + CustomerDefaultPaymentMethodResponse, DefaultPaymentMethod, ListCountriesCurrenciesRequest, + ListCountriesCurrenciesResponse, PaymentMethodCollectLinkRenderRequest, + PaymentMethodCollectLinkRequest, PaymentMethodCollectLinkResponse, + PaymentMethodDeleteResponse, PaymentMethodListRequest, PaymentMethodListResponse, + PaymentMethodResponse, PaymentMethodUpdate, }, payments::{ ExtendedCardInfoResponse, PaymentIdType, PaymentListConstraints, diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 3f1df4b8e96..c90031dc077 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -994,6 +994,19 @@ impl serde::Serialize for PaymentMethodList { } } +#[cfg(all( + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2") +))] +#[derive(Debug, serde::Serialize, ToSchema)] +pub struct CustomerPaymentMethodsListResponse { + /// List of payment methods for customer + pub customer_payment_methods: Vec<CustomerPaymentMethod>, + /// Returns whether a customer id is not tied to a payment intent (only when the request is made against a client secret) + pub is_guest_customer: Option<bool>, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethodsListResponse { /// List of payment methods for customer @@ -1028,6 +1041,97 @@ pub struct CustomerDefaultPaymentMethodResponse { pub payment_method_type: Option<api_enums::PaymentMethodType>, } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[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: Option<String>, + /// The unique identifier of the customer. + #[schema(example = "pm_iouuy468iyuowqs")] + pub payment_method_id: String, + + /// The unique identifier of the customer. + #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] + pub customer_id: id_type::CustomerId, + + /// The type of payment method use for the payment. + #[schema(value_type = PaymentMethod,example = "card")] + pub payment_method: api_enums::PaymentMethod, + + /// This is a sub-category of payment method. + #[schema(value_type = Option<PaymentMethodType>,example = "credit_card")] + pub payment_method_type: Option<api_enums::PaymentMethodType>, + + /// The name of the bank/ provider issuing the payment method to the end user + #[schema(example = "Citibank")] + pub payment_method_issuer: Option<String>, + + /// A standard code representing the issuer of payment method + #[schema(value_type = Option<PaymentMethodIssuerCode>,example = "jp_applepay")] + pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, + + /// Indicates whether the payment method is eligible for recurring payments + #[schema(example = true)] + pub recurring_enabled: bool, + + /// Indicates whether the payment method is eligible for installment payments + #[schema(example = true)] + pub installment_payment_enabled: bool, + + /// Type of payment experience enabled with the connector + #[schema(value_type = Option<Vec<PaymentExperience>>,example = json!(["redirect_to_url"]))] + pub payment_experience: Option<Vec<api_enums::PaymentExperience>>, + + /// PaymentMethod Data from locker + pub payment_method_data: Option<PaymentMethodListData>, + + /// Masked bank details from PM auth services + #[schema(example = json!({"mask": "0000"}))] + pub bank: Option<MaskedBankDetails>, + + /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] + pub metadata: Option<pii::SecretSerdeValue>, + + /// A timestamp (ISO 8601 code) that determines when the customer was created + #[schema(value_type = Option<PrimitiveDateTime>,example = "2023-01-18T11:04:09.922Z")] + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub created: Option<time::PrimitiveDateTime>, + + /// Surcharge details for this saved card + pub surcharge_details: Option<SurchargeDetailsResponse>, + + /// Whether this payment method requires CVV to be collected + #[schema(example = true)] + pub requires_cvv: bool, + + /// A timestamp (ISO 8601 code) that determines when the payment method was last used + #[schema(value_type = Option<PrimitiveDateTime>,example = "2024-02-24T11:04:09.922Z")] + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub last_used_at: Option<time::PrimitiveDateTime>, + /// Indicates if the payment method has been set to default or not + #[schema(example = true)] + pub default_payment_method_set: bool, + + /// The billing details of the payment method + #[schema(value_type = Option<Address>)] + pub billing: Option<payments::Address>, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, Clone, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum PaymentMethodListData { + Card(CardDetailFromLocker), + #[cfg(feature = "payouts")] + Bank(payouts::Bank), +} + +#[cfg(all( + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2") +))] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethod { /// Token for payment method in temporary card locker which gets refreshed often diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 3e6f470d80e..3492006261c 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -37,6 +37,7 @@ v1 = ["api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "stor customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2"] merchant_account_v2 = ["api_models/merchant_account_v2", "diesel_models/merchant_account_v2", "hyperswitch_domain_models/merchant_account_v2"] payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2", "hyperswitch_domain_models/payment_v2"] +payment_methods_v2 = ["api_models/payment_methods_v2"] routing_v2 = ["api_models/routing_v2"] merchant_connector_account_v2 = ["api_models/merchant_connector_account_v2", "kgraph_utils/merchant_connector_account_v2", "hyperswitch_domain_models/merchant_connector_account_v2", "diesel_models/merchant_connector_account_v2"] diff --git a/crates/router/src/compatibility/stripe/customers/types.rs b/crates/router/src/compatibility/stripe/customers/types.rs index e2acc7b17b5..1dc43175342 100644 --- a/crates/router/src/compatibility/stripe/customers/types.rs +++ b/crates/router/src/compatibility/stripe/customers/types.rs @@ -193,7 +193,7 @@ pub struct CustomerPaymentMethodListResponse { #[derive(Default, Serialize, PartialEq, Eq)] pub struct PaymentMethodData { - pub id: String, + pub id: Option<String>, pub object: &'static str, pub card: Option<CardDetails>, pub created: Option<time::PrimitiveDateTime>, @@ -222,12 +222,29 @@ impl From<api::CustomerPaymentMethodsListResponse> for CustomerPaymentMethodList } } +// Check this in review impl From<api_types::CustomerPaymentMethod> for PaymentMethodData { fn from(item: api_types::CustomerPaymentMethod) -> Self { + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") + ))] + let card = item.card.map(From::from); + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] + let card = match item.payment_method_data { + Some(api_types::PaymentMethodListData::Card(card)) => Some(CardDetails::from(card)), + _ => None, + }; Self { + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") + ))] + id: Some(item.payment_token), + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] id: item.payment_token, object: "payment_method", - card: item.card.map(From::from), + card, created: item.created, } } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 8cb64d1e0d8..f3bccf4d65f 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -48,6 +48,11 @@ use super::surcharge_decision_configs::{ perform_surcharge_decision_management_for_payment_method_list, perform_surcharge_decision_management_for_saved_cards, }; +#[cfg(all( + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2") +))] +use crate::routes::app::SessionStateInfo; #[cfg(feature = "payouts")] use crate::types::domain::types::AsyncLift; use crate::{ @@ -67,7 +72,7 @@ use crate::{ }, db, logger, pii::prelude::*, - routes::{self, app::SessionStateInfo, metrics, payment_methods::ParentPaymentMethodToken}, + routes::{self, metrics, payment_methods::ParentPaymentMethodToken}, services, types::{ api::{self, routing as routing_types, PaymentMethodCreateExt}, @@ -3609,6 +3614,63 @@ fn filter_recurring_based( recurring_enabled.map_or(true, |enabled| payment_method.recurring_enabled == enabled) } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub async fn list_customer_payment_method_util( + state: routes::SessionState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + req: Option<api::PaymentMethodListRequest>, + customer_id: Option<id_type::CustomerId>, + is_payment_associated: bool, +) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> { + let limit = req.as_ref().and_then(|pml_req| pml_req.limit); + + let (customer_id, payment_intent) = if is_payment_associated { + let cloned_secret = req.and_then(|r| r.client_secret.clone()); + let payment_intent = helpers::verify_payment_intent_time_and_client_secret( + &state, + &merchant_account, + &key_store, + cloned_secret, + ) + .await?; + + ( + payment_intent + .as_ref() + .and_then(|pi| pi.customer_id.clone()), + payment_intent, + ) + } else { + (customer_id, None) + }; + + let resp = if let Some(cust) = customer_id { + Box::pin(list_customer_payment_method( + &state, + merchant_account, + key_store, + payment_intent, + &cust, + limit, + is_payment_associated, + )) + .await? + } else { + let response = api::CustomerPaymentMethodsListResponse { + customer_payment_methods: Vec::new(), + is_guest_customer: Some(true), + }; + services::ApplicationResponse::Json(response) + }; + + Ok(resp) +} + +#[cfg(all( + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2") +))] pub async fn do_list_customer_pm_fetch_customer_if_not_passed( state: routes::SessionState, merchant_account: domain::MerchantAccount, @@ -3680,6 +3742,10 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed( } } +#[cfg(all( + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2") +))] pub async fn list_customer_payment_method( state: &routes::SessionState, merchant_account: domain::MerchantAccount, @@ -3767,88 +3833,21 @@ pub async fn list_customer_payment_method( let payment_method = pm.payment_method.get_required_value("payment_method")?; - let payment_method_retrieval_context = match payment_method { - enums::PaymentMethod::Card => { - let card_details = - get_card_details_with_locker_fallback(&pm, state, &key_store).await?; - - if card_details.is_some() { - PaymentMethodListContext { - card_details, - #[cfg(feature = "payouts")] - bank_transfer_details: None, - hyperswitch_token_data: 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; - } - } - - enums::PaymentMethod::BankDebit => { - // Retrieve the pm_auth connector details so that it can be tokenized - let bank_account_token_data = - get_bank_account_connector_details(state, &pm, &key_store) - .await - .unwrap_or_else(|error| { - logger::error!(?error); - None - }); - if let Some(data) = bank_account_token_data { - let token_data = PaymentTokenData::AuthBankDebit(data); - - PaymentMethodListContext { - card_details: None, - #[cfg(feature = "payouts")] - bank_transfer_details: None, - hyperswitch_token_data: token_data, - } - } else { - continue; - } - } - - enums::PaymentMethod::Wallet => PaymentMethodListContext { - card_details: None, - #[cfg(feature = "payouts")] - bank_transfer_details: None, - hyperswitch_token_data: PaymentTokenData::wallet_token( - pm.payment_method_id.clone(), - ), - }, + let pm_list_context = get_pm_list_context( + state, + &payment_method, + &key_store, + &pm, + Some(parent_payment_method_token.clone()), + true, + ) + .await?; - #[cfg(feature = "payouts")] - enums::PaymentMethod::BankTransfer => PaymentMethodListContext { - card_details: None, - bank_transfer_details: Some( - get_bank_from_hs_locker( - state, - &key_store, - &parent_payment_method_token, - &pm.customer_id, - &pm.merchant_id, - pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), - ) - .await?, - ), - hyperswitch_token_data: PaymentTokenData::temporary_generic( - parent_payment_method_token.clone(), - ), - }, + if pm_list_context.is_none() { + continue; + } - _ => PaymentMethodListContext { - card_details: None, - #[cfg(feature = "payouts")] - bank_transfer_details: None, - hyperswitch_token_data: PaymentTokenData::temporary_generic(generate_id( - consts::ID_LENGTH, - "token", - )), - }, - }; + let pm_list_context = pm_list_context.get_required_value("PaymentMethodListContext")?; // Retrieve the masked bank details to be sent as a response let bank_details = if payment_method == enums::PaymentMethod::BankDebit { @@ -3904,7 +3903,7 @@ pub async fn list_customer_payment_method( payment_method, payment_method_type: pm.payment_method_type, payment_method_issuer: pm.payment_method_issuer, - card: payment_method_retrieval_context.card_details, + card: pm_list_context.card_details, metadata: pm.metadata, payment_method_issuer_code: pm.payment_method_issuer_code, recurring_enabled: mca_enabled, @@ -3912,7 +3911,7 @@ pub async fn list_customer_payment_method( payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), created: Some(pm.created_at), #[cfg(feature = "payouts")] - bank_transfer: payment_method_retrieval_context.bank_transfer_details, + bank_transfer: pm_list_context.bank_transfer_details, bank: bank_details, surcharge_details: None, requires_cvv, @@ -3934,15 +3933,15 @@ pub async fn list_customer_payment_method( .and_then(|b_profile| b_profile.intent_fulfillment_time) .unwrap_or(consts::DEFAULT_INTENT_FULFILLMENT_TIME); + let hyperswitch_token_data = pm_list_context + .hyperswitch_token_data + .get_required_value("PaymentTokenData")?; + ParentPaymentMethodToken::create_key_for_token(( &parent_payment_method_token, pma.payment_method, )) - .insert( - intent_fulfillment_time, - payment_method_retrieval_context.hyperswitch_token_data, - state, - ) + .insert(intent_fulfillment_time, hyperswitch_token_data, state) .await?; if let Some(metadata) = pma.metadata { @@ -3973,6 +3972,115 @@ pub async fn list_customer_payment_method( customer_payment_methods: customer_pms, is_guest_customer: payment_intent.as_ref().map(|_| false), //to return this key only when the request is tied to a payment intent }; + + Box::pin(perform_surcharge_ops( + payment_intent, + state, + merchant_account, + key_store, + business_profile, + &mut response, + )) + .await?; + + Ok(services::ApplicationResponse::Json(response)) +} + +async fn get_pm_list_context( + state: &routes::SessionState, + payment_method: &enums::PaymentMethod, + key_store: &domain::MerchantKeyStore, + pm: &diesel_models::PaymentMethod, + #[cfg(feature = "payouts")] parent_payment_method_token: Option<String>, + #[cfg(not(feature = "payouts"))] _parent_payment_method_token: Option<String>, + is_payment_associated: bool, +) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> { + let payment_method_retrieval_context = match payment_method { + enums::PaymentMethod::Card => { + let card_details = get_card_details_with_locker_fallback(pm, state, key_store).await?; + + card_details.as_ref().map(|card| PaymentMethodListContext { + card_details: Some(card.clone()), + #[cfg(feature = "payouts")] + bank_transfer_details: None, + hyperswitch_token_data: is_payment_associated.then_some( + PaymentTokenData::permanent_card( + Some(pm.payment_method_id.clone()), + pm.locker_id.clone().or(Some(pm.payment_method_id.clone())), + pm.locker_id.clone().unwrap_or(pm.payment_method_id.clone()), + ), + ), + }) + } + + enums::PaymentMethod::BankDebit => { + // Retrieve the pm_auth connector details so that it can be tokenized + let bank_account_token_data = get_bank_account_connector_details(state, pm, key_store) + .await + .unwrap_or_else(|err| { + logger::error!(error=?err); + None + }); + + bank_account_token_data.map(|data| { + let token_data = PaymentTokenData::AuthBankDebit(data); + + PaymentMethodListContext { + card_details: None, + #[cfg(feature = "payouts")] + bank_transfer_details: None, + hyperswitch_token_data: is_payment_associated.then_some(token_data), + } + }) + } + + enums::PaymentMethod::Wallet => Some(PaymentMethodListContext { + card_details: None, + #[cfg(feature = "payouts")] + bank_transfer_details: None, + hyperswitch_token_data: is_payment_associated + .then_some(PaymentTokenData::wallet_token(pm.payment_method_id.clone())), + }), + + #[cfg(feature = "payouts")] + enums::PaymentMethod::BankTransfer => Some(PaymentMethodListContext { + card_details: None, + bank_transfer_details: Some( + get_bank_from_hs_locker( + state, + key_store, + parent_payment_method_token.as_ref(), + &pm.customer_id, + &pm.merchant_id, + pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), + ) + .await?, + ), + hyperswitch_token_data: parent_payment_method_token + .map(|token| PaymentTokenData::temporary_generic(token.clone())), + }), + + _ => Some(PaymentMethodListContext { + card_details: None, + #[cfg(feature = "payouts")] + bank_transfer_details: None, + hyperswitch_token_data: is_payment_associated.then_some( + PaymentTokenData::temporary_generic(generate_id(consts::ID_LENGTH, "token")), + ), + }), + }; + + Ok(payment_method_retrieval_context) +} + +async fn perform_surcharge_ops( + payment_intent: Option<storage::PaymentIntent>, + state: &routes::SessionState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + business_profile: Option<BusinessProfile>, + response: &mut api::CustomerPaymentMethodsListResponse, +) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { let payment_attempt = payment_intent .as_ref() .async_map(|payment_intent| async { @@ -3989,7 +4097,6 @@ pub async fn list_customer_payment_method( }) .await .transpose()?; - if let Some((payment_attempt, payment_intent, business_profile)) = payment_attempt .zip(payment_intent) .zip(business_profile) @@ -4002,13 +4109,355 @@ pub async fn list_customer_payment_method( &business_profile, &payment_attempt, payment_intent, - &mut response, + response, + ) + .await?; + } + + Ok(()) +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +struct SavedPMLPaymentsInfo { + pub payment_intent: storage::PaymentIntent, + pub business_profile: Option<BusinessProfile>, + pub requires_cvv: bool, + pub off_session_payment_flag: bool, + pub is_connector_agnostic_mit_enabled: bool, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl SavedPMLPaymentsInfo { + pub async fn form_payments_info( + payment_intent: storage::PaymentIntent, + merchant_account: &domain::MerchantAccount, + db: &dyn db::StorageInterface, + ) -> errors::RouterResult<Self> { + let requires_cvv = db + .find_config_by_key_unwrap_or( + format!("{}_requires_cvv", merchant_account.get_id()).as_str(), + Some("true".to_string()), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch requires_cvv config")? + .config + != "false"; + + let off_session_payment_flag = matches!( + payment_intent.setup_future_usage, + Some(common_enums::FutureUsage::OffSession) + ); + + let profile_id = core_utils::get_profile_id_from_business_details( + payment_intent.business_country, + payment_intent.business_label.as_ref(), + merchant_account, + payment_intent.profile_id.as_ref(), + db, + false, + ) + .await + .attach_printable("Could not find profile id from business details")?; + + let business_profile = core_utils::validate_and_get_business_profile( + db, + Some(profile_id).as_ref(), + merchant_account.get_id(), ) .await?; + + let is_connector_agnostic_mit_enabled = business_profile + .as_ref() + .and_then(|business_profile| business_profile.is_connector_agnostic_mit_enabled) + .unwrap_or(false); + + Ok(Self { + payment_intent, + business_profile, + requires_cvv, + off_session_payment_flag, + is_connector_agnostic_mit_enabled, + }) + } + + pub async fn perform_payment_ops( + &self, + state: &routes::SessionState, + parent_payment_method_token: Option<String>, + pma: &api::CustomerPaymentMethod, + pm_list_context: PaymentMethodListContext, + ) -> errors::RouterResult<()> { + let token = parent_payment_method_token + .as_ref() + .get_required_value("parent_payment_method_token")?; + let hyperswitch_token_data = pm_list_context + .hyperswitch_token_data + .get_required_value("PaymentTokenData")?; + + let intent_fulfillment_time = self + .business_profile + .as_ref() + .and_then(|b_profile| b_profile.intent_fulfillment_time) + .unwrap_or(consts::DEFAULT_INTENT_FULFILLMENT_TIME); + + ParentPaymentMethodToken::create_key_for_token((token, pma.payment_method)) + .insert(intent_fulfillment_time, hyperswitch_token_data, state) + .await?; + + if let Some(metadata) = pma.metadata.clone() { + let pm_metadata_vec: payment_methods::PaymentMethodMetadata = metadata + .parse_value("PaymentMethodMetadata") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed to deserialize metadata to PaymentmethodMetadata struct", + )?; + + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + + for pm_metadata in pm_metadata_vec.payment_method_tokenization { + let key = format!( + "pm_token_{}_{}_{}", + token, pma.payment_method, pm_metadata.0 + ); + + redis_conn + .set_key_with_expiry(&key, pm_metadata.1, intent_fulfillment_time) + .await + .change_context(errors::StorageError::KVError) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add data in redis")?; + } + } + + Ok(()) + } +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub async fn list_customer_payment_method( + state: &routes::SessionState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + payment_intent: Option<storage::PaymentIntent>, + customer_id: &id_type::CustomerId, + limit: Option<i64>, + is_payment_associated: bool, +) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> { + let db = &*state.store; + let key_manager_state = &(state).into(); + // let key = key_store.key.get_inner().peek(); + + let customer = db + .find_customer_by_customer_id_merchant_id( + key_manager_state, + customer_id, + merchant_account.get_id(), + &key_store, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + + let payments_info = payment_intent + .async_map(|pi| SavedPMLPaymentsInfo::form_payments_info(pi, &merchant_account, db)) + .await + .transpose()?; + + let saved_payment_methods = db + .find_payment_method_by_customer_id_merchant_id_status( + customer_id, + merchant_account.get_id(), + common_enums::PaymentMethodStatus::Active, + limit, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + + let mut filtered_saved_payment_methods_ctx = Vec::new(); + for pm in saved_payment_methods.into_iter() { + let payment_method = pm.payment_method.get_required_value("payment_method")?; + let parent_payment_method_token = + is_payment_associated.then(|| generate_id(consts::ID_LENGTH, "token")); + + let pm_list_context = get_pm_list_context( + state, + &payment_method, + &key_store, + &pm, + parent_payment_method_token.clone(), + is_payment_associated, + ) + .await?; + + if let Some(ctx) = pm_list_context { + filtered_saved_payment_methods_ctx.push((ctx, parent_payment_method_token, pm)); + } + } + + let pm_list_futures = filtered_saved_payment_methods_ctx + .into_iter() + .map(|ctx| { + generate_saved_pm_response( + state, + &key_store, + &merchant_account, + ctx, + &customer, + payments_info.as_ref(), + ) + }) + .collect::<Vec<_>>(); + + let final_result = futures::future::join_all(pm_list_futures).await; + + let mut customer_pms = Vec::new(); + for result in final_result.into_iter() { + let pma = result.attach_printable("saved pm list failed")?; + customer_pms.push(pma); + } + + let mut response = api::CustomerPaymentMethodsListResponse { + customer_payment_methods: customer_pms, + is_guest_customer: is_payment_associated.then_some(false), //to return this key only when the request is tied to a payment intent + }; + + if is_payment_associated { + Box::pin(perform_surcharge_ops( + payments_info.as_ref().map(|pi| pi.payment_intent.clone()), + state, + merchant_account, + key_store, + payments_info.and_then(|pi| pi.business_profile), + &mut response, + )) + .await?; } Ok(services::ApplicationResponse::Json(response)) } + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +async fn generate_saved_pm_response( + state: &routes::SessionState, + key_store: &domain::MerchantKeyStore, + merchant_account: &domain::MerchantAccount, + pm_list_context: ( + PaymentMethodListContext, + Option<String>, + diesel_models::PaymentMethod, + ), + customer: &domain::Customer, + payment_info: Option<&SavedPMLPaymentsInfo>, +) -> Result<api::CustomerPaymentMethod, error_stack::Report<errors::ApiErrorResponse>> { + let (pm_list_context, parent_payment_method_token, pm) = pm_list_context; + let payment_method = pm.payment_method.get_required_value("payment_method")?; + + let bank_details = if payment_method == enums::PaymentMethod::BankDebit { + get_masked_bank_details(state, &pm, key_store) + .await + .unwrap_or_else(|err| { + logger::error!(error=?err); + None + }) + } else { + None + }; + + let payment_method_billing = decrypt_generic_data::<api_models::payments::Address>( + state, + pm.payment_method_billing_address, + key_store, + ) + .await + .attach_printable("unable to decrypt payment method billing address details")?; + + let connector_mandate_details = pm + .connector_mandate_details + .clone() + .map(|val| val.parse_value::<storage::PaymentsMandateReference>("PaymentsMandateReference")) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize to Payment Mandate Reference ")?; + + let (is_connector_agnostic_mit_enabled, requires_cvv, off_session_payment_flag) = payment_info + .map(|pi| { + ( + pi.is_connector_agnostic_mit_enabled, + pi.requires_cvv, + pi.off_session_payment_flag, + ) + }) + .unwrap_or((false, false, false)); + + let mca_enabled = get_mca_status( + state, + key_store, + merchant_account.get_id(), + is_connector_agnostic_mit_enabled, + connector_mandate_details, + pm.network_transaction_id.as_ref(), + ) + .await?; + + let requires_cvv = if is_connector_agnostic_mit_enabled { + requires_cvv + && !(off_session_payment_flag + && (pm.connector_mandate_details.is_some() || pm.network_transaction_id.is_some())) + } else { + requires_cvv && !(off_session_payment_flag && pm.connector_mandate_details.is_some()) + }; + + let pmd = if let Some(card) = pm_list_context.card_details.as_ref() { + Some(api::PaymentMethodListData::Card(card.clone())) + } else if cfg!(feature = "payouts") { + pm_list_context + .bank_transfer_details + .clone() + .map(api::PaymentMethodListData::Bank) + } else { + None + }; + + let pma = api::CustomerPaymentMethod { + payment_token: parent_payment_method_token.clone(), + payment_method_id: pm.payment_method_id.clone(), + customer_id: pm.customer_id, + payment_method, + payment_method_type: pm.payment_method_type, + payment_method_issuer: pm.payment_method_issuer, + payment_method_data: pmd, + metadata: pm.metadata, + payment_method_issuer_code: pm.payment_method_issuer_code, + recurring_enabled: mca_enabled, + installment_payment_enabled: false, + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + created: Some(pm.created_at), + bank: bank_details, + surcharge_details: None, + requires_cvv: requires_cvv + && !(off_session_payment_flag && pm.connector_mandate_details.is_some()), + last_used_at: Some(pm.last_used_at), + default_payment_method_set: customer.default_payment_method_id.is_some() + && customer.default_payment_method_id == Some(pm.payment_method_id), + billing: payment_method_billing, + }; + + payment_info + .async_map(|pi| { + pi.perform_payment_ops(state, parent_payment_method_token, &pma, pm_list_context) + }) + .await + .transpose()?; + + Ok(pma) +} + pub async fn get_mca_status( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, @@ -4396,7 +4845,7 @@ pub async fn update_last_used_at( pub async fn get_bank_from_hs_locker( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, - temp_token: &str, + temp_token: Option<&String>, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, token_ref: &str, @@ -4419,16 +4868,18 @@ pub async fn get_bank_from_hs_locker( .change_context(errors::ApiErrorResponse::InternalServerError)?; match &pm_parsed { api::PayoutMethodData::Bank(bank) => { - vault::Vault::store_payout_method_data_in_locker( - state, - Some(temp_token.to_string()), - &pm_parsed, - Some(customer_id.to_owned()), - key_store, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error storing payout method data in temporary locker")?; + if let Some(token) = temp_token { + vault::Vault::store_payout_method_data_in_locker( + state, + Some(token.clone()), + &pm_parsed, + Some(customer_id.to_owned()), + key_store, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error storing payout method data in temporary locker")?; + } Ok(bank.to_owned()) } api::PayoutMethodData::Card(_) => Err(errors::ApiErrorResponse::InvalidRequestData { diff --git a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs index 6a3ceeada1c..23f79848dee 100644 --- a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs +++ b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs @@ -3,7 +3,16 @@ use api_models::{ payments, routing, surcharge_decision_configs::{self, SurchargeDecisionConfigs, SurchargeDecisionManagerRecord}, }; +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] use common_utils::{ext_traits::StringExt, types as common_utils_types}; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +use common_utils::{ + ext_traits::{OptionExt, StringExt}, + types as common_utils_types, +}; use error_stack::{self, ResultExt}; use euclid::{ backend, @@ -267,6 +276,11 @@ where } Ok(surcharge_metadata) } + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] pub async fn perform_surcharge_decision_management_for_saved_cards( state: &SessionState, algorithm_ref: routing::RoutingAlgorithmRef, @@ -303,10 +317,13 @@ pub async fn perform_surcharge_decision_management_for_saved_cards( .change_context(ConfigError::InputConstructionError)?; for customer_payment_method in customer_payment_method_list.iter_mut() { + let payment_token = customer_payment_method.payment_token.clone(); + backend_input.payment_method.payment_method = Some(customer_payment_method.payment_method); backend_input.payment_method.payment_method_type = customer_payment_method.payment_method_type; - backend_input.payment_method.card_network = customer_payment_method + + let card_network = customer_payment_method .card .as_ref() .and_then(|card| card.scheme.as_ref()) @@ -317,13 +334,98 @@ pub async fn perform_surcharge_decision_management_for_saved_cards( .change_context(ConfigError::DslExecutionError) }) .transpose()?; + + backend_input.payment_method.card_network = card_network; + + let surcharge_details = surcharge_source + .generate_surcharge_details_and_populate_surcharge_metadata( + &backend_input, + payment_attempt, + ( + &mut surcharge_metadata, + types::SurchargeKey::Token(payment_token), + ), + )?; + customer_payment_method.surcharge_details = surcharge_details + .map(|surcharge_details| { + SurchargeDetailsResponse::foreign_try_from((&surcharge_details, payment_attempt)) + .change_context(ConfigError::DslParsingError) + }) + .transpose()?; + } + Ok(surcharge_metadata) +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub async fn perform_surcharge_decision_management_for_saved_cards( + state: &SessionState, + algorithm_ref: routing::RoutingAlgorithmRef, + payment_attempt: &storage::PaymentAttempt, + payment_intent: &storage::PaymentIntent, + customer_payment_method_list: &mut [api_models::payment_methods::CustomerPaymentMethod], +) -> ConditionalConfigResult<types::SurchargeMetadata> { + let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.attempt_id.clone()); + let surcharge_source = match ( + payment_attempt.get_surcharge_details(), + algorithm_ref.surcharge_config_algo_id, + ) { + (Some(request_surcharge_details), _) => { + SurchargeSource::Predetermined(request_surcharge_details) + } + (None, Some(algorithm_id)) => { + let cached_algo = ensure_algorithm_cached( + &*state.store, + &payment_attempt.merchant_id, + algorithm_id.as_str(), + ) + .await?; + + SurchargeSource::Generate(cached_algo) + } + (None, None) => return Ok(surcharge_metadata), + }; + let surcharge_source_log_message = match &surcharge_source { + SurchargeSource::Generate(_) => "Surcharge was calculated through surcharge rules", + SurchargeSource::Predetermined(_) => "Surcharge was sent in payment create request", + }; + logger::debug!(customer_saved_card_list_surcharge_source = surcharge_source_log_message); + let mut backend_input = make_dsl_input_for_surcharge(payment_attempt, payment_intent, None) + .change_context(ConfigError::InputConstructionError)?; + + for customer_payment_method in customer_payment_method_list.iter_mut() { + let payment_token = customer_payment_method + .payment_token + .clone() + .get_required_value("payment_token") + .change_context(ConfigError::InputConstructionError)?; + + backend_input.payment_method.payment_method = Some(customer_payment_method.payment_method); + backend_input.payment_method.payment_method_type = + customer_payment_method.payment_method_type; + + let card_network = match &customer_payment_method.payment_method_data { + Some(api_models::payment_methods::PaymentMethodListData::Card(card)) => card + .scheme + .as_ref() + .map(|scheme| { + scheme + .clone() + .parse_enum("CardNetwork") + .change_context(ConfigError::DslExecutionError) + }) + .transpose()?, + _ => None, + }; + + backend_input.payment_method.card_network = card_network; + let surcharge_details = surcharge_source .generate_surcharge_details_and_populate_surcharge_metadata( &backend_input, payment_attempt, ( &mut surcharge_metadata, - types::SurchargeKey::Token(customer_payment_method.payment_token.clone()), + types::SurchargeKey::Token(payment_token), ), )?; customer_payment_method.surcharge_details = surcharge_details diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 708fcbbf406..2286ee8265c 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -30,7 +30,7 @@ use super::blocklist; use super::currency; #[cfg(feature = "dummy_connector")] use super::dummy_connector::*; -#[cfg(all(any(feature = "olap", feature = "oltp"), not(feature = "customer_v2")))] +#[cfg(any(feature = "olap", feature = "oltp"))] use super::payment_methods::*; #[cfg(feature = "payouts")] use super::payout_link::*; @@ -501,7 +501,30 @@ impl DummyConnector { pub struct Payments; -#[cfg(any(feature = "olap", feature = "oltp"))] +#[cfg(all( + any(feature = "olap", feature = "oltp"), + feature = "v2", + feature = "payment_methods_v2", + feature = "payment_v2" +))] +impl Payments { + pub fn server(state: AppState) -> Scope { + let mut route = web::scope("/v2/payments").app_data(web::Data::new(state)); + route = route.service( + web::resource("/{payment_id}/saved_payment_methods") + .route(web::get().to(list_customer_payment_method_for_payment)), + ); + + route + } +} + +#[cfg(all( + any(feature = "olap", feature = "oltp"), + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2"), + not(feature = "payment_v2") +))] impl Payments { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/payments").app_data(web::Data::new(state)); @@ -590,7 +613,7 @@ impl Payments { ) .service( web::resource("/{payment_id}/extended_card_info").route(web::get().to(retrieve_extended_card_info)), - ); + ) } route } @@ -844,6 +867,7 @@ pub struct Customers; #[cfg(all( feature = "v2", feature = "customer_v2", + feature = "payment_methods_v2", any(feature = "olap", feature = "oltp") ))] impl Customers { @@ -853,6 +877,13 @@ impl Customers { { route = route.service(web::resource("").route(web::post().to(customers_create))) } + #[cfg(all(feature = "oltp", feature = "v2", feature = "payment_methods_v2"))] + { + route = route.service( + web::resource("/{customer_id}/saved_payment_methods") + .route(web::get().to(list_customer_payment_method_api)), + ); + } route } } @@ -860,6 +891,7 @@ impl Customers { #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "customer_v2"), + not(feature = "payment_methods_v2"), any(feature = "olap", feature = "oltp") ))] impl Customers { @@ -897,13 +929,12 @@ impl Customers { .route(web::get().to(customers_retrieve)) .route(web::post().to(customers_update)) .route(web::delete().to(customers_delete)), - ); + ) } route } } - pub struct Refunds; #[cfg(any(feature = "olap", feature = "oltp"))] diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index f55f6c80e7a..6d7b3526b79 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -229,6 +229,11 @@ pub async fn list_payment_method_api( )) .await } + +#[cfg(all( + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2") +))] /// List payment methods for a Customer /// /// To filter and list the applicable payment methods for a particular Customer ID @@ -287,6 +292,134 @@ pub async fn list_customer_payment_method_api( )) .await } + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +/// List payment methods for a Customer v2 +/// +/// To filter and list the applicable payment methods for a particular Customer ID, is to be associated with a payment +#[utoipa::path( + get, + path = "v2/payments/{payment_id}/saved_payment_methods", + params ( + ("client-secret" = String, Path, description = "A secret known only to your application and the authorization server"), + ("accepted_country" = Vec<String>, Query, description = "The two-letter ISO currency code"), + ("accepted_currency" = Vec<Currency>, Path, description = "The three-letter ISO currency code"), + ("minimum_amount" = i64, Query, description = "The minimum amount accepted for processing by the particular payment method."), + ("maximum_amount" = i64, Query, description = "The maximum amount amount accepted for processing by the particular payment method."), + ("recurring_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for recurring payments"), + ("installment_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for installment payments"), + ), + responses( + (status = 200, description = "Payment Methods retrieved for customer tied to its respective client-secret passed in the param", body = CustomerPaymentMethodsListResponse), + (status = 400, description = "Invalid Data"), + (status = 404, description = "Payment Methods does not exist in records") + ), + tag = "Payment Methods", + operation_id = "List all Payment Methods for a Customer", + security(("publishable_key" = [])) +)] +#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))] +pub async fn list_customer_payment_method_for_payment( + state: web::Data<AppState>, + payment_id: web::Path<(String,)>, + req: HttpRequest, + query_payload: web::Query<payment_methods::PaymentMethodListRequest>, +) -> HttpResponse { + let flow = Flow::CustomerPaymentMethodsList; + let payload = query_payload.into_inner(); + let _payment_id = payment_id.into_inner().0.clone(); + + let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) { + Ok((auth, _auth_flow)) => (auth, _auth_flow), + Err(e) => return api::log_and_return_error_response(e), + }; + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth, req, _| { + cards::list_customer_payment_method_util( + state, + auth.merchant_account, + auth.key_store, + Some(req), + None, + true, + ) + }, + &*auth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +/// List payment methods for a Customer v2 +/// +/// To filter and list the applicable payment methods for a particular Customer ID, to be used in a non-payments context +#[utoipa::path( + get, + path = "v2/customers/{customer_id}/saved_payment_methods", + params ( + ("accepted_country" = Vec<String>, Query, description = "The two-letter ISO currency code"), + ("accepted_currency" = Vec<Currency>, Path, description = "The three-letter ISO currency code"), + ("minimum_amount" = i64, Query, description = "The minimum amount accepted for processing by the particular payment method."), + ("maximum_amount" = i64, Query, description = "The maximum amount amount accepted for processing by the particular payment method."), + ("recurring_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for recurring payments"), + ("installment_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for installment payments"), + ), + responses( + (status = 200, description = "Payment Methods retrieved", body = CustomerPaymentMethodsListResponse), + (status = 400, description = "Invalid Data"), + (status = 404, description = "Payment Methods does not exist in records") + ), + tag = "Payment Methods", + operation_id = "List all Payment Methods for a Customer", + security(("api_key" = [])) +)] +#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))] +pub async fn list_customer_payment_method_api( + state: web::Data<AppState>, + customer_id: web::Path<(id_type::CustomerId,)>, + req: HttpRequest, + query_payload: web::Query<payment_methods::PaymentMethodListRequest>, +) -> HttpResponse { + let flow = Flow::CustomerPaymentMethodsList; + let payload = query_payload.into_inner(); + let customer_id = customer_id.into_inner().0.clone(); + + let ephemeral_or_api_auth = match auth::is_ephemeral_auth(req.headers()) { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(err), + }; + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth, req, _| { + cards::list_customer_payment_method_util( + state, + auth.merchant_account, + auth.key_store, + Some(req), + Some(customer_id.clone()), + false, + ) + }, + &*ephemeral_or_api_auth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(all( + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2") +))] /// List payment methods for a Customer /// /// To filter and list the applicable payment methods for a particular Customer ID diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index 77873503d6e..062a2fdf630 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -1,3 +1,19 @@ +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub use api_models::payment_methods::{ + CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CustomerPaymentMethod, + CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest, + GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, + PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate, + PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodList, + PaymentMethodListData, PaymentMethodListRequest, PaymentMethodListResponse, + PaymentMethodMigrate, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData, + TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2, + TokenizedWalletValue1, TokenizedWalletValue2, +}; +#[cfg(all( + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2") +))] pub use api_models::payment_methods::{ CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CustomerPaymentMethod, CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest, diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index 8a8f89f9017..05e3e566c07 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -81,7 +81,7 @@ impl PaymentTokenData { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodListContext { pub card_details: Option<api::CardDetailFromLocker>, - pub hyperswitch_token_data: PaymentTokenData, + pub hyperswitch_token_data: Option<PaymentTokenData>, #[cfg(feature = "payouts")] pub bank_transfer_details: Option<api::BankPayout>, }
2024-06-03T13:32:14Z
## Description <!-- Describe your changes in detail --> Refactored customer's pml for v2 The customers Payment method list will be moved under two distinct endpoints: For Client (with payment tokens) - /payments/:id:/saved_payment_methods For Server (without payment token) - /customers/:cust_id:/saved_payment_methods Payment tokens for the listed payment methods would be generated only in case of client calls in a payments context. ### 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)? --> - Save a card - Create another payment ``` curl --location --request POST 'http://localhost:8080/v2/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' \ --data-raw '{ "amount": 200, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "Some_cust2", "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", "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" }, "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": "8056594430", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response - ``` { "payment_id": "pay_GNxoHRthb37nMZt6KLhv", "merchant_id": "sarthak1", "status": "requires_payment_method", "amount": 200, "net_amount": 200, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_GNxoHRthb37nMZt6KLhv_secret_G97qG0GJ85JeGks8NmnA", "created": "2024-07-02T09:56:52.153Z", "currency": "USD", "customer_id": "Some_cust2", "customer": { "id": "Some_cust2", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "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": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "Some_cust2", "created_at": 1719914212, "expires": 1719917812, "secret": "epk_7299286e8535424b957d32f6f5e44e99" }, "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": null, "payment_link": null, "profile_id": "pro_1HgRzJgJf21X3s7FPrhP", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-02T10:11:52.153Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-07-02T09:56:52.226Z", "charges": null, "frm_metadata": null } ``` - List saved payment method for v2 ``` curl --location --request GET 'http://localhost:8080/v2/payments/pay_GNxoHRthb37nMZt6KLhv/saved_payment_methods?client_secret=pay_GNxoHRthb37nMZt6KLhv_secret_G97qG0GJ85JeGks8NmnA' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_16e38a16176e45298a70da6c56c5028d' ``` Response - ``` { "customer_payment_methods": [ { "payment_token": "token_SBCX3r5nb9QaHNGtSbgK", "payment_method_id": "pm_R8n4IKXyEpAGcKaEQl0g", "customer_id": "Some_cust2", "payment_method": "card", "payment_method_type": null, "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "payment_method_data": { "Card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "10", "expiry_year": "2025", "card_token": null, "card_holder_name": "joseph Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true } }, "bank": null, "metadata": null, "created": "2024-06-26T08:26:47.674Z", "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-06-26T10:39:30.552Z", "default_payment_method_set": false, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } }, { "payment_token": "token_nvHY8mkVcPYA94KQefdx", "payment_method_id": "pm_xFF1OOhEMqVQhzEv3b06", "customer_id": "Some_cust2", "payment_method": "card", "payment_method_type": null, "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "payment_method_data": { "Card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "10", "expiry_year": "2025", "card_token": null, "card_holder_name": "joseph Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true } }, "bank": null, "metadata": null, "created": "2024-06-13T11:55:47.828Z", "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-06-13T11:55:47.828Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } } ], "is_guest_customer": false } ``` - Use Merchant API for saved payment methods - ``` curl --location --request GET 'http://localhost:8080/v2/customers/Some_cust2/saved_payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' ``` Response - ``` { "customer_payment_methods": [ { "payment_token": null, "payment_method_id": "pm_R8n4IKXyEpAGcKaEQl0g", "customer_id": "Some_cust2", "payment_method": "card", "payment_method_type": null, "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "payment_method_data": { "Card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "10", "expiry_year": "2025", "card_token": null, "card_holder_name": "joseph Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true } }, "bank": null, "metadata": null, "created": "2024-06-26T08:26:47.674Z", "surcharge_details": null, "requires_cvv": false, "last_used_at": "2024-06-26T10:39:30.552Z", "default_payment_method_set": false, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } }, { "payment_token": null, "payment_method_id": "pm_xFF1OOhEMqVQhzEv3b06", "customer_id": "Some_cust2", "payment_method": "card", "payment_method_type": null, "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "payment_method_data": { "Card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "10", "expiry_year": "2025", "card_token": null, "card_holder_name": "joseph Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true } }, "bank": null, "metadata": null, "created": "2024-06-13T11:55:47.828Z", "surcharge_details": null, "requires_cvv": false, "last_used_at": "2024-06-13T11:55:47.828Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } } ], "is_guest_customer": null } ```
537630f00482939d4c0b49c643dee3763fe0e046
- Save a card - Create another payment ``` curl --location --request POST 'http://localhost:8080/v2/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' \ --data-raw '{ "amount": 200, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "Some_cust2", "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", "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" }, "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": "8056594430", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response - ``` { "payment_id": "pay_GNxoHRthb37nMZt6KLhv", "merchant_id": "sarthak1", "status": "requires_payment_method", "amount": 200, "net_amount": 200, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_GNxoHRthb37nMZt6KLhv_secret_G97qG0GJ85JeGks8NmnA", "created": "2024-07-02T09:56:52.153Z", "currency": "USD", "customer_id": "Some_cust2", "customer": { "id": "Some_cust2", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "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": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "Some_cust2", "created_at": 1719914212, "expires": 1719917812, "secret": "epk_7299286e8535424b957d32f6f5e44e99" }, "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": null, "payment_link": null, "profile_id": "pro_1HgRzJgJf21X3s7FPrhP", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-07-02T10:11:52.153Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-07-02T09:56:52.226Z", "charges": null, "frm_metadata": null } ``` - List saved payment method for v2 ``` curl --location --request GET 'http://localhost:8080/v2/payments/pay_GNxoHRthb37nMZt6KLhv/saved_payment_methods?client_secret=pay_GNxoHRthb37nMZt6KLhv_secret_G97qG0GJ85JeGks8NmnA' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_16e38a16176e45298a70da6c56c5028d' ``` Response - ``` { "customer_payment_methods": [ { "payment_token": "token_SBCX3r5nb9QaHNGtSbgK", "payment_method_id": "pm_R8n4IKXyEpAGcKaEQl0g", "customer_id": "Some_cust2", "payment_method": "card", "payment_method_type": null, "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "payment_method_data": { "Card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "10", "expiry_year": "2025", "card_token": null, "card_holder_name": "joseph Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true } }, "bank": null, "metadata": null, "created": "2024-06-26T08:26:47.674Z", "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-06-26T10:39:30.552Z", "default_payment_method_set": false, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } }, { "payment_token": "token_nvHY8mkVcPYA94KQefdx", "payment_method_id": "pm_xFF1OOhEMqVQhzEv3b06", "customer_id": "Some_cust2", "payment_method": "card", "payment_method_type": null, "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "payment_method_data": { "Card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "10", "expiry_year": "2025", "card_token": null, "card_holder_name": "joseph Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true } }, "bank": null, "metadata": null, "created": "2024-06-13T11:55:47.828Z", "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-06-13T11:55:47.828Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } } ], "is_guest_customer": false } ``` - Use Merchant API for saved payment methods - ``` curl --location --request GET 'http://localhost:8080/v2/customers/Some_cust2/saved_payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' ``` Response - ``` { "customer_payment_methods": [ { "payment_token": null, "payment_method_id": "pm_R8n4IKXyEpAGcKaEQl0g", "customer_id": "Some_cust2", "payment_method": "card", "payment_method_type": null, "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "payment_method_data": { "Card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "10", "expiry_year": "2025", "card_token": null, "card_holder_name": "joseph Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true } }, "bank": null, "metadata": null, "created": "2024-06-26T08:26:47.674Z", "surcharge_details": null, "requires_cvv": false, "last_used_at": "2024-06-26T10:39:30.552Z", "default_payment_method_set": false, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } }, { "payment_token": null, "payment_method_id": "pm_xFF1OOhEMqVQhzEv3b06", "customer_id": "Some_cust2", "payment_method": "card", "payment_method_type": null, "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "payment_method_data": { "Card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "10", "expiry_year": "2025", "card_token": null, "card_holder_name": "joseph Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true } }, "bank": null, "metadata": null, "created": "2024-06-13T11:55:47.828Z", "surcharge_details": null, "requires_cvv": false, "last_used_at": "2024-06-13T11:55:47.828Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } } ], "is_guest_customer": null } ```
[ "crates/api_models/Cargo.toml", "crates/api_models/src/events/payment.rs", "crates/api_models/src/payment_methods.rs", "crates/router/Cargo.toml", "crates/router/src/compatibility/stripe/customers/types.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/payment_methods/surch...
juspay/hyperswitch
juspay__hyperswitch-4848
Bug: refactor: Home and Sign out API changes for 2FA Phase - II As we are having the reset TOTP and regenerate recovery codes flows in the Phase - II, we need to let FE know whether the user has completed the 2FA or not and also number of recovery codes left for the user, so that FE can show a warning if there are less. And also redis needs to be cleaned up if user signs out.
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index ee9498cfeee..a61b9fd7dff 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -165,7 +165,10 @@ pub struct GetUserDetailsResponse { #[serde(skip_serializing)] pub user_id: String, pub org_id: String, + pub is_two_factor_auth_setup: bool, + pub recovery_codes_left: Option<usize>, } + #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetUserRoleDetailsRequest { pub email: pii::Email, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index c259e87c93d..f7ef79bb7d6 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -94,6 +94,8 @@ pub async fn get_user_details( verification_days_left, role_id: user_from_token.role_id, org_id: user_from_token.org_id, + is_two_factor_auth_setup: user.get_totp_status() == TotpStatus::Set, + recovery_codes_left: user.get_recovery_codes().map(|codes| codes.len()), }, )) } @@ -328,6 +330,10 @@ pub async fn signout( state: SessionState, user_from_token: auth::UserFromToken, ) -> UserResponse<()> { + tfa_utils::delete_totp_from_redis(&state, &user_from_token.user_id).await?; + tfa_utils::delete_recovery_code_from_redis(&state, &user_from_token.user_id).await?; + tfa_utils::delete_totp_secret_from_redis(&state, &user_from_token.user_id).await?; + auth::blacklist::insert_user_in_blacklist(&state, &user_from_token.user_id).await?; auth::cookies::remove_cookie_response() } diff --git a/crates/router/src/utils/user/two_factor_auth.rs b/crates/router/src/utils/user/two_factor_auth.rs index a0915f3ed86..aa0077e00ae 100644 --- a/crates/router/src/utils/user/two_factor_auth.rs +++ b/crates/router/src/utils/user/two_factor_auth.rs @@ -115,3 +115,26 @@ pub async fn insert_recovery_code_in_redis(state: &SessionState, user_id: &str) .await .change_context(UserErrors::InternalServerError) } + +pub async fn delete_totp_from_redis(state: &SessionState, user_id: &str) -> UserResult<()> { + let redis_conn = super::get_redis_connection(state)?; + let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); + redis_conn + .delete_key(&key) + .await + .change_context(UserErrors::InternalServerError) + .map(|_| ()) +} + +pub async fn delete_recovery_code_from_redis( + state: &SessionState, + user_id: &str, +) -> UserResult<()> { + let redis_conn = super::get_redis_connection(state)?; + let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); + redis_conn + .delete_key(&key) + .await + .change_context(UserErrors::InternalServerError) + .map(|_| ()) +}
2024-06-03T10:06:39Z
## Description <!-- Describe your changes in detail --> After this PR, Home API will send the details about the user's 2FA, specifically weather user has completed 2FA setup and number of recovery codes left for him. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #4848 ## 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. Home API ``` curl --location 'http://localhost:8080/user' \ --header 'Authorization: Bearer Login Token' ``` ```json { "merchant_id": "company_name", "name": "name", "email": "email", "verification_days_left": null, "role_id": "org_admin", "org_id": "org_lbZlm2cx4j2LgVo7bUwq", "is_two_factor_auth_setup": true, "recovery_codes_left": 8 } ``` 2. Signout 1. Hit Signout API ``` curl --location --request POST 'http://localhost:8080/user/signout' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer Login Token' ``` 200 OK 2. Signin with the same user again ``` curl --location 'http://localhost:8080/user/v2/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "password": "password" }' ``` ``` { "flow_type": "dashboard_entry", "token": "Login Token", "merchant_id": "company_name", "name": "name", "email": "email", "verification_days_left": null, "user_role": "org_admin" } ``` 3. Take the token from the above response and hit 2FA status API ``` curl --location 'http://localhost:8080/user/2fa' \ --header 'Authorization: Bearer Login Token' ``` ``` { "totp": false, "recovery_code": false } ```
15d6c3e846a77dec6b6a5165d86044a9b9fd52f1
1. Home API ``` curl --location 'http://localhost:8080/user' \ --header 'Authorization: Bearer Login Token' ``` ```json { "merchant_id": "company_name", "name": "name", "email": "email", "verification_days_left": null, "role_id": "org_admin", "org_id": "org_lbZlm2cx4j2LgVo7bUwq", "is_two_factor_auth_setup": true, "recovery_codes_left": 8 } ``` 2. Signout 1. Hit Signout API ``` curl --location --request POST 'http://localhost:8080/user/signout' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer Login Token' ``` 200 OK 2. Signin with the same user again ``` curl --location 'http://localhost:8080/user/v2/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "password": "password" }' ``` ``` { "flow_type": "dashboard_entry", "token": "Login Token", "merchant_id": "company_name", "name": "name", "email": "email", "verification_days_left": null, "user_role": "org_admin" } ``` 3. Take the token from the above response and hit 2FA status API ``` curl --location 'http://localhost:8080/user/2fa' \ --header 'Authorization: Bearer Login Token' ``` ``` { "totp": false, "recovery_code": false } ```
[ "crates/api_models/src/user.rs", "crates/router/src/core/user.rs", "crates/router/src/utils/user/two_factor_auth.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4850
Bug: [REFACTOR] use `const` instead of `String` for `business_status` As of now, we've around `9` distinct values for `process_tracker` and all these values are hard coded as Strings in various places. This makes it harder for us to keep track of the values that exist in the code base. As a measure to tackle this issue, we would have to create a set of `const`s in scheduler crate and use them in places where we've used hardcoded strings now. This will help us keep track of all the values that are used and helps increase readability.
diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs index cd0dbed2c64..135c8e2b055 100644 --- a/crates/diesel_models/src/process_tracker.rs +++ b/crates/diesel_models/src/process_tracker.rs @@ -76,8 +76,6 @@ impl ProcessTrackerNew { 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(), @@ -91,7 +89,7 @@ impl ProcessTrackerNew { .encode_to_value() .change_context(errors::DatabaseError::Others) .attach_printable("Failed to serialize process tracker tracking data")?, - business_status: String::from(BUSINESS_STATUS_PENDING), + business_status: String::from(business_status::PENDING), status: storage_enums::ProcessTrackerStatus::New, event: vec![], created_at: current_time, @@ -227,3 +225,42 @@ mod tests { assert_eq!(enum_format, ProcessTrackerRunner::PaymentsSyncWorkflow); } } + +pub mod business_status { + /// Indicates that an irrecoverable error occurred during the workflow execution. + pub const GLOBAL_FAILURE: &str = "GLOBAL_FAILURE"; + + /// Task successfully completed by consumer. + /// A task that reaches this status should not be retried (rescheduled for execution) later. + pub const COMPLETED_BY_PT: &str = "COMPLETED_BY_PT"; + + /// An error occurred during the workflow execution which prevents further execution and + /// retries. + /// A task that reaches this status should not be retried (rescheduled for execution) later. + pub const FAILURE: &str = "FAILURE"; + + /// The resource associated with the task was removed, due to which further retries can/should + /// not be done. + pub const REVOKED: &str = "Revoked"; + + /// The task was executed for the maximum possible number of times without a successful outcome. + /// A task that reaches this status should not be retried (rescheduled for execution) later. + pub const RETRIES_EXCEEDED: &str = "RETRIES_EXCEEDED"; + + /// The outgoing webhook was successfully delivered in the initial attempt. + /// Further retries of the task are not required. + pub const INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL: &str = "INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL"; + + /// Indicates that an error occurred during the workflow execution. + /// This status is typically set by the workflow error handler. + /// A task that reaches this status should not be retried (rescheduled for execution) later. + pub const GLOBAL_ERROR: &str = "GLOBAL_ERROR"; + + /// The resource associated with the task has been significantly modified since the task was + /// created, due to which further retries of the current task are not required. + /// A task that reaches this status should not be retried (rescheduled for execution) later. + pub const RESOURCE_STATUS_MISMATCH: &str = "RESOURCE_STATUS_MISMATCH"; + + /// Business status set for newly created tasks. + pub const PENDING: &str = "Pending"; +} diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index 7e78a355e5c..167e7a6b6ed 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -4,7 +4,7 @@ use std::{collections::HashMap, str::FromStr, sync::Arc}; use actix_web::{dev::Server, web, Scope}; use api_models::health_check::SchedulerHealthCheckResponse; use common_utils::ext_traits::{OptionExt, StringExt}; -use diesel_models::process_tracker as storage; +use diesel_models::process_tracker::{self as storage, business_status}; use error_stack::ResultExt; use router::{ configs::settings::{CmdLineConf, Settings}, @@ -329,10 +329,13 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner { let status = state .get_db() .as_scheduler() - .finish_process_with_business_status(process, "GLOBAL_FAILURE".to_string()) + .finish_process_with_business_status( + process, + business_status::GLOBAL_FAILURE, + ) .await; if let Err(err) = status { - logger::error!(%err, "Failed while performing database operation: GLOBAL_FAILURE"); + logger::error!(%err, "Failed while performing database operation: {}", business_status::GLOBAL_FAILURE); } } }, diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index 8fe536731d3..ef81e3c190d 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -381,7 +381,9 @@ pub async fn update_api_key_expiry_task( retry_count: Some(0), schedule_time, tracking_data: Some(updated_api_key_expiry_workflow_model), - business_status: Some("Pending".to_string()), + business_status: Some(String::from( + diesel_models::process_tracker::business_status::PENDING, + )), status: Some(storage_enums::ProcessTrackerStatus::New), updated_at: Some(current_time), }; @@ -450,7 +452,7 @@ pub async fn revoke_api_key_expiry_task( let task_ids = vec![task_id]; let updated_process_tracker_data = storage::ProcessTrackerUpdate::StatusUpdate { status: storage_enums::ProcessTrackerStatus::Finish, - business_status: Some("Revoked".to_string()), + business_status: Some(String::from(diesel_models::business_status::REVOKED)), }; store diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 9e20017d57f..f37385b80c6 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1178,7 +1178,7 @@ pub async fn start_tokenize_data_workflow( db.as_scheduler() .finish_process_with_business_status( tokenize_tracker.clone(), - "COMPLETED_BY_PT".to_string(), + diesel_models::process_tracker::business_status::COMPLETED_BY_PT, ) .await?; } @@ -1241,7 +1241,10 @@ pub async fn retry_delete_tokenize( } None => db .as_scheduler() - .finish_process_with_business_status(pt, "RETRIES_EXCEEDED".to_string()) + .finish_process_with_business_status( + pt, + diesel_models::process_tracker::business_status::RETRIES_EXCEEDED, + ) .await .map_err(Into::into), } diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 0d441e95382..164fd1ec784 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -9,6 +9,7 @@ use common_utils::{ ext_traits::{AsyncExt, ValueExt}, types::MinorUnit, }; +use diesel_models::process_tracker::business_status; use error_stack::{report, ResultExt}; use masking::PeekInterface; use router_env::{instrument, tracing}; @@ -1028,7 +1029,7 @@ pub async fn sync_refund_with_gateway_workflow( .as_scheduler() .finish_process_with_business_status( refund_tracker.clone(), - "COMPLETED_BY_PT".to_string(), + business_status::COMPLETED_BY_PT, ) .await? } @@ -1193,7 +1194,7 @@ pub async fn trigger_refund_execute_workflow( db.as_scheduler() .finish_process_with_business_status( refund_tracker.clone(), - "COMPLETED_BY_PT".to_string(), + business_status::COMPLETED_BY_PT, ) .await?; } diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs index 0be4e9272f0..07fe78f51ce 100644 --- a/crates/router/src/core/webhooks/outgoing.rs +++ b/crates/router/src/core/webhooks/outgoing.rs @@ -3,6 +3,7 @@ use api_models::{ webhooks, }; use common_utils::{ext_traits::Encode, request::RequestContent}; +use diesel_models::process_tracker::business_status; use error_stack::{report, ResultExt}; use masking::{ExposeInterface, Mask, PeekInterface, Secret}; use router_env::{ @@ -231,7 +232,7 @@ async fn trigger_webhook_to_merchant( state .store .as_scheduler() - .finish_process_with_business_status(process_tracker, "FAILURE".into()) + .finish_process_with_business_status(process_tracker, business_status::FAILURE) .await .change_context( errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed, @@ -304,7 +305,7 @@ async fn trigger_webhook_to_merchant( state.clone(), &business_profile.merchant_id, process_tracker, - "INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL", + business_status::INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL, ) .await?; } else { @@ -769,7 +770,7 @@ async fn success_response_handler( Some(process_tracker) => state .store .as_scheduler() - .finish_process_with_business_status(process_tracker, business_status.into()) + .finish_process_with_business_status(process_tracker, business_status) .await .change_context( errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 0545191318d..75b830cbb41 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1821,7 +1821,7 @@ impl ProcessTrackerInterface for KafkaStore { async fn finish_process_with_business_status( &self, this: storage::ProcessTracker, - business_status: String, + business_status: &'static str, ) -> CustomResult<(), errors::StorageError> { self.diesel_store .finish_process_with_business_status(this, business_status) diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 79c8b2ed2f0..f5626c267d2 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -40,7 +40,8 @@ pub mod user_role; use std::collections::HashMap; pub use diesel_models::{ - ProcessTracker, ProcessTrackerNew, ProcessTrackerRunner, ProcessTrackerUpdate, + process_tracker::business_status, ProcessTracker, ProcessTrackerNew, ProcessTrackerRunner, + ProcessTrackerUpdate, }; pub use hyperswitch_domain_models::payments::{ payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate}, diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index dff7905a262..c24671be34d 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -1,5 +1,7 @@ use common_utils::{errors::ValidationError, ext_traits::ValueExt}; -use diesel_models::{enums as storage_enums, ApiKeyExpiryTrackingData}; +use diesel_models::{ + enums as storage_enums, process_tracker::business_status, ApiKeyExpiryTrackingData, +}; use router_env::logger; use scheduler::{workflows::ProcessTrackerWorkflow, SchedulerSessionState}; @@ -96,7 +98,7 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow { state .get_db() .as_scheduler() - .finish_process_with_business_status(process, "COMPLETED_BY_PT".to_string()) + .finish_process_with_business_status(process, business_status::COMPLETED_BY_PT) .await? } // If tasks are remaining that has to be scheduled diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs index 9184a78b6b2..7560da210d1 100644 --- a/crates/router/src/workflows/outgoing_webhook_retry.rs +++ b/crates/router/src/workflows/outgoing_webhook_retry.rs @@ -6,6 +6,7 @@ use api_models::{ webhooks::{OutgoingWebhook, OutgoingWebhookContent}, }; use common_utils::ext_traits::{StringExt, ValueExt}; +use diesel_models::process_tracker::business_status; use error_stack::ResultExt; use masking::PeekInterface; use router_env::tracing::{self, instrument}; @@ -197,7 +198,7 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { db.as_scheduler() .finish_process_with_business_status( process.clone(), - "RESOURCE_STATUS_MISMATCH".to_string(), + business_status::RESOURCE_STATUS_MISMATCH, ) .await?; } @@ -309,7 +310,7 @@ pub(crate) async fn retry_webhook_delivery_task( } None => { db.as_scheduler() - .finish_process_with_business_status(process, "RETRIES_EXCEEDED".to_string()) + .finish_process_with_business_status(process, business_status::RETRIES_EXCEEDED) .await } } diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index c34b8ebe73b..666de8c3376 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -1,4 +1,5 @@ use common_utils::ext_traits::{OptionExt, StringExt, ValueExt}; +use diesel_models::process_tracker::business_status; use error_stack::ResultExt; use router_env::logger; use scheduler::{ @@ -89,7 +90,7 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow { state .store .as_scheduler() - .finish_process_with_business_status(process, "COMPLETED_BY_PT".to_string()) + .finish_process_with_business_status(process, business_status::COMPLETED_BY_PT) .await? } _ => { @@ -269,7 +270,7 @@ pub async fn retry_sync_task( } None => { db.as_scheduler() - .finish_process_with_business_status(pt, "RETRIES_EXCEEDED".to_string()) + .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED) .await?; Ok(true) } diff --git a/crates/scheduler/src/consumer.rs b/crates/scheduler/src/consumer.rs index 3e15a7cde0f..b58e8ce60d7 100644 --- a/crates/scheduler/src/consumer.rs +++ b/crates/scheduler/src/consumer.rs @@ -30,7 +30,7 @@ use crate::{ // Valid consumer business statuses pub fn valid_business_statuses() -> Vec<&'static str> { - vec!["Pending"] + vec![storage::business_status::PENDING] } #[instrument(skip_all)] @@ -262,7 +262,7 @@ pub async fn consumer_error_handler( vec![process.id], storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Finish, - business_status: Some("GLOBAL_ERROR".to_string()), + business_status: Some(String::from(storage::business_status::GLOBAL_ERROR)), }, ) .await diff --git a/crates/scheduler/src/consumer/workflows.rs b/crates/scheduler/src/consumer/workflows.rs index bbece87f309..974f1ec4153 100644 --- a/crates/scheduler/src/consumer/workflows.rs +++ b/crates/scheduler/src/consumer/workflows.rs @@ -1,6 +1,7 @@ use async_trait::async_trait; use common_utils::errors::CustomResult; pub use diesel_models::process_tracker as storage; +use diesel_models::process_tracker::business_status; use router_env::logger; use crate::{errors, SchedulerSessionState}; @@ -45,7 +46,10 @@ pub trait ProcessTrackerWorkflows<T>: Send + Sync { let status = app_state .get_db() .as_scheduler() - .finish_process_with_business_status(process, "GLOBAL_FAILURE".to_string()) + .finish_process_with_business_status( + process, + business_status::GLOBAL_FAILURE, + ) .await; if let Err(error) = status { logger::error!(?error, "Failed to update process business status"); diff --git a/crates/scheduler/src/db/process_tracker.rs b/crates/scheduler/src/db/process_tracker.rs index feb201f8b75..c73b53b608c 100644 --- a/crates/scheduler/src/db/process_tracker.rs +++ b/crates/scheduler/src/db/process_tracker.rs @@ -52,7 +52,7 @@ pub trait ProcessTrackerInterface: Send + Sync + 'static { async fn finish_process_with_business_status( &self, this: storage::ProcessTracker, - business_status: String, + business_status: &'static str, ) -> CustomResult<(), errors::StorageError>; async fn find_processes_by_time_status( @@ -166,13 +166,13 @@ impl ProcessTrackerInterface for Store { async fn finish_process_with_business_status( &self, this: storage::ProcessTracker, - business_status: String, + business_status: &'static str, ) -> CustomResult<(), errors::StorageError> { self.update_process( this, storage::ProcessTrackerUpdate::StatusUpdate { status: storage_enums::ProcessTrackerStatus::Finish, - business_status: Some(business_status), + business_status: Some(String::from(business_status)), }, ) .await @@ -284,7 +284,7 @@ impl ProcessTrackerInterface for MockDb { async fn finish_process_with_business_status( &self, _this: storage::ProcessTracker, - _business_status: String, + _business_status: &'static str, ) -> CustomResult<(), errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)?
2024-06-03T09:31:02Z
## Description <!-- Describe your changes in detail --> When below command is executed in sandbox DB, we get a set of "distinct" `business_status`es that is specified for process tracker: ```sql SELECT DISTINCT(business_status) FROM process_tracker; ``` For debugging and fun, execute to learn more about process tracker and its behavior: ```sql SELECT DISTINCT(name, retry_count, business_status, status), created_at FROM process_tracker order by created_at desc LIMIT 10000; ``` The main goal for us here is to keep all the `business_status`es in a single place, confined for ease of access and increased readability. This also helps us keep track of the statuses we use. ### 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 keep a track of the statuses that we use in `process_tracker` ## 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 should not require any testing as the change done is here just a mere replacement of hardcoded string with `const`s. If needed, the changes can be verified by following #3712's instructions. Reproduced below: Perform PSync call from connector like `Checkout`. Payment Status should go to `processing` state. Wait for `process_tracker` to kick in and do a `force_sync` on its own. Wait for the status to get updated. I had webhooks set up (invalid configuration), even that is verified to be working. Command used in DB: ```sql SELECT * FROM process_tracker ORDER BY created_at desc LIMIT 2; ``` ![image](https://github.com/juspay/hyperswitch/assets/69745008/9d2ad8b1-6750-4d1a-ac5a-2493a0348e05) ![image](https://github.com/juspay/hyperswitch/assets/69745008/90d8221c-907a-4c1b-a99a-0936e0cc6225) ![image](https://github.com/juspay/hyperswitch/assets/69745008/75aaaca7-7b71-413a-9bb4-75c4652f5366) ![image](https://github.com/juspay/hyperswitch/assets/69745008/f04231d1-0703-45b4-9db1-ace2b21f8372)
2852a3ba156e3e2bd89d0a116990134268e7bee8
This should not require any testing as the change done is here just a mere replacement of hardcoded string with `const`s. If needed, the changes can be verified by following #3712's instructions. Reproduced below: Perform PSync call from connector like `Checkout`. Payment Status should go to `processing` state. Wait for `process_tracker` to kick in and do a `force_sync` on its own. Wait for the status to get updated. I had webhooks set up (invalid configuration), even that is verified to be working. Command used in DB: ```sql SELECT * FROM process_tracker ORDER BY created_at desc LIMIT 2; ``` ![image](https://github.com/juspay/hyperswitch/assets/69745008/9d2ad8b1-6750-4d1a-ac5a-2493a0348e05) ![image](https://github.com/juspay/hyperswitch/assets/69745008/90d8221c-907a-4c1b-a99a-0936e0cc6225) ![image](https://github.com/juspay/hyperswitch/assets/69745008/75aaaca7-7b71-413a-9bb4-75c4652f5366) ![image](https://github.com/juspay/hyperswitch/assets/69745008/f04231d1-0703-45b4-9db1-ace2b21f8372)
[ "crates/diesel_models/src/process_tracker.rs", "crates/router/src/bin/scheduler.rs", "crates/router/src/core/api_keys.rs", "crates/router/src/core/payment_methods/vault.rs", "crates/router/src/core/refunds.rs", "crates/router/src/core/webhooks/outgoing.rs", "crates/router/src/db/kafka_store.rs", "crat...
juspay/hyperswitch
juspay__hyperswitch-4840
Bug: [FEATURE] [AUTHORIZEDOTNET] Support payment_method_id in recurring mandate payment ### Feature Description Support `payment_method_id` in recurring mandate payment for connector Authorizedotnet. ### Possible Implementation Support `payment_method_id` in recurring mandate payment for connector Authorizedotnet. ### 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/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index b281d0a0a77..15aedad7599 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -1,16 +1,15 @@ use common_utils::{ errors::CustomResult, ext_traits::{Encode, ValueExt}, - id_type, pii, }; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret, StrongSecret}; +use rand::distributions::{Alphanumeric, DistString}; use serde::{Deserialize, Serialize}; use crate::{ connector::utils::{ - self, missing_field_err, CardData, PaymentsSyncRequestData, RefundsRequestData, RouterData, - WalletData, + self, CardData, PaymentsSyncRequestData, RefundsRequestData, RouterData, WalletData, }, core::errors, services, @@ -179,7 +178,7 @@ struct PaymentProfileDetails { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CustomerDetails { - id: id_type::CustomerId, + id: String, } #[derive(Debug, Serialize)] @@ -273,10 +272,7 @@ pub struct AuthorizedotnetZeroMandateRequest { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct Profile { - merchant_customer_id: id_type::CustomerId, - #[serde(skip_serializing_if = "Option::is_none")] - description: Option<String>, - email: Option<pii::Email>, + description: String, payment_profiles: PaymentProfiles, } @@ -318,12 +314,8 @@ impl TryFrom<&types::SetupMandateRouterData> for CreateCustomerProfileRequest { create_customer_profile_request: AuthorizedotnetZeroMandateRequest { merchant_authentication, profile: Profile { - merchant_customer_id: item - .customer_id - .clone() - .ok_or_else(missing_field_err("customer_id"))?, - description: item.description.clone(), - email: item.request.email.clone(), + //The payment ID is included in the description because the connector requires unique description when creating a mandate. + description: item.payment_id.clone(), payment_profiles: PaymentProfiles { customer_type: CustomerType::Individual, payment: PaymentDetails::CreditCard(CreditCardDetails { @@ -393,16 +385,18 @@ impl<F, T> response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, redirection_data: None, - mandate_reference: item.response.customer_profile_id.map(|mandate_id| { - types::MandateReference { - connector_mandate_id: Some(mandate_id), - payment_method_id: item + mandate_reference: item.response.customer_profile_id.map( + |customer_profile_id| types::MandateReference { + connector_mandate_id: item .response .customer_payment_profile_id_list .first() - .cloned(), - } - }), + .map(|payment_profile_id| { + format!("{customer_profile_id}-{payment_profile_id}") + }), + payment_method_id: None, + }, + ), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -635,27 +629,24 @@ impl api_models::payments::ConnectorMandateReferenceId, ), ) -> Result<Self, Self::Error> { + let mandate_id = connector_mandate_id + .connector_mandate_id + .ok_or(errors::ConnectorError::MissingConnectorMandateID)?; Ok(Self { transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, amount: item.amount, currency_code: item.router_data.request.currency, payment: None, - profile: Some(ProfileDetails::CustomerProfileDetails( - CustomerProfileDetails { - customer_profile_id: Secret::from( - connector_mandate_id - .connector_mandate_id - .ok_or(errors::ConnectorError::MissingConnectorMandateID)?, - ), - payment_profile: PaymentProfileDetails { - payment_profile_id: Secret::from( - connector_mandate_id - .payment_method_id - .ok_or(errors::ConnectorError::MissingConnectorMandateID)?, - ), - }, - }, - )), + profile: mandate_id + .split_once('-') + .map(|(customer_profile_id, payment_profile_id)| { + ProfileDetails::CustomerProfileDetails(CustomerProfileDetails { + customer_profile_id: Secret::from(customer_profile_id.to_string()), + payment_profile: PaymentProfileDetails { + payment_profile_id: Secret::from(payment_profile_id.to_string()), + }, + }) + }), order: Order { description: item.router_data.connector_request_reference_id.clone(), }, @@ -709,11 +700,13 @@ impl create_profile: true, })), Some(CustomerDetails { - id: item - .router_data - .customer_id - .clone() - .ok_or_else(missing_field_err("customer_id"))?, + //The payment ID is included in the customer details because the connector requires unique customer information with a length of fewer than 20 characters when creating a mandate. + //If the length exceeds 20 characters, a random alphanumeric string is used instead. + id: if item.router_data.payment_id.len() <= 20 { + item.router_data.payment_id.clone() + } else { + Alphanumeric.sample_string(&mut rand::thread_rng(), 20) + }, }), ) } else { @@ -1087,6 +1080,24 @@ impl<F, T> .and_then(|x| x.secure_acceptance_url.to_owned()); let redirection_data = url.map(|url| services::RedirectForm::from((url, services::Method::Get))); + let mandate_reference = item.response.profile_response.map(|profile_response| { + let payment_profile_id = profile_response + .customer_payment_profile_id_list + .and_then(|customer_payment_profile_id_list| { + customer_payment_profile_id_list.first().cloned() + }); + types::MandateReference { + connector_mandate_id: profile_response.customer_profile_id.and_then( + |customer_profile_id| { + payment_profile_id.map(|payment_profile_id| { + format!("{customer_profile_id}-{payment_profile_id}") + }) + }, + ), + payment_method_id: None, + } + }); + Ok(Self { status, response: match error { @@ -1096,16 +1107,7 @@ impl<F, T> transaction_response.transaction_id.clone(), ), redirection_data, - mandate_reference: item.response.profile_response.map( - |profile_response| types::MandateReference { - connector_mandate_id: profile_response.customer_profile_id, - payment_method_id: profile_response - .customer_payment_profile_id_list - .and_then(|customer_payment_profile_id_list| { - customer_payment_profile_id_list.first().cloned() - }), - }, - ), + mandate_reference, connector_metadata: metadata, network_txn_id: transaction_response .network_trans_id
2024-05-31T12:00:38Z
## Description <!-- Describe your changes in detail --> Support `payment_method_id` in recurring mandate payment for connector Authorizedotnet. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/4840 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Payment Intent Create (Zero): Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_8aib7npeItergz3tpMqm1iqsMXrAdiw8VjVdjiVUWLMUSRWR34DrRDGJPmy2mcMm' \ --data '{ "amount": 0, "currency": "USD", "confirm": false, "customer_id": "tester799" }' ``` Response: ``` { "payment_id": "pay_hduDivSEknVCYLL3ekxX", "merchant_id": "merchant_1717157151", "status": "requires_payment_method", "amount": 0, "net_amount": 0, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "API_KEY_HERE", "created": "2024-06-03T09:25:42.690Z", "currency": "USD", "customer_id": "tester799", "customer": { "id": "tester799", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "tester799", "created_at": 1717406742, "expires": 1717410342, "secret": "epk_6d3c1f24d50e48ebb08373224ef23d5a" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lxWuQ5I3AgeVdF3GLB03", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-03T09:40:42.690Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-06-03T09:25:42.781Z", "charges": null, "frm_metadata": null } ``` - Payment Confirm (Zero): Request: ``` curl --location 'http://localhost:8080/payments/pay_jKXxp9HeQV41lRZW4TsV/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "card_cvc": "123" } }, "customer_acceptance": { "acceptance_type": "offline" } }' ``` Response: ``` { "payment_id": "pay_hduDivSEknVCYLL3ekxX", "merchant_id": "merchant_1717157151", "status": "succeeded", "amount": 0, "net_amount": 0, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_hduDivSEknVCYLL3ekxX_secret_iJjHlRGKZhNU4XJto9AD", "created": "2024-06-03T09:25:42.690Z", "currency": "USD", "customer_id": "tester799", "customer": { "id": "tester799", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lxWuQ5I3AgeVdF3GLB03", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_F6pucFwthqPFPERwAhf8", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-03T09:40:42.690Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_D0ahV0rd04bLhjjYrV2I", "payment_method_status": null, "updated": "2024-06-03T09:28:35.781Z", "charges": null, "frm_metadata": null } ``` - Payment Intent Create (Non-Zero): Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 370, "currency": "USD", "confirm": false, "customer_id": "tester799" }' ``` Response: ``` { "payment_id": "pay_ZBSRCNSVIqDtDcw6IsUz", "merchant_id": "merchant_1717157151", "status": "requires_payment_method", "amount": 370, "net_amount": 370, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_ZBSRCNSVIqDtDcw6IsUz_secret_uZouNfEDWSG1goR8XmeG", "created": "2024-06-03T09:27:07.982Z", "currency": "USD", "customer_id": "tester799", "customer": { "id": "tester799", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "tester799", "created_at": 1717406827, "expires": 1717410427, "secret": "epk_9301e21e18a54abe870465212fee94d2" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lxWuQ5I3AgeVdF3GLB03", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-03T09:42:07.982Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-06-03T09:27:08.012Z", "charges": null, "frm_metadata": null } ``` - Payment Confirm (Non-Zero): Request: ``` curl --location 'http://localhost:8080/payments/pay_ZBSRCNSVIqDtDcw6IsUz/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "card_cvc": "123" } }, "customer_acceptance": { "acceptance_type": "offline" } }' ``` Response: ``` { "payment_id": "pay_ZBSRCNSVIqDtDcw6IsUz", "merchant_id": "merchant_1717157151", "status": "succeeded", "amount": 370, "net_amount": 370, "amount_capturable": 370, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_ZBSRCNSVIqDtDcw6IsUz_secret_uZouNfEDWSG1goR8XmeG", "created": "2024-06-03T09:27:07.982Z", "currency": "USD", "customer_id": "tester799", "customer": { "id": "tester799", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lxWuQ5I3AgeVdF3GLB03", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_F6pucFwthqPFPERwAhf8", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-03T09:42:07.982Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_KOptxkOcyGWIly77GCiQ", "payment_method_status": null, "updated": "2024-06-03T09:29:35.382Z", "charges": null, "frm_metadata": null } ``` - Payments Create - Using payment_method_id: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 400, "currency": "USD", "confirm": true, "customer_id": "tester799", "recurring_details": { "type": "payment_method_id", "data": "pm_D0ahV0rd04bLhjjYrV2I" }, "off_session": true }' ``` Response: ``` { "payment_id": "pay_3Z93A6rW7b2qOUHxED2H", "merchant_id": "merchant_1717157151", "status": "succeeded", "amount": 400, "net_amount": 400, "amount_capturable": 0, "amount_received": 400, "connector": "authorizedotnet", "client_secret": "pay_3Z93A6rW7b2qOUHxED2H_secret_BonNTHUTARbIb2QiWN2o", "created": "2024-06-03T09:32:47.521Z", "currency": "USD", "customer_id": "tester799", "customer": { "id": "tester799", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "tester799", "created_at": 1717407167, "expires": 1717410767, "secret": "epk_bf0885fc144047dcb5dad7a35be92057" }, "manual_retry_allowed": false, "connector_transaction_id": "80019529820", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80019529820", "payment_link": null, "profile_id": "pro_lxWuQ5I3AgeVdF3GLB03", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_F6pucFwthqPFPERwAhf8", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-03T09:47:47.521Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_D0ahV0rd04bLhjjYrV2I", "payment_method_status": "active", "updated": "2024-06-03T09:32:48.396Z", "charges": null, "frm_metadata": null } ```
865007717c5c7e617ca1b447ea5f9bb3d274cac3
- Payment Intent Create (Zero): Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_8aib7npeItergz3tpMqm1iqsMXrAdiw8VjVdjiVUWLMUSRWR34DrRDGJPmy2mcMm' \ --data '{ "amount": 0, "currency": "USD", "confirm": false, "customer_id": "tester799" }' ``` Response: ``` { "payment_id": "pay_hduDivSEknVCYLL3ekxX", "merchant_id": "merchant_1717157151", "status": "requires_payment_method", "amount": 0, "net_amount": 0, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "API_KEY_HERE", "created": "2024-06-03T09:25:42.690Z", "currency": "USD", "customer_id": "tester799", "customer": { "id": "tester799", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "tester799", "created_at": 1717406742, "expires": 1717410342, "secret": "epk_6d3c1f24d50e48ebb08373224ef23d5a" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lxWuQ5I3AgeVdF3GLB03", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-03T09:40:42.690Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-06-03T09:25:42.781Z", "charges": null, "frm_metadata": null } ``` - Payment Confirm (Zero): Request: ``` curl --location 'http://localhost:8080/payments/pay_jKXxp9HeQV41lRZW4TsV/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "card_cvc": "123" } }, "customer_acceptance": { "acceptance_type": "offline" } }' ``` Response: ``` { "payment_id": "pay_hduDivSEknVCYLL3ekxX", "merchant_id": "merchant_1717157151", "status": "succeeded", "amount": 0, "net_amount": 0, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_hduDivSEknVCYLL3ekxX_secret_iJjHlRGKZhNU4XJto9AD", "created": "2024-06-03T09:25:42.690Z", "currency": "USD", "customer_id": "tester799", "customer": { "id": "tester799", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lxWuQ5I3AgeVdF3GLB03", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_F6pucFwthqPFPERwAhf8", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-03T09:40:42.690Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_D0ahV0rd04bLhjjYrV2I", "payment_method_status": null, "updated": "2024-06-03T09:28:35.781Z", "charges": null, "frm_metadata": null } ``` - Payment Intent Create (Non-Zero): Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 370, "currency": "USD", "confirm": false, "customer_id": "tester799" }' ``` Response: ``` { "payment_id": "pay_ZBSRCNSVIqDtDcw6IsUz", "merchant_id": "merchant_1717157151", "status": "requires_payment_method", "amount": 370, "net_amount": 370, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_ZBSRCNSVIqDtDcw6IsUz_secret_uZouNfEDWSG1goR8XmeG", "created": "2024-06-03T09:27:07.982Z", "currency": "USD", "customer_id": "tester799", "customer": { "id": "tester799", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "tester799", "created_at": 1717406827, "expires": 1717410427, "secret": "epk_9301e21e18a54abe870465212fee94d2" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lxWuQ5I3AgeVdF3GLB03", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-03T09:42:07.982Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-06-03T09:27:08.012Z", "charges": null, "frm_metadata": null } ``` - Payment Confirm (Non-Zero): Request: ``` curl --location 'http://localhost:8080/payments/pay_ZBSRCNSVIqDtDcw6IsUz/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "card_cvc": "123" } }, "customer_acceptance": { "acceptance_type": "offline" } }' ``` Response: ``` { "payment_id": "pay_ZBSRCNSVIqDtDcw6IsUz", "merchant_id": "merchant_1717157151", "status": "succeeded", "amount": 370, "net_amount": 370, "amount_capturable": 370, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_ZBSRCNSVIqDtDcw6IsUz_secret_uZouNfEDWSG1goR8XmeG", "created": "2024-06-03T09:27:07.982Z", "currency": "USD", "customer_id": "tester799", "customer": { "id": "tester799", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_lxWuQ5I3AgeVdF3GLB03", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_F6pucFwthqPFPERwAhf8", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-03T09:42:07.982Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_KOptxkOcyGWIly77GCiQ", "payment_method_status": null, "updated": "2024-06-03T09:29:35.382Z", "charges": null, "frm_metadata": null } ``` - Payments Create - Using payment_method_id: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 400, "currency": "USD", "confirm": true, "customer_id": "tester799", "recurring_details": { "type": "payment_method_id", "data": "pm_D0ahV0rd04bLhjjYrV2I" }, "off_session": true }' ``` Response: ``` { "payment_id": "pay_3Z93A6rW7b2qOUHxED2H", "merchant_id": "merchant_1717157151", "status": "succeeded", "amount": 400, "net_amount": 400, "amount_capturable": 0, "amount_received": 400, "connector": "authorizedotnet", "client_secret": "pay_3Z93A6rW7b2qOUHxED2H_secret_BonNTHUTARbIb2QiWN2o", "created": "2024-06-03T09:32:47.521Z", "currency": "USD", "customer_id": "tester799", "customer": { "id": "tester799", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "tester799", "created_at": 1717407167, "expires": 1717410767, "secret": "epk_bf0885fc144047dcb5dad7a35be92057" }, "manual_retry_allowed": false, "connector_transaction_id": "80019529820", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80019529820", "payment_link": null, "profile_id": "pro_lxWuQ5I3AgeVdF3GLB03", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_F6pucFwthqPFPERwAhf8", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-06-03T09:47:47.521Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_D0ahV0rd04bLhjjYrV2I", "payment_method_status": "active", "updated": "2024-06-03T09:32:48.396Z", "charges": null, "frm_metadata": null } ```
[ "crates/router/src/connector/authorizedotnet/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4829
Bug: feat: Add new auth type to allow both SPTs and Login Tokens for 2FA APIs The following APIs are needed in both with Sign In and in the dashboard. - `/2fa/totp/verify` - `/2fa/recovery_code/verify` - `/2fa/recovery_code/generate` Currently these APIs use SPT as auth, which makes them unable to access using Login Tokens. We need a new Auth type which allows us to do this.
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index c7615aa4be4..331c256e8a4 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -18,4 +18,4 @@ pub const MIN_PASSWORD_LENGTH: usize = 8; pub const REDIS_TOTP_PREFIX: &str = "TOTP_"; pub const REDIS_RECOVERY_CODE_PREFIX: &str = "RC_"; pub const REDIS_TOTP_SECRET_PREFIX: &str = "TOTP_SEC_"; -pub const REDIS_TOTP_SECRET_TTL_IN_SECS: i64 = 5 * 60; // 5 minutes +pub const REDIS_TOTP_SECRET_TTL_IN_SECS: i64 = 15 * 60; // 15 minutes diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 69a4cfc8a61..cfc01afb91b 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1237,11 +1237,11 @@ pub async fn create_merchant_account( pub async fn list_merchants_for_user( state: SessionState, - user_from_token: Box<dyn auth::GetUserIdFromAuth>, + user_from_token: auth::UserIdFromAuth, ) -> UserResponse<Vec<user_api::UserMerchantAccount>> { let user_roles = state .store - .list_user_roles_by_user_id(user_from_token.get_user_id().as_str()) + .list_user_roles_by_user_id(user_from_token.user_id.as_str()) .await .change_context(UserErrors::InternalServerError)?; @@ -1697,7 +1697,7 @@ pub async fn reset_totp( pub async fn verify_totp( state: SessionState, - user_token: auth::UserFromSinglePurposeToken, + user_token: auth::UserIdFromAuth, req: user_api::VerifyTotpRequest, ) -> UserResponse<user_api::TokenResponse> { let user_from_db: domain::UserFromStorage = state @@ -1737,7 +1737,7 @@ pub async fn verify_totp( pub async fn update_totp( state: SessionState, - user_token: auth::UserFromSinglePurposeToken, + user_token: auth::UserIdFromAuth, req: user_api::VerifyTotpRequest, ) -> UserResponse<()> { let user_from_db: domain::UserFromStorage = state @@ -1806,7 +1806,7 @@ pub async fn update_totp( pub async fn generate_recovery_codes( state: SessionState, - user_token: auth::UserFromSinglePurposeToken, + user_token: auth::UserIdFromAuth, ) -> UserResponse<user_api::RecoveryCodes> { if !tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await? { return Err(UserErrors::TotpRequired.into()); @@ -1838,7 +1838,7 @@ pub async fn generate_recovery_codes( pub async fn verify_recovery_code( state: SessionState, - user_token: auth::UserFromSinglePurposeToken, + user_token: auth::UserIdFromAuth, req: user_api::VerifyRecoveryCodeRequest, ) -> UserResponse<user_api::TokenResponse> { let user_from_db: domain::UserFromStorage = state diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 5af3a2bef25..457e232ebd1 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1316,7 +1316,7 @@ impl User { // The route is utilized to select an invitation from a list of merchants in an intermediate state .service( web::resource("/merchants_select/list") - .route(web::get().to(list_merchants_for_user_with_spt)), + .route(web::get().to(list_merchants_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))) diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index e5cc7e4e294..5325cbe437b 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -318,24 +318,7 @@ pub async fn list_merchants_for_user(state: web::Data<AppState>, req: HttpReques &req, (), |state, user, _, _| user_core::list_merchants_for_user(state, user), - &auth::DashboardNoPermissionAuth, - api_locking::LockAction::NotApplicable, - )) - .await -} - -pub async fn list_merchants_for_user_with_spt( - state: web::Data<AppState>, - req: HttpRequest, -) -> HttpResponse { - let flow = Flow::UserMerchantAccountList; - Box::pin(api::server_wrap( - flow, - state, - &req, - (), - |state, user, _, _| user_core::list_merchants_for_user(state, user), - &auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvite), + &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::AcceptInvite), api_locking::LockAction::NotApplicable, )) .await @@ -674,7 +657,7 @@ pub async fn totp_verify( &req, json_payload.into_inner(), |state, user, req_body, _| user_core::verify_totp(state, user, req_body), - &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP), + &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP), api_locking::LockAction::NotApplicable, )) .await @@ -692,7 +675,7 @@ pub async fn verify_recovery_code( &req, json_payload.into_inner(), |state, user, req_body, _| user_core::verify_recovery_code(state, user, req_body), - &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP), + &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP), api_locking::LockAction::NotApplicable, )) .await @@ -710,7 +693,7 @@ pub async fn totp_update( &req, json_payload.into_inner(), |state, user, req_body, _| user_core::update_totp(state, user, req_body), - &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP), + &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP), api_locking::LockAction::NotApplicable, )) .await @@ -724,7 +707,7 @@ pub async fn generate_recovery_codes(state: web::Data<AppState>, req: HttpReques &req, (), |state, user, _, _| user_core::generate_recovery_codes(state, user), - &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP), + &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP), api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 28f9ccd1a77..72d0860eed9 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -64,10 +64,15 @@ pub enum AuthenticationType { UserJwt { user_id: String, }, - SinglePurposeJWT { + SinglePurposeJwt { user_id: String, purpose: TokenPurpose, }, + SinglePurposeOrLoginJwt { + user_id: String, + purpose: Option<TokenPurpose>, + role_id: Option<String>, + }, MerchantId { merchant_id: String, }, @@ -107,7 +112,8 @@ impl AuthenticationType { | Self::WebhookAuth { merchant_id } => Some(merchant_id.as_ref()), Self::AdminApiKey | Self::UserJwt { .. } - | Self::SinglePurposeJWT { .. } + | Self::SinglePurposeJwt { .. } + | Self::SinglePurposeOrLoginJwt { .. } | Self::NoAuth => None, } } @@ -189,6 +195,19 @@ pub struct UserFromToken { pub org_id: String, } +pub struct UserIdFromAuth { + pub user_id: String, +} + +#[cfg(feature = "olap")] +#[derive(serde::Serialize, serde::Deserialize)] +pub struct SinglePurposeOrLoginToken { + pub user_id: String, + pub role_id: Option<String>, + pub purpose: Option<TokenPurpose>, + pub exp: u64, +} + pub trait AuthInfo { fn get_merchant_id(&self) -> Option<&str>; } @@ -205,23 +224,6 @@ impl AuthInfo for AuthenticationData { } } -pub trait GetUserIdFromAuth { - fn get_user_id(&self) -> String; -} - -impl GetUserIdFromAuth for UserFromToken { - fn get_user_id(&self) -> String { - self.user_id.clone() - } -} - -#[cfg(feature = "olap")] -impl GetUserIdFromAuth for UserFromSinglePurposeToken { - fn get_user_id(&self) -> String { - self.user_id.clone() - } -} - #[async_trait] pub trait AuthenticateAndFetch<T, A> where @@ -355,7 +357,7 @@ where user_id: payload.user_id.clone(), origin: payload.origin.clone(), }, - AuthenticationType::SinglePurposeJWT { + AuthenticationType::SinglePurposeJwt { user_id: payload.user_id, purpose: payload.purpose, }, @@ -363,9 +365,13 @@ where } } +#[cfg(feature = "olap")] +#[derive(Debug)] +pub struct SinglePurposeOrLoginTokenAuth(pub TokenPurpose); + #[cfg(feature = "olap")] #[async_trait] -impl<A> AuthenticateAndFetch<Box<dyn GetUserIdFromAuth>, A> for SinglePurposeJWTAuth +impl<A> AuthenticateAndFetch<UserIdFromAuth, A> for SinglePurposeOrLoginTokenAuth where A: SessionStateInfo + Sync, { @@ -373,26 +379,35 @@ where &self, request_headers: &HeaderMap, state: &A, - ) -> RouterResult<(Box<dyn GetUserIdFromAuth>, AuthenticationType)> { - let payload = parse_jwt_payload::<A, SinglePurposeToken>(request_headers, state).await?; + ) -> RouterResult<(UserIdFromAuth, AuthenticationType)> { + let payload = + parse_jwt_payload::<A, SinglePurposeOrLoginToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - if self.0 != payload.purpose { - return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); - } + let is_purpose_equal = payload + .purpose + .as_ref() + .is_some_and(|purpose| purpose == &self.0); - Ok(( - Box::new(UserFromSinglePurposeToken { - user_id: payload.user_id.clone(), - origin: payload.origin.clone(), - }), - AuthenticationType::SinglePurposeJWT { - user_id: payload.user_id, - purpose: payload.purpose, - }, - )) + let purpose_exists = payload.purpose.is_some(); + let role_id_exists = payload.role_id.is_some(); + + if is_purpose_equal && !role_id_exists || role_id_exists && !purpose_exists { + Ok(( + UserIdFromAuth { + user_id: payload.user_id.clone(), + }, + AuthenticationType::SinglePurposeOrLoginJwt { + user_id: payload.user_id, + purpose: payload.purpose, + role_id: payload.role_id, + }, + )) + } else { + Err(errors::ApiErrorResponse::InvalidJwtToken.into()) + } } } @@ -864,37 +879,6 @@ where } } -#[cfg(feature = "olap")] -#[async_trait] -impl<A> AuthenticateAndFetch<Box<dyn GetUserIdFromAuth>, A> for DashboardNoPermissionAuth -where - A: SessionStateInfo + Sync, -{ - async fn authenticate_and_fetch( - &self, - request_headers: &HeaderMap, - state: &A, - ) -> RouterResult<(Box<dyn GetUserIdFromAuth>, AuthenticationType)> { - let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; - if payload.check_in_blacklist(state).await? { - return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); - } - - Ok(( - Box::new(UserFromToken { - user_id: payload.user_id.clone(), - merchant_id: payload.merchant_id.clone(), - org_id: payload.org_id, - role_id: payload.role_id, - }), - AuthenticationType::MerchantJwt { - merchant_id: payload.merchant_id, - user_id: Some(payload.user_id), - }, - )) - } -} - #[cfg(feature = "olap")] #[async_trait] impl<A> AuthenticateAndFetch<(), A> for DashboardNoPermissionAuth diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs index 8a3aefd8fc0..0ac8c419ef6 100644 --- a/crates/router/src/services/authentication/blacklist.rs +++ b/crates/router/src/services/authentication/blacklist.rs @@ -7,7 +7,7 @@ use redis_interface::RedisConnectionPool; use super::AuthToken; #[cfg(feature = "olap")] -use super::SinglePurposeToken; +use super::{SinglePurposeOrLoginToken, SinglePurposeToken}; #[cfg(feature = "email")] use crate::consts::{EMAIL_TOKEN_BLACKLIST_PREFIX, EMAIL_TOKEN_TIME_IN_SECS}; use crate::{ @@ -166,3 +166,14 @@ impl BlackList for SinglePurposeToken { check_user_in_blacklist(state, &self.user_id, self.exp).await } } + +#[cfg(feature = "olap")] +#[async_trait::async_trait] +impl BlackList for SinglePurposeOrLoginToken { + async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool> + where + A: SessionStateInfo + Sync, + { + check_user_in_blacklist(state, &self.user_id, self.exp).await + } +}
2024-05-30T14:55:01Z
## Description <!-- Describe your changes in detail --> This PR adds new auth type `SinglePurposeOrLoginTokenAuth`, which will allow both SPTs and Login Tokens to be used as auth token for APIs. ### 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 #4829. ## 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. Verify TOTP ``` curl --location 'http://localhost:8080/user/2fa/totp/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer SPT with purpose as TOTP' \ --data '{ "totp": "597760" }' ``` ``` curl --location 'http://localhost:8080/user/2fa/totp/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer Login Token' \ --data '{ "totp": "597760" }' ``` In both the cases this API should give 200 OK. 2. Verify Recovery Code ``` curl --location 'http://localhost:8080/user/2fa/recovery_code/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer SPT with purpose as TOTP' \ --data '{ "recovery_code": "recovery_code" }' ``` ``` curl --location 'http://localhost:8080/user/2fa/recovery_code/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer Login Token' \ --data '{ "recovery_code": "recovery_code" }' ``` In both the cases this API should give 200 OK. 3. Generate Recovery Codes ``` curl --location 'http://localhost:8080/user/2fa/recovery_code/generate' \ --header 'Authorization: Bearer SPT with purpose as TOTP' \ ``` ``` curl --location 'http://localhost:8080/user/2fa/recovery_code/generate' \ --header 'Authorization: Bearer Login Token' \ ``` In both the cases, API should respond like this ``` { "recovery_codes": [ "w5fM-NLm0", "TumH-oyXE", "wDIr-zEmu", "HZjm-e16M", "Q4qB-MupL", "5BtN-vRuY", "4vG6-URGf", "Dbq8-n5V1" ] } ``` 4. Merchant select List ``` curl --location 'http://localhost:8080/user/merchants_select/list' \ --header 'Authorization: Bearer SPT with Purpose as AcceptInvite' ``` ``` curl --location 'http://localhost:8080/user/merchants_select/list' \ --header 'Authorization: Bearer Login Token' ``` In both the cases, API should respond like this ``` [ { "merchant_id": "merchant_1681110944832", "merchant_name": "sdjkfl", "is_active": true, "role_id": "merchant_admin", "role_name": "admin", "org_id": "org_LoNX0cc4lNZVgJrPV65QY" }, { "merchant_id": "merchant_1704717001", "merchant_name": null, "is_active": true, "role_id": "merchant_customer_support", "role_name": "customer_support", "org_id": "org_7yULICVqnwmSX5PgW5zK" } ] ``` 5. Switch List ``` curl --location 'http://localhost:8080/user/switch/list' \ --header 'Authorization: Bearer SPT with Purpose as AcceptInvite' ``` ``` curl --location 'http://localhost:8080/user/switch/list' \ --header 'Authorization: Bearer Login Token' ``` In both the cases, API should respond like this ``` [ { "merchant_id": "merchant_1681110944832", "merchant_name": "sdjkfl", "is_active": true, "role_id": "merchant_admin", "role_name": "admin", "org_id": "org_LoNX0cc4lNZVgJrPV65QY" }, { "merchant_id": "merchant_1704717001", "merchant_name": null, "is_active": true, "role_id": "merchant_customer_support", "role_name": "customer_support", "org_id": "org_7yULICVqnwmSX5PgW5zK" } ] ```
ba0a1e95b72c0acf5bde81d424aa8fe220c40a22
1. Verify TOTP ``` curl --location 'http://localhost:8080/user/2fa/totp/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer SPT with purpose as TOTP' \ --data '{ "totp": "597760" }' ``` ``` curl --location 'http://localhost:8080/user/2fa/totp/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer Login Token' \ --data '{ "totp": "597760" }' ``` In both the cases this API should give 200 OK. 2. Verify Recovery Code ``` curl --location 'http://localhost:8080/user/2fa/recovery_code/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer SPT with purpose as TOTP' \ --data '{ "recovery_code": "recovery_code" }' ``` ``` curl --location 'http://localhost:8080/user/2fa/recovery_code/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer Login Token' \ --data '{ "recovery_code": "recovery_code" }' ``` In both the cases this API should give 200 OK. 3. Generate Recovery Codes ``` curl --location 'http://localhost:8080/user/2fa/recovery_code/generate' \ --header 'Authorization: Bearer SPT with purpose as TOTP' \ ``` ``` curl --location 'http://localhost:8080/user/2fa/recovery_code/generate' \ --header 'Authorization: Bearer Login Token' \ ``` In both the cases, API should respond like this ``` { "recovery_codes": [ "w5fM-NLm0", "TumH-oyXE", "wDIr-zEmu", "HZjm-e16M", "Q4qB-MupL", "5BtN-vRuY", "4vG6-URGf", "Dbq8-n5V1" ] } ``` 4. Merchant select List ``` curl --location 'http://localhost:8080/user/merchants_select/list' \ --header 'Authorization: Bearer SPT with Purpose as AcceptInvite' ``` ``` curl --location 'http://localhost:8080/user/merchants_select/list' \ --header 'Authorization: Bearer Login Token' ``` In both the cases, API should respond like this ``` [ { "merchant_id": "merchant_1681110944832", "merchant_name": "sdjkfl", "is_active": true, "role_id": "merchant_admin", "role_name": "admin", "org_id": "org_LoNX0cc4lNZVgJrPV65QY" }, { "merchant_id": "merchant_1704717001", "merchant_name": null, "is_active": true, "role_id": "merchant_customer_support", "role_name": "customer_support", "org_id": "org_7yULICVqnwmSX5PgW5zK" } ] ``` 5. Switch List ``` curl --location 'http://localhost:8080/user/switch/list' \ --header 'Authorization: Bearer SPT with Purpose as AcceptInvite' ``` ``` curl --location 'http://localhost:8080/user/switch/list' \ --header 'Authorization: Bearer Login Token' ``` In both the cases, API should respond like this ``` [ { "merchant_id": "merchant_1681110944832", "merchant_name": "sdjkfl", "is_active": true, "role_id": "merchant_admin", "role_name": "admin", "org_id": "org_LoNX0cc4lNZVgJrPV65QY" }, { "merchant_id": "merchant_1704717001", "merchant_name": null, "is_active": true, "role_id": "merchant_customer_support", "role_name": "customer_support", "org_id": "org_7yULICVqnwmSX5PgW5zK" } ] ```
[ "crates/router/src/consts/user.rs", "crates/router/src/core/user.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/user.rs", "crates/router/src/services/authentication.rs", "crates/router/src/services/authentication/blacklist.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4834
Bug: [BUG] 5xx during External Authentication through Netcetera Fails ### Bug Description In some very rare scenarios, when external authentication fails from netcetera, hyperswitch throws 5xx because of error message deserialization error. The error object returned by netcetera is inconsistent with their official documentation. Few fields that were marked as required were missing in the actual response. This caused deserialization failure. ### Expected Behavior Hyperswitch should be retuning appropriate error message instead of throwing 5xx. ### Actual Behavior Hyperswitch throws 5xx. ### 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 by enabling external authentication. 2. Confirm the payment 3. Do auth call. 4. Check if 5xx is thrown. ### 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/netcetera.rs b/crates/router/src/connector/netcetera.rs index 43df87db40f..714873cfb53 100644 --- a/crates/router/src/connector/netcetera.rs +++ b/crates/router/src/connector/netcetera.rs @@ -107,7 +107,7 @@ impl ConnectorCommon for Netcetera { status_code: res.status_code, code: response.error_details.error_code, message: response.error_details.error_description, - reason: Some(response.error_details.error_detail), + reason: response.error_details.error_detail, attempt_status: None, connector_transaction_id: None, }) diff --git a/crates/router/src/connector/netcetera/transformers.rs b/crates/router/src/connector/netcetera/transformers.rs index 25ed7c5271e..9218c2eaf1e 100644 --- a/crates/router/src/connector/netcetera/transformers.rs +++ b/crates/router/src/connector/netcetera/transformers.rs @@ -105,8 +105,8 @@ impl NetceteraPreAuthenticationResponse::Failure(error_response) => { Err(types::ErrorResponse { code: error_response.error_details.error_code, - message: error_response.error_details.error_detail, - reason: Some(error_response.error_details.error_description), + message: error_response.error_details.error_description, + reason: error_response.error_details.error_detail, status_code: item.http_code, attempt_status: None, connector_transaction_id: None, @@ -173,8 +173,8 @@ impl } NetceteraAuthenticationResponse::Error(error_response) => Err(types::ErrorResponse { code: error_response.error_details.error_code, - message: error_response.error_details.error_detail, - reason: Some(error_response.error_details.error_description), + message: error_response.error_details.error_description, + reason: error_response.error_details.error_detail, status_code: item.http_code, attempt_status: None, connector_transaction_id: None, @@ -234,20 +234,20 @@ pub struct NetceteraErrorDetails { pub error_code: String, /// Code indicating the 3-D Secure component that identified the error. - pub error_component: String, + pub error_component: Option<String>, /// Text describing the problem identified. pub error_description: String, /// Additional detail regarding the problem identified. - pub error_detail: String, + pub error_detail: Option<String>, /// Universally unique identifier for the transaction assigned by the 3DS SDK. #[serde(rename = "sdkTransID")] pub sdk_trans_id: Option<String>, /// The Message Type that was identified as erroneous. - pub error_message_type: String, + pub error_message_type: Option<String>, } #[derive(Debug, Serialize, Deserialize)]
2024-05-30T13:18:32Z
## Description <!-- Describe your changes in detail --> Few fields in netcetera error object that were marked required in the official api documentation were missing in api response body. This caused deserialization failure at hyperswitch. So made those fields optional. ### 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. Tested sanity of Netcetera Authentication Connector.
21a3a2ea8ada838c67b0e5871f01d09bd5a8b9ed
Manual. Tested sanity of Netcetera Authentication Connector.
[ "crates/router/src/connector/netcetera.rs", "crates/router/src/connector/netcetera/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4820
Bug: feat(users): add endpoint to reset totp Add support to reset TOTP from dashboard!
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 7b6e8ebd365..9931d450ab9 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1634,7 +1634,39 @@ pub async fn begin_totp( let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), None)?; let secret = totp.get_secret_base32().into(); + tfa_utils::insert_totp_secret_in_redis(&state, &user_token.user_id, &secret).await?; + + Ok(ApplicationResponse::Json(user_api::BeginTotpResponse { + secret: Some(user_api::TotpSecret { + secret, + totp_url: totp.get_url().into(), + }), + })) +} + +pub async fn reset_totp( + state: AppState, + user_token: auth::UserFromToken, +) -> UserResponse<user_api::BeginTotpResponse> { + let user_from_db: domain::UserFromStorage = state + .store + .find_user_by_id(&user_token.user_id) + .await + .change_context(UserErrors::InternalServerError)? + .into(); + + if user_from_db.get_totp_status() != TotpStatus::Set { + return Err(UserErrors::TotpNotSetup.into()); + } + if !tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await? + && !tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id).await? + { + return Err(UserErrors::TwoFactorAuthRequired.into()); + } + + let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), None)?; + let secret = totp.get_secret_base32().into(); tfa_utils::insert_totp_secret_in_redis(&state, &user_token.user_id, &secret).await?; Ok(ApplicationResponse::Json(user_api::BeginTotpResponse { diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index b38479cd2b6..6d790d81873 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1217,6 +1217,7 @@ impl User { .service( web::scope("/totp") .service(web::resource("/begin").route(web::get().to(totp_begin))) + .service(web::resource("/reset").route(web::get().to(totp_reset))) .service( web::resource("/verify") .route(web::post().to(totp_verify)) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 9e53eb35473..ee466a7e09a 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -214,6 +214,7 @@ impl From<Flow> for ApiIdentifier { | Flow::VerifyEmailRequest | Flow::UpdateUserAccountDetails | Flow::TotpBegin + | Flow::TotpReset | Flow::TotpVerify | Flow::TotpUpdate | Flow::RecoveryCodeVerify diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 5ba7ec8da25..6b73ea03b62 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -648,6 +648,20 @@ pub async fn totp_begin(state: web::Data<AppState>, req: HttpRequest) -> HttpRes .await } +pub async fn totp_reset(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { + let flow = Flow::TotpReset; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + (), + |state, user, _, _| user_core::reset_totp(state, user), + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn totp_verify( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 1bfc20ff1ca..ddbc64e81f8 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -404,6 +404,8 @@ pub enum Flow { UserFromEmail, /// Begin TOTP TotpBegin, + // Reset TOTP + TotpReset, /// Verify TOTP TotpVerify, /// Update TOTP secret
2024-05-30T08:43:41Z
## Description Add support to reset TOTP ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes [#4820](https://github.com/juspay/hyperswitch/issues/4820) ## How did you test it? Use the curl to reset TOTP when it is already setup (from inside dashboard): ``` curl --location 'http://localhost:8080/user/2fa/totp/reset' \ --header 'Authorization: Bearer JWT' \ --header 'Cookie: Cookie_1=value' ``` Response: ``` { "secret": { "secret": "VERUDBNHLYZDGFTKNXY2VVP4EQ5GOBUB", "totp_url": "otpauth://totp/Hyperswitch:ver%40gmail.com?secret=VERUDBNHLYZDGFTKNXY2VVP4EQ5GOBUB&issuer=Hyperswitch" } } ``` The Response can be used to generate new QR and reset TOTP.
bed42ce4be901f2b8f46033dd395dee8dbe807c9
Use the curl to reset TOTP when it is already setup (from inside dashboard): ``` curl --location 'http://localhost:8080/user/2fa/totp/reset' \ --header 'Authorization: Bearer JWT' \ --header 'Cookie: Cookie_1=value' ``` Response: ``` { "secret": { "secret": "VERUDBNHLYZDGFTKNXY2VVP4EQ5GOBUB", "totp_url": "otpauth://totp/Hyperswitch:ver%40gmail.com?secret=VERUDBNHLYZDGFTKNXY2VVP4EQ5GOBUB&issuer=Hyperswitch" } } ``` The Response can be used to generate new QR and reset TOTP.
[ "crates/router/src/core/user.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/user.rs", "crates/router_env/src/logger/types.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4883
Bug: [FEATURE] Add Moka Cache instead of Static Cache for 3DS Decision Manager and Surcharge Configs ### Feature Description Add Moka Cache instead of Static Cache for 3DS Decision Manager and Surcharge Configs ### Possible Implementation Add Moka Cache instead of Static Cache for 3DS Decision Manager and Surcharge Configs ### 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/euclid/src/backend/vir_interpreter.rs b/crates/euclid/src/backend/vir_interpreter.rs index b7be62cf674..b8d14e228aa 100644 --- a/crates/euclid/src/backend/vir_interpreter.rs +++ b/crates/euclid/src/backend/vir_interpreter.rs @@ -1,5 +1,9 @@ pub mod types; +use std::fmt::Debug; + +use serde::{Deserialize, Serialize}; + use crate::{ backend::{self, inputs, EuclidBackend}, frontend::{ @@ -9,6 +13,7 @@ use crate::{ }, }; +#[derive(Serialize, Deserialize, Debug, Clone)] pub struct VirInterpreterBackend<O> { program: vir::ValuedProgram<O>, } diff --git a/crates/euclid/src/frontend/vir.rs b/crates/euclid/src/frontend/vir.rs index 750ff4e61ff..6c8bc7ab2f1 100644 --- a/crates/euclid/src/frontend/vir.rs +++ b/crates/euclid/src/frontend/vir.rs @@ -1,13 +1,15 @@ //! Valued Intermediate Representation +use serde::{Deserialize, Serialize}; + use crate::types::{EuclidValue, Metadata}; -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub enum ValuedComparisonLogic { NegativeConjunction, PositiveDisjunction, } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Serialize, Deserialize)] pub struct ValuedComparison { pub values: Vec<EuclidValue>, pub logic: ValuedComparisonLogic, @@ -16,20 +18,20 @@ pub struct ValuedComparison { pub type ValuedIfCondition = Vec<ValuedComparison>; -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Serialize, Deserialize)] pub struct ValuedIfStatement { pub condition: ValuedIfCondition, pub nested: Option<Vec<ValuedIfStatement>>, } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Serialize, Deserialize)] pub struct ValuedRule<O> { pub name: String, pub connector_selection: O, pub statements: Vec<ValuedIfStatement>, } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Serialize, Deserialize)] pub struct ValuedProgram<O> { pub default_selection: O, pub rules: Vec<ValuedRule<O>>, diff --git a/crates/euclid/src/types.rs b/crates/euclid/src/types.rs index 904525d54b7..05d3fe6bb8e 100644 --- a/crates/euclid/src/types.rs +++ b/crates/euclid/src/types.rs @@ -1,7 +1,7 @@ pub mod transformers; use euclid_macros::EnumNums; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use strum::VariantNames; use crate::{ @@ -143,7 +143,7 @@ impl EuclidKey { enums::collect_variants!(EuclidKey); -#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum NumValueRefinement { NotEqual, @@ -178,18 +178,18 @@ impl From<NumValueRefinement> for ast::ComparisonType { } } -#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize)] +#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct StrValue { pub value: String, } -#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize)] +#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct MetadataValue { pub key: String, pub value: String, } -#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize)] +#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct NumValue { pub number: i64, pub refinement: Option<NumValueRefinement>, @@ -234,7 +234,7 @@ impl NumValue { } } -#[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum EuclidValue { PaymentMethod(enums::PaymentMethod), CardBin(StrValue), diff --git a/crates/router/src/core/conditional_config.rs b/crates/router/src/core/conditional_config.rs index a8bc8a797dc..f740c6dfcc2 100644 --- a/crates/router/src/core/conditional_config.rs +++ b/crates/router/src/core/conditional_config.rs @@ -6,6 +6,7 @@ use common_utils::ext_traits::{Encode, StringExt, ValueExt}; use diesel_models::configs; use error_stack::ResultExt; use euclid::frontend::ast; +use storage_impl::redis::cache; use super::routing::helpers::{ get_payment_config_routing_id, update_merchant_active_algorithm_ref, @@ -99,8 +100,9 @@ pub async fn upsert_conditional_config( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error serializing the config")?; - algo_id.update_conditional_config_id(key); - update_merchant_active_algorithm_ref(db, &key_store, algo_id) + algo_id.update_conditional_config_id(key.clone()); + let config_key = cache::CacheKind::DecisionManager(key.into()); + update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; @@ -134,8 +136,9 @@ pub async fn upsert_conditional_config( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error fetching the config")?; - algo_id.update_conditional_config_id(key); - update_merchant_active_algorithm_ref(db, &key_store, algo_id) + algo_id.update_conditional_config_id(key.clone()); + let config_key = cache::CacheKind::DecisionManager(key.into()); + update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; @@ -164,7 +167,8 @@ pub async fn delete_conditional_config( .attach_printable("Could not decode the conditional_config algorithm")? .unwrap_or_default(); algo_id.config_algo_id = None; - update_merchant_active_algorithm_ref(db, &key_store, algo_id) + let config_key = cache::CacheKind::DecisionManager(key.clone().into()); + update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update deleted algorithm ref")?; diff --git a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs index 14beb6be131..d708019fe14 100644 --- a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs +++ b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs @@ -1,21 +1,21 @@ -use std::sync::Arc; - use api_models::{ payment_methods::SurchargeDetailsResponse, payments, routing, surcharge_decision_configs::{self, SurchargeDecisionConfigs, SurchargeDecisionManagerRecord}, }; -use common_utils::{ext_traits::StringExt, static_cache::StaticCache, types as common_utils_types}; +use common_utils::{ext_traits::StringExt, types as common_utils_types}; use error_stack::{self, ResultExt}; use euclid::{ backend, backend::{inputs as dsl_inputs, EuclidBackend}, }; use router_env::{instrument, tracing}; +use serde::{Deserialize, Serialize}; +use storage_impl::redis::cache::{self, SURCHARGE_CACHE}; use crate::{ core::{ - errors::ConditionalConfigError as ConfigError, + errors::{self, ConditionalConfigError as ConfigError}, payments::{ conditional_configs::ConditionalConfigResult, routing::make_dsl_input_for_surcharge, types, PaymentData, @@ -29,9 +29,8 @@ use crate::{ SessionState, }; -static CONF_CACHE: StaticCache<VirInterpreterBackendCacheWrapper> = StaticCache::new(); - -struct VirInterpreterBackendCacheWrapper { +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct VirInterpreterBackendCacheWrapper { cached_algorithm: backend::VirInterpreterBackend<SurchargeDecisionConfigs>, merchant_surcharge_configs: surcharge_decision_configs::MerchantSurchargeConfigs, } @@ -53,7 +52,7 @@ impl TryFrom<SurchargeDecisionManagerRecord> for VirInterpreterBackendCacheWrapp enum SurchargeSource { /// Surcharge will be generated through the surcharge rules - Generate(Arc<VirInterpreterBackendCacheWrapper>), + Generate(VirInterpreterBackendCacheWrapper), /// Surcharge is predefined by the merchant through payment create request Predetermined(payments::RequestSurchargeDetails), } @@ -116,19 +115,13 @@ pub async fn perform_surcharge_decision_management_for_payment_method_list( surcharge_decision_configs::MerchantSurchargeConfigs::default(), ), (None, Some(algorithm_id)) => { - let key = ensure_algorithm_cached( + let cached_algo = ensure_algorithm_cached( &*state.store, &payment_attempt.merchant_id, - algorithm_ref.timestamp, algorithm_id.as_str(), ) .await?; - let cached_algo = CONF_CACHE - .retrieve(&key) - .change_context(ConfigError::CacheMiss) - .attach_printable( - "Unable to retrieve cached routing algorithm even after refresh", - )?; + let merchant_surcharge_config = cached_algo.merchant_surcharge_configs.clone(); ( SurchargeSource::Generate(cached_algo), @@ -233,19 +226,13 @@ where SurchargeSource::Predetermined(request_surcharge_details) } (None, Some(algorithm_id)) => { - let key = ensure_algorithm_cached( + let cached_algo = ensure_algorithm_cached( &*state.store, &payment_data.payment_attempt.merchant_id, - algorithm_ref.timestamp, algorithm_id.as_str(), ) .await?; - let cached_algo = CONF_CACHE - .retrieve(&key) - .change_context(ConfigError::CacheMiss) - .attach_printable( - "Unable to retrieve cached routing algorithm even after refresh", - )?; + SurchargeSource::Generate(cached_algo) } (None, None) => return Ok(surcharge_metadata), @@ -291,19 +278,13 @@ pub async fn perform_surcharge_decision_management_for_saved_cards( SurchargeSource::Predetermined(request_surcharge_details) } (None, Some(algorithm_id)) => { - let key = ensure_algorithm_cached( + let cached_algo = ensure_algorithm_cached( &*state.store, &payment_attempt.merchant_id, - algorithm_ref.timestamp, algorithm_id.as_str(), ) .await?; - let cached_algo = CONF_CACHE - .retrieve(&key) - .change_context(ConfigError::CacheMiss) - .attach_printable( - "Unable to retrieve cached routing algorithm even after refresh", - )?; + SurchargeSource::Generate(cached_algo) } (None, None) => return Ok(surcharge_metadata), @@ -388,48 +369,31 @@ fn get_surcharge_details_from_surcharge_output( pub async fn ensure_algorithm_cached( store: &dyn StorageInterface, merchant_id: &str, - timestamp: i64, algorithm_id: &str, -) -> ConditionalConfigResult<String> { +) -> ConditionalConfigResult<VirInterpreterBackendCacheWrapper> { let key = format!("surcharge_dsl_{merchant_id}"); - let present = CONF_CACHE - .present(&key) - .change_context(ConfigError::DslCachePoisoned) - .attach_printable("Error checking presence of DSL")?; - let expired = CONF_CACHE - .expired(&key, timestamp) - .change_context(ConfigError::DslCachePoisoned) - .attach_printable("Error checking presence of DSL")?; - if !present || expired { - refresh_surcharge_algorithm_cache(store, key.clone(), algorithm_id, timestamp).await? - } - Ok(key) -} - -#[instrument(skip_all)] -pub async fn refresh_surcharge_algorithm_cache( - store: &dyn StorageInterface, - key: String, - algorithm_id: &str, - timestamp: i64, -) -> ConditionalConfigResult<()> { - let config = store - .find_config_by_key(algorithm_id) - .await - .change_context(ConfigError::DslMissingInDb) - .attach_printable("Error parsing DSL from config")?; - let record: SurchargeDecisionManagerRecord = config - .config - .parse_struct("Program") - .change_context(ConfigError::DslParsingError) - .attach_printable("Error parsing routing algorithm from configs")?; - let value_to_cache = VirInterpreterBackendCacheWrapper::try_from(record)?; - CONF_CACHE - .save(key, value_to_cache, timestamp) - .change_context(ConfigError::DslCachePoisoned) - .attach_printable("Error saving DSL to cache")?; - Ok(()) + let value_to_cache = || async { + let config: diesel_models::Config = store.find_config_by_key(algorithm_id).await?; + let record: SurchargeDecisionManagerRecord = config + .config + .parse_struct("Program") + .change_context(errors::StorageError::DeserializationFailed) + .attach_printable("Error parsing routing algorithm from configs")?; + VirInterpreterBackendCacheWrapper::try_from(record) + .change_context(errors::StorageError::ValueNotFound("Program".to_string())) + .attach_printable("Error initializing DSL interpreter backend") + }; + let interpreter = cache::get_or_populate_in_memory( + store.get_cache_store().as_ref(), + &key, + value_to_cache, + &SURCHARGE_CACHE, + ) + .await + .change_context(ConfigError::CacheMiss) + .attach_printable("Unable to retrieve cached routing algorithm even after refresh")?; + Ok(interpreter) } pub fn execute_dsl_and_get_conditional_config( diff --git a/crates/router/src/core/payments/conditional_configs.rs b/crates/router/src/core/payments/conditional_configs.rs index c73fa3659b7..7ec9a749152 100644 --- a/crates/router/src/core/payments/conditional_configs.rs +++ b/crates/router/src/core/payments/conditional_configs.rs @@ -4,19 +4,17 @@ use api_models::{ conditional_configs::{ConditionalConfigs, DecisionManagerRecord}, routing, }; -use common_utils::{ext_traits::StringExt, static_cache::StaticCache}; +use common_utils::ext_traits::StringExt; use error_stack::ResultExt; use euclid::backend::{self, inputs as dsl_inputs, EuclidBackend}; use router_env::{instrument, tracing}; +use storage_impl::redis::cache::{self, DECISION_MANAGER_CACHE}; use super::routing::make_dsl_input; use crate::{ core::{errors, errors::ConditionalConfigError as ConfigError, payments}, routes, }; - -static CONF_CACHE: StaticCache<backend::VirInterpreterBackend<ConditionalConfigs>> = - StaticCache::new(); pub type ConditionalConfigResult<O> = errors::CustomResult<O, ConfigError>; #[instrument(skip_all)] @@ -31,76 +29,40 @@ pub async fn perform_decision_management<F: Clone>( } else { return Ok(ConditionalConfigs::default()); }; + let db = &*state.store; + + let key = format!("dsl_{merchant_id}"); + + let find_key_from_db = || async { + let config = db.find_config_by_key(&algorithm_id).await?; + + let rec: DecisionManagerRecord = config + .config + .parse_struct("Program") + .change_context(errors::StorageError::DeserializationFailed) + .attach_printable("Error parsing routing algorithm from configs")?; + + backend::VirInterpreterBackend::with_program(rec.program) + .change_context(errors::StorageError::ValueNotFound("Program".to_string())) + .attach_printable("Error initializing DSL interpreter backend") + }; - let key = ensure_algorithm_cached( - state, - merchant_id, - algorithm_ref.timestamp, - algorithm_id.as_str(), + let interpreter = cache::get_or_populate_in_memory( + db.get_cache_store().as_ref(), + &key, + find_key_from_db, + &DECISION_MANAGER_CACHE, ) - .await?; - let cached_algo = CONF_CACHE - .retrieve(&key) - .change_context(ConfigError::CacheMiss) - .attach_printable("Unable to retrieve cached routing algorithm even after refresh")?; + .await + .change_context(ConfigError::DslCachePoisoned)?; + let backend_input = make_dsl_input(payment_data).change_context(ConfigError::InputConstructionError)?; - let interpreter = cached_algo.as_ref(); - execute_dsl_and_get_conditional_config(backend_input, interpreter).await -} -#[instrument(skip_all)] -pub async fn ensure_algorithm_cached( - state: &routes::SessionState, - merchant_id: &str, - timestamp: i64, - algorithm_id: &str, -) -> ConditionalConfigResult<String> { - let key = format!("dsl_{merchant_id}"); - let present = CONF_CACHE - .present(&key) - .change_context(ConfigError::DslCachePoisoned) - .attach_printable("Error checking presece of DSL")?; - let expired = CONF_CACHE - .expired(&key, timestamp) - .change_context(ConfigError::DslCachePoisoned) - .attach_printable("Error checking presence of DSL")?; - if !present || expired { - refresh_routing_cache(state, key.clone(), algorithm_id, timestamp).await?; - }; - Ok(key) -} - -#[instrument(skip_all)] -pub async fn refresh_routing_cache( - state: &routes::SessionState, - key: String, - algorithm_id: &str, - timestamp: i64, -) -> ConditionalConfigResult<()> { - let config = state - .store - .find_config_by_key(algorithm_id) - .await - .change_context(ConfigError::DslMissingInDb) - .attach_printable("Error parsing DSL from config")?; - let rec: DecisionManagerRecord = config - .config - .parse_struct("Program") - .change_context(ConfigError::DslParsingError) - .attach_printable("Error parsing routing algorithm from configs")?; - let interpreter: backend::VirInterpreterBackend<ConditionalConfigs> = - backend::VirInterpreterBackend::with_program(rec.program) - .change_context(ConfigError::DslBackendInitError) - .attach_printable("Error initializing DSL interpreter backend")?; - CONF_CACHE - .save(key, interpreter, timestamp) - .change_context(ConfigError::DslCachePoisoned) - .attach_printable("Error saving DSL to cache")?; - Ok(()) + execute_dsl_and_get_conditional_config(backend_input, &interpreter) } -pub async fn execute_dsl_and_get_conditional_config( +pub fn execute_dsl_and_get_conditional_config( backend_input: dsl_inputs::BackendInput, interpreter: &backend::VirInterpreterBackend<ConditionalConfigs>, ) -> ConditionalConfigResult<ConditionalConfigs> { diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 145800ebc6a..15eda58c913 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -558,9 +558,9 @@ pub async fn get_merchant_cgraph<'a>( #[cfg(not(feature = "business_profile_routing"))] let key = match transaction_type { - api_enums::TransactionType::Payment => format!("kgraph_{}", merchant_id), + api_enums::TransactionType::Payment => format!("cgraph_{}", merchant_id), #[cfg(feature = "payouts")] - api_enums::TransactionType::Payout => format!("kgraph_po_{}", merchant_id), + api_enums::TransactionType::Payout => format!("cgraph_po_{}", merchant_id), }; let cached_cgraph = CGRAPH_CACHE diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index a64dadaa35d..5314de4d2f8 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -15,6 +15,8 @@ use diesel_models::configs; use diesel_models::routing_algorithm::RoutingAlgorithm; use error_stack::ResultExt; use rustc_hash::FxHashSet; +#[cfg(not(feature = "business_profile_routing"))] +use storage_impl::redis::cache; use super::payments; #[cfg(feature = "payouts")] @@ -232,7 +234,11 @@ pub async fn create_routing_config( if records_are_empty { merchant_dictionary.active_id = Some(algorithm_id.clone()); algorithm_ref.update_algorithm_id(algorithm_id); - helpers::update_merchant_active_algorithm_ref(db, &key_store, algorithm_ref).await?; + let key = + cache::CacheKind::Routing(format!("dsl_{}", &merchant_account.merchant_id).into()); + + helpers::update_merchant_active_algorithm_ref(db, &key_store, key, algorithm_ref) + .await?; } helpers::update_merchant_routing_dictionary( @@ -363,7 +369,9 @@ pub async fn link_routing_config( merchant_dictionary, ) .await?; - helpers::update_merchant_active_algorithm_ref(db, &key_store, routing_ref).await?; + let key = + cache::CacheKind::Routing(format!("dsl_{}", &merchant_account.merchant_id).into()); + helpers::update_merchant_active_algorithm_ref(db, &key_store, key, routing_ref).await?; metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]); Ok(service_api::ApplicationResponse::Json(response)) diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 2e1032e8e4c..c89eb2b8579 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -188,6 +188,7 @@ pub async fn update_routing_algorithm( pub async fn update_merchant_active_algorithm_ref( db: &dyn StorageInterface, key_store: &domain::MerchantKeyStore, + config_key: cache::CacheKind<'_>, algorithm_id: routing_types::RoutingAlgorithmRef, ) -> RouterResult<()> { let ref_value = algorithm_id @@ -226,6 +227,11 @@ pub async fn update_merchant_active_algorithm_ref( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref in merchant account")?; + cache::publish_into_redact_channel(db.get_cache_store().as_ref(), [config_key]) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to invalidate the config cache")?; + Ok(()) } diff --git a/crates/router/src/core/surcharge_decision_config.rs b/crates/router/src/core/surcharge_decision_config.rs index 7f451e6008f..b35d7c5ad28 100644 --- a/crates/router/src/core/surcharge_decision_config.rs +++ b/crates/router/src/core/surcharge_decision_config.rs @@ -9,6 +9,7 @@ use common_utils::ext_traits::{Encode, StringExt, ValueExt}; use diesel_models::configs; use error_stack::ResultExt; use euclid::frontend::ast; +use storage_impl::redis::cache; use super::routing::helpers::{ get_payment_method_surcharge_routing_id, update_merchant_active_algorithm_ref, @@ -88,8 +89,9 @@ pub async fn upsert_surcharge_decision_config( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error serializing the config")?; - algo_id.update_surcharge_config_id(key); - update_merchant_active_algorithm_ref(db, &key_store, algo_id) + algo_id.update_surcharge_config_id(key.clone()); + let config_key = cache::CacheKind::Surcharge(key.into()); + update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; @@ -124,8 +126,9 @@ pub async fn upsert_surcharge_decision_config( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error fetching the config")?; - algo_id.update_surcharge_config_id(key); - update_merchant_active_algorithm_ref(db, &key_store, algo_id) + algo_id.update_surcharge_config_id(key.clone()); + let config_key = cache::CacheKind::Surcharge(key.clone().into()); + update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; @@ -154,7 +157,8 @@ pub async fn delete_surcharge_decision_config( .attach_printable("Could not decode the surcharge conditional_config algorithm")? .unwrap_or_default(); algo_id.surcharge_config_algo_id = None; - update_merchant_active_algorithm_ref(db, &key_store, algo_id) + let config_key = cache::CacheKind::Surcharge(key.clone().into()); + update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update deleted algorithm ref")?; diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index 9b82ef414ce..39d63080a4b 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -514,10 +514,10 @@ async fn publish_and_redact_merchant_account_cache( .map(|publishable_key| CacheKind::Accounts(publishable_key.into())); #[cfg(feature = "business_profile_routing")] - let kgraph_key = merchant_account.default_profile.as_ref().map(|profile_id| { + let cgraph_key = merchant_account.default_profile.as_ref().map(|profile_id| { CacheKind::CGraph( format!( - "kgraph_{}_{}", + "cgraph_{}_{}", merchant_account.merchant_id.clone(), profile_id, ) @@ -526,8 +526,8 @@ async fn publish_and_redact_merchant_account_cache( }); #[cfg(not(feature = "business_profile_routing"))] - let kgraph_key = Some(CacheKind::CGraph( - format!("kgraph_{}", merchant_account.merchant_id.clone()).into(), + let cgraph_key = Some(CacheKind::CGraph( + format!("cgraph_{}", merchant_account.merchant_id.clone()).into(), )); let mut cache_keys = vec![CacheKind::Accounts( @@ -535,7 +535,7 @@ async fn publish_and_redact_merchant_account_cache( )]; cache_keys.extend(publishable_key.into_iter()); - cache_keys.extend(kgraph_key.into_iter()); + cache_keys.extend(cgraph_key.into_iter()); cache::publish_into_redact_channel(store.get_cache_store().as_ref(), cache_keys).await?; Ok(()) diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs index 9d1df7b67eb..e4efab0da33 100644 --- a/crates/storage_impl/src/redis/cache.rs +++ b/crates/storage_impl/src/redis/cache.rs @@ -28,6 +28,12 @@ const ACCOUNTS_CACHE_PREFIX: &str = "accounts"; /// Prefix for routing cache key const ROUTING_CACHE_PREFIX: &str = "routing"; +/// Prefix for three ds decision manager cache key +const DECISION_MANAGER_CACHE_PREFIX: &str = "decision_manager"; + +/// Prefix for surcharge cache key +const SURCHARGE_CACHE_PREFIX: &str = "surcharge"; + /// Prefix for cgraph cache key const CGRAPH_CACHE_PREFIX: &str = "cgraph"; @@ -57,6 +63,14 @@ pub static ACCOUNTS_CACHE: Lazy<Cache> = pub static ROUTING_CACHE: Lazy<Cache> = Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); +/// 3DS Decision Manager Cache +pub static DECISION_MANAGER_CACHE: Lazy<Cache> = + Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); + +/// Surcharge Cache +pub static SURCHARGE_CACHE: Lazy<Cache> = + Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); + /// CGraph Cache pub static CGRAPH_CACHE: Lazy<Cache> = Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); @@ -74,6 +88,8 @@ pub enum CacheKind<'a> { Config(Cow<'a, str>), Accounts(Cow<'a, str>), Routing(Cow<'a, str>), + DecisionManager(Cow<'a, str>), + Surcharge(Cow<'a, str>), CGraph(Cow<'a, str>), PmFiltersCGraph(Cow<'a, str>), All(Cow<'a, str>), @@ -85,6 +101,8 @@ impl<'a> From<CacheKind<'a>> for RedisValue { CacheKind::Config(s) => format!("{CONFIG_CACHE_PREFIX},{s}"), CacheKind::Accounts(s) => format!("{ACCOUNTS_CACHE_PREFIX},{s}"), CacheKind::Routing(s) => format!("{ROUTING_CACHE_PREFIX},{s}"), + CacheKind::DecisionManager(s) => format!("{DECISION_MANAGER_CACHE_PREFIX},{s}"), + CacheKind::Surcharge(s) => format!("{SURCHARGE_CACHE_PREFIX},{s}"), CacheKind::CGraph(s) => format!("{CGRAPH_CACHE_PREFIX},{s}"), CacheKind::PmFiltersCGraph(s) => format!("{PM_FILTERS_CGRAPH_CACHE_PREFIX},{s}"), CacheKind::All(s) => format!("{ALL_CACHE_PREFIX},{s}"), @@ -105,10 +123,15 @@ impl<'a> TryFrom<RedisValue> for CacheKind<'a> { ACCOUNTS_CACHE_PREFIX => Ok(Self::Accounts(Cow::Owned(split.1.to_string()))), CONFIG_CACHE_PREFIX => Ok(Self::Config(Cow::Owned(split.1.to_string()))), ROUTING_CACHE_PREFIX => Ok(Self::Routing(Cow::Owned(split.1.to_string()))), + DECISION_MANAGER_CACHE_PREFIX => { + Ok(Self::DecisionManager(Cow::Owned(split.1.to_string()))) + } + SURCHARGE_CACHE_PREFIX => Ok(Self::Surcharge(Cow::Owned(split.1.to_string()))), CGRAPH_CACHE_PREFIX => Ok(Self::CGraph(Cow::Owned(split.1.to_string()))), PM_FILTERS_CGRAPH_CACHE_PREFIX => { Ok(Self::PmFiltersCGraph(Cow::Owned(split.1.to_string()))) } + ALL_CACHE_PREFIX => Ok(Self::All(Cow::Owned(split.1.to_string()))), _ => Err(validation_err.into()), } diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs index e83546c0f8d..7c4bd93681f 100644 --- a/crates/storage_impl/src/redis/pub_sub.rs +++ b/crates/storage_impl/src/redis/pub_sub.rs @@ -3,8 +3,8 @@ use redis_interface::{errors as redis_errors, PubsubInterface, RedisValue}; use router_env::{logger, tracing::Instrument}; use crate::redis::cache::{ - CacheKey, CacheKind, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE, PM_FILTERS_CGRAPH_CACHE, - ROUTING_CACHE, + CacheKey, CacheKind, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE, DECISION_MANAGER_CACHE, + PM_FILTERS_CGRAPH_CACHE, ROUTING_CACHE, SURCHARGE_CACHE, }; #[async_trait::async_trait] @@ -119,6 +119,24 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> { .await; key } + CacheKind::DecisionManager(key) => { + DECISION_MANAGER_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; + key + } + CacheKind::Surcharge(key) => { + SURCHARGE_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; + key + } CacheKind::All(key) => { CONFIG_CACHE .remove(CacheKey { @@ -150,6 +168,19 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> { prefix: self.key_prefix.clone(), }) .await; + DECISION_MANAGER_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; + SURCHARGE_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: self.key_prefix.clone(), + }) + .await; + key } };
2024-05-29T11:36:14Z
## Description refactor conditional_configs to use Moka Cache instead of Static Cache ### 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 be tested
05105321caceb14f99f0ec0f8ccefd9db9b02bb6
Cannot be tested
[ "crates/euclid/src/backend/vir_interpreter.rs", "crates/euclid/src/frontend/vir.rs", "crates/euclid/src/types.rs", "crates/router/src/core/conditional_config.rs", "crates/router/src/core/payment_methods/surcharge_decision_configs.rs", "crates/router/src/core/payments/conditional_configs.rs", "crates/rou...
juspay/hyperswitch
juspay__hyperswitch-4812
Bug: [CHORE] : [Paypal] Add session_token flow for Paypal sdk and update the wasm ### Feature Description - Change payment_experience for paypal via paypal to sdk - update the wasm ### Possible Implementation - update wasm config for paypal https://github.com/juspay/hyperswitch/pull/4697 ### 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/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs index 94cc06786aa..87d1e3e810b 100644 --- a/crates/connector_configs/src/transformer.rs +++ b/crates/connector_configs/src/transformer.rs @@ -63,6 +63,36 @@ impl DashboardRequestPayload { }, } } + + pub fn transform_paypal_payment_method( + providers: Vec<Provider>, + ) -> Vec<payment_methods::RequestPaymentMethodTypes> { + let payment_experiences = [ + api_models::enums::PaymentExperience::RedirectToUrl, + api_models::enums::PaymentExperience::InvokeSdkClient, + ]; + + let mut payment_method_types = Vec::new(); + + for experience in payment_experiences { + for provider in &providers { + let data = payment_methods::RequestPaymentMethodTypes { + payment_method_type: provider.payment_method_type, + card_networks: None, + minimum_amount: Some(0), + maximum_amount: Some(68607706), + recurring_enabled: true, + installment_payment_enabled: false, + accepted_currencies: provider.accepted_currencies.clone(), + accepted_countries: provider.accepted_countries.clone(), + payment_experience: Some(experience), + }; + payment_method_types.push(data); + } + } + + payment_method_types + } pub fn transform_payment_method( connector: Connector, provider: Vec<Provider>, @@ -125,8 +155,37 @@ impl DashboardRequestPayload { } } - PaymentMethod::Wallet - | PaymentMethod::BankRedirect + PaymentMethod::Wallet => match request.connector { + Connector::Paypal => { + if let Some(provider) = payload.provider { + let val = Self::transform_paypal_payment_method(provider); + if !val.is_empty() { + let methods = PaymentMethodsEnabled { + payment_method: payload.payment_method, + payment_method_types: Some(val), + }; + payment_method_enabled.push(methods); + } + } + } + _ => { + if let Some(provider) = payload.provider { + let val = Self::transform_payment_method( + request.connector, + provider, + payload.payment_method, + ); + if !val.is_empty() { + let methods = PaymentMethodsEnabled { + payment_method: payload.payment_method, + payment_method_types: Some(val), + }; + payment_method_enabled.push(methods); + } + } + } + }, + PaymentMethod::BankRedirect | PaymentMethod::PayLater | PaymentMethod::BankTransfer | PaymentMethod::Crypto diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index c3ee6dfb0ad..138fef0cdf3 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -1650,9 +1650,9 @@ merchant_secret="Source verification key" client_id="Client ID" [paypal_payout] -[[paypal.wallet]] +[[paypal_payout.wallet]] payment_method_type = "paypal" -[[paypal.wallet]] +[[paypal_payout.wallet]] payment_method_type = "venmo" [paypal_payout.connector_auth.BodyKey] api_key="Client Secret" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 86183ae7f6f..7236863745d 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -1650,9 +1650,9 @@ merchant_secret="Source verification key" client_id="Client ID" [paypal_payout] -[[paypal.wallet]] +[[paypal_payout.wallet]] payment_method_type = "paypal" -[[paypal.wallet]] +[[paypal_payout.wallet]] payment_method_type = "venmo" [paypal_payout.connector_auth.BodyKey] api_key="Client Secret"
2024-05-29T11:14:21Z
## Description <!-- Describe your changes in detail --> Allow Paypal Wallet to have both payment_experiences RedirectToUrl and InvokeSdkClient <img width="952" alt="image" src="https://github.com/juspay/hyperswitch/assets/120017870/f7eb2488-bbe2-4e50-bfbd-1d7e3b1dc6ca"> Dashboard Request Payload <img width="1374" alt="image" src="https://github.com/juspay/hyperswitch/assets/120017870/73c30b9f-f8ce-45a2-9252-0781829951d5"> Reference PR https://github.com/juspay/hyperswitch/pull/4697 ### 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)? -->
7888dd48b2f3da7d3f867369331accee624f2b39
[ "crates/connector_configs/src/transformer.rs", "crates/connector_configs/toml/development.toml", "crates/connector_configs/toml/sandbox.toml" ]
juspay/hyperswitch
juspay__hyperswitch-4809
Bug: feat(users): add support to check 2FA status Add support to check whether the 2FA has been done recently or not. ( For now it will check for last five minutes) Use case: The api will help to check for when was last TOTP done, if user has recently done sign in and trying to do some operation that asks for TOTP again from inside dashboard, we can ignore TOTP based on the result this api gives.
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index a472b3a76e6..c41f52a93ea 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -16,8 +16,9 @@ use crate::user::{ GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse, ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, - TokenOrPayloadResponse, TokenResponse, UpdateUserAccountDetailsRequest, UserFromEmailRequest, - UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, + TokenOrPayloadResponse, TokenResponse, TwoFactorAuthStatusResponse, + UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate, VerifyEmailRequest, + VerifyRecoveryCodeRequest, VerifyTotpRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -73,6 +74,7 @@ common_utils::impl_misc_api_event_type!( GetUserRoleDetailsRequest, GetUserRoleDetailsResponse, TokenResponse, + TwoFactorAuthStatusResponse, UserFromEmailRequest, BeginTotpResponse, VerifyRecoveryCodeRequest, diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 0c8678d2ef8..ee9498cfeee 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -235,6 +235,12 @@ pub struct TokenResponse { pub token_type: TokenPurpose, } +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct TwoFactorAuthStatusResponse { + pub totp: bool, + pub recovery_code: bool, +} + #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum TokenOrPayloadResponse<T> { diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 7b6e8ebd365..0da381bd493 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1874,3 +1874,16 @@ pub async fn terminate_two_factor_auth( token, ) } + +pub async fn check_two_factor_auth_status( + state: AppState, + user_token: auth::UserFromToken, +) -> UserResponse<user_api::TwoFactorAuthStatusResponse> { + Ok(ApplicationResponse::Json( + user_api::TwoFactorAuthStatusResponse { + totp: tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await?, + recovery_code: tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id) + .await?, + }, + )) +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index b38479cd2b6..141e9f53af4 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1214,6 +1214,7 @@ impl User { // Two factor auth routes route = route.service( web::scope("/2fa") + .service(web::resource("").route(web::get().to(check_two_factor_auth_status))) .service( web::scope("/totp") .service(web::resource("/begin").route(web::get().to(totp_begin))) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 9e53eb35473..417a4360c51 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -218,7 +218,8 @@ impl From<Flow> for ApiIdentifier { | Flow::TotpUpdate | Flow::RecoveryCodeVerify | Flow::RecoveryCodesGenerate - | Flow::TerminateTwoFactorAuth => Self::User, + | Flow::TerminateTwoFactorAuth + | Flow::TwoFactorAuthStatus => Self::User, Flow::ListRoles | Flow::GetRole diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 5ba7ec8da25..f22e4aac521 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -735,3 +735,20 @@ pub async fn terminate_two_factor_auth( )) .await } + +pub async fn check_two_factor_auth_status( + state: web::Data<AppState>, + req: HttpRequest, +) -> HttpResponse { + let flow = Flow::TwoFactorAuthStatus; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + (), + |state, user, _, _| user_core::check_two_factor_auth_status(state, user), + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 1bfc20ff1ca..728f2ed206e 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -414,6 +414,8 @@ pub enum Flow { RecoveryCodesGenerate, // Terminate two factor authentication TerminateTwoFactorAuth, + // Check 2FA status + TwoFactorAuthStatus, /// List initial webhook delivery attempts WebhookEventInitialDeliveryAttemptList, /// List delivery attempts for a webhook event
2024-05-29T11:10:35Z
## Description The api checks whether the 2FA has been done recently or not. It just checks the status in Redis and gives the response. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes [#4809](https://github.com/juspay/hyperswitch/issues/4809) ## How did you test it? Use the curl to get the status ``` curl --location 'http://localhost:8080/user/2fa' \ --header 'Authorization: Bearer JWT' \ --header 'Cookie: Cookie_1=value' ``` Response will be something like ``` { "totp": true, "recovery_code": false } ```
cd9c9b609c8d5d7c77658d973f7922ae71af9a4d
Use the curl to get the status ``` curl --location 'http://localhost:8080/user/2fa' \ --header 'Authorization: Bearer JWT' \ --header 'Cookie: Cookie_1=value' ``` Response will be something like ``` { "totp": true, "recovery_code": false } ```
[ "crates/api_models/src/events/user.rs", "crates/api_models/src/user.rs", "crates/router/src/core/user.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/user.rs", "crates/router_env/src/logger/types.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4808
Bug: [BUG] Fixing 3DS payment failure in headless mode ### Bug Description 3DS payments were failing in the refund test in Cypress headless mode. I added the timeout and properly configured the hooks to fetch the redirection URL correctly. ### Expected Behavior It should pass in headless mode ### Actual Behavior Its failing in headless mode ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Run the cypress test in headless using the below command CYPRESS_CONNECTOR='connector_name' npm run cypress:ci ### Context For The Bug _No response_ ### Environment In 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!
2024-05-29T10:09:01Z
## Description 3DS payments were failing in the refund test in Cypress headless mode. I added the timeout and properly configured the hooks to fetch the redirection URL correctly. ## Motivation and Context To ensure the test runs successfully without any failures in the CI/CD pipeline. ## How did you test it? Tested locally in the headless mode Stripe <img width="843" alt="Screenshot 2024-05-29 at 1 41 57 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/b5737099-bf5c-4408-b598-77185c257411"> Cybersource <img width="898" alt="Screenshot 2024-05-29 at 2 45 53 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/63c7be7b-9b12-4312-8b55-26aa53fde86d"> NMI <img width="807" alt="Screenshot 2024-05-29 at 3 09 28 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/496d2212-0ceb-4fd8-8584-b507907f2521"> Adyen <img width="852" alt="Screenshot 2024-05-29 at 3 17 36 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/07722a6d-b771-4585-b618-944423c8c15b">
b812e596a1bef4cc154f5b925753ad158c9022de
Tested locally in the headless mode Stripe <img width="843" alt="Screenshot 2024-05-29 at 1 41 57 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/b5737099-bf5c-4408-b598-77185c257411"> Cybersource <img width="898" alt="Screenshot 2024-05-29 at 2 45 53 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/63c7be7b-9b12-4312-8b55-26aa53fde86d"> NMI <img width="807" alt="Screenshot 2024-05-29 at 3 09 28 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/496d2212-0ceb-4fd8-8584-b507907f2521"> Adyen <img width="852" alt="Screenshot 2024-05-29 at 3 17 36 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/07722a6d-b771-4585-b618-944423c8c15b">
[]
juspay/hyperswitch
juspay__hyperswitch-4797
Bug: [Kafka] - Consolidate payment logs into a single topic for sessionizing Consolidate intent, attempt, dispute, refund events into a single topic `hyperswitch-consolidated-events` for sessionizer to consume #### Initial log structure ```json { "log": { "merchant_id": "test", "payment_id": "p1", "attempt_id": "a1", ... } "log_type": "payment_attempt" } ```
diff --git a/config/config.example.toml b/config/config.example.toml index 5433d7a8e46..5d40d0e55ef 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -263,8 +263,7 @@ stripe = { banks = "alior_bank,bank_millennium,bank_nowy_bfg_sa,bank_pekao_sa,ba # This data is used to call respective connectors for wallets and cards [connectors.supported] -wallets = ["klarna", - "mifinity", "braintree", "applepay"] +wallets = ["klarna", "mifinity", "braintree", "applepay"] rewards = ["cashtocode", "zen"] cards = [ "adyen", @@ -352,8 +351,8 @@ email_role_arn = "" # The amazon resource name ( arn ) of the role which sts_role_session_name = "" # An identifier for the assumed role session, used to uniquely identify a session. [user] -password_validity_in_days = 90 # Number of days after which password should be updated -two_factor_auth_expiry_in_secs = 300 # Number of seconds after which 2FA should be done again if doing update/change from inside +password_validity_in_days = 90 # Number of days after which password should be updated +two_factor_auth_expiry_in_secs = 300 # Number of seconds after which 2FA should be done again if doing update/change from inside #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] @@ -364,7 +363,7 @@ stax = { long_lived_token = true, payment_method = "card,bank_debit" } square = { long_lived_token = false, payment_method = "card" } braintree = { long_lived_token = false, payment_method = "card" } gocardless = { long_lived_token = true, payment_method = "bank_debit" } -billwerk = {long_lived_token = false, payment_method = "card"} +billwerk = { long_lived_token = false, payment_method = "card" } [temp_locker_enable_config] stripe = { payment_method = "bank_transfer" } @@ -397,16 +396,16 @@ slack_invite_url = "https://www.example.com/" # Slack invite url for hyperswit discord_invite_url = "https://www.example.com/" # Discord invite url for hyperswitch [mandates.supported_payment_methods] -card.credit = { connector_list = "stripe,adyen,cybersource,bankofamerica"} # Mandate supported payment method type and connector for card -wallet.paypal = { connector_list = "adyen" } # Mandate supported payment method type and connector for wallets -pay_later.klarna = { connector_list = "adyen" } # Mandate supported payment method type and connector for pay_later -bank_debit.ach = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit -bank_debit.becs = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit -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 +card.credit = { connector_list = "stripe,adyen,cybersource,bankofamerica" } # Mandate supported payment method type and connector for card +wallet.paypal = { connector_list = "adyen" } # Mandate supported payment method type and connector for wallets +pay_later.klarna = { connector_list = "adyen" } # Mandate supported payment method type and connector for pay_later +bank_debit.ach = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit +bank_debit.becs = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit +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,bankofamerica" } -wallet.google_pay = { connector_list = "bankofamerica"} +wallet.google_pay = { connector_list = "bankofamerica" } bank_redirect.giropay = { connector_list = "adyen,globalpay" } @@ -589,6 +588,7 @@ outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webh dispute_analytics_topic = "topic" # Kafka topic to be used for Dispute events audit_events_topic = "topic" # Kafka topic to be used for Payment Audit events payout_analytics_topic = "topic" # Kafka topic to be used for Payouts and PayoutAttempt events +consolidated_events_topic = "topic" # Kafka topic to be used for Consolidated events # File storage configuration [file_storage] diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index fc02335dcf5..7215e1931a4 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -81,6 +81,7 @@ outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webh dispute_analytics_topic = "topic" # Kafka topic to be used for Dispute events audit_events_topic = "topic" # Kafka topic to be used for Payment Audit events payout_analytics_topic = "topic" # Kafka topic to be used for Payouts and PayoutAttempt events +consolidated_events_topic = "topic" # Kafka topic to be used for Consolidated events # File storage configuration [file_storage] diff --git a/config/development.toml b/config/development.toml index 56d74e67489..496ce6477a8 100644 --- a/config/development.toml +++ b/config/development.toml @@ -89,8 +89,7 @@ vault_private_key = "" tunnel_private_key = "" [connectors.supported] -wallets = ["klarna", - "mifinity", "braintree", "applepay", "adyen"] +wallets = ["klarna", "mifinity", "braintree", "applepay", "adyen"] rewards = ["cashtocode", "zen"] cards = [ "aci", @@ -559,7 +558,7 @@ redis_lock_expiry_seconds = 180 # 3 * 60 seconds delay_between_retries_in_milliseconds = 500 [kv_config] -ttl = 900 # 15 * 60 seconds +ttl = 900 # 15 * 60 seconds soft_kill = false [frm] @@ -579,6 +578,7 @@ outgoing_webhook_logs_topic = "hyperswitch-outgoing-webhook-events" dispute_analytics_topic = "hyperswitch-dispute-events" audit_events_topic = "hyperswitch-audit-events" payout_analytics_topic = "hyperswitch-payout-events" +consolidated_events_topic = "hyperswitch-consolidated-events" [analytics] source = "sqlx" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 3dac84e21d8..b94b5c8afbb 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -180,8 +180,7 @@ zsl.base_url = "https://api.sitoffalb.net/" apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US,KR,VN,MA,ZA,VA,CL,SV,GT,HN,PA", currency = "AED,AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } [connectors.supported] -wallets = ["klarna", - "mifinity", "braintree", "applepay"] +wallets = ["klarna", "mifinity", "braintree", "applepay"] rewards = ["cashtocode", "zen"] cards = [ "aci", @@ -239,7 +238,7 @@ cards = [ "worldline", "worldpay", "zen", - "zsl" + "zsl", ] [delayed_session_response] @@ -269,7 +268,7 @@ stax = { long_lived_token = true, payment_method = "card,bank_debit" } square = { long_lived_token = false, payment_method = "card" } braintree = { long_lived_token = false, payment_method = "card" } gocardless = { long_lived_token = true, payment_method = "bank_debit" } -billwerk = {long_lived_token = false, payment_method = "card"} +billwerk = { long_lived_token = false, payment_method = "card" } [temp_locker_enable_config] stripe = { payment_method = "bank_transfer" } @@ -433,6 +432,7 @@ outgoing_webhook_logs_topic = "hyperswitch-outgoing-webhook-events" dispute_analytics_topic = "hyperswitch-dispute-events" audit_events_topic = "hyperswitch-audit-events" payout_analytics_topic = "hyperswitch-payout-events" +consolidated_events_topic = "hyperswitch-consolidated-events" [analytics] source = "sqlx" @@ -454,7 +454,7 @@ connection_timeout = 10 queue_strategy = "Fifo" [kv_config] -ttl = 900 # 15 * 60 seconds +ttl = 900 # 15 * 60 seconds soft_kill = false [frm] diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs index 4bca5824835..e1ecd09804c 100644 --- a/crates/router/src/events.rs +++ b/crates/router/src/events.rs @@ -30,6 +30,7 @@ pub enum EventType { AuditEvent, #[cfg(feature = "payouts")] Payout, + Consolidated, } #[derive(Debug, Default, Deserialize, Clone)] diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index 6f2aa9fcd10..3523ab9261f 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -12,9 +12,13 @@ use rdkafka::{ pub mod payout; use crate::events::EventType; mod dispute; +mod dispute_event; mod payment_attempt; +mod payment_attempt_event; mod payment_intent; +mod payment_intent_event; mod refund; +mod refund_event; use diesel_models::refund::Refund; use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent}; use serde::Serialize; @@ -23,8 +27,10 @@ use time::{OffsetDateTime, PrimitiveDateTime}; #[cfg(feature = "payouts")] use self::payout::KafkaPayout; use self::{ - dispute::KafkaDispute, payment_attempt::KafkaPaymentAttempt, - payment_intent::KafkaPaymentIntent, refund::KafkaRefund, + dispute::KafkaDispute, dispute_event::KafkaDisputeEvent, payment_attempt::KafkaPaymentAttempt, + payment_attempt_event::KafkaPaymentAttemptEvent, payment_intent::KafkaPaymentIntent, + payment_intent_event::KafkaPaymentIntentEvent, refund::KafkaRefund, + refund_event::KafkaRefundEvent, }; use crate::types::storage::Dispute; @@ -89,6 +95,42 @@ impl<'a, T: KafkaMessage> KafkaMessage for KafkaEvent<'a, T> { } } +#[derive(serde::Serialize, Debug)] +struct KafkaConsolidatedLog<'a, T: KafkaMessage> { + #[serde(flatten)] + event: &'a T, + tenant_id: TenantID, +} + +#[derive(serde::Serialize, Debug)] +struct KafkaConsolidatedEvent<'a, T: KafkaMessage> { + log: KafkaConsolidatedLog<'a, T>, + log_type: EventType, +} + +impl<'a, T: KafkaMessage> KafkaConsolidatedEvent<'a, T> { + fn new(event: &'a T, tenant_id: TenantID) -> Self { + Self { + log: KafkaConsolidatedLog { event, tenant_id }, + log_type: event.event_type(), + } + } +} + +impl<'a, T: KafkaMessage> KafkaMessage for KafkaConsolidatedEvent<'a, T> { + fn key(&self) -> String { + self.log.event.key() + } + + fn event_type(&self) -> EventType { + EventType::Consolidated + } + + fn creation_timestamp(&self) -> Option<i64> { + self.log.event.creation_timestamp() + } +} + #[derive(Debug, serde::Deserialize, Clone, Default)] #[serde(default)] pub struct KafkaSettings { @@ -103,6 +145,7 @@ pub struct KafkaSettings { audit_events_topic: String, #[cfg(feature = "payouts")] payout_analytics_topic: String, + consolidated_events_topic: String, } impl KafkaSettings { @@ -175,6 +218,12 @@ impl KafkaSettings { )) })?; + common_utils::fp_utils::when(self.consolidated_events_topic.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "Consolidated Events topic must not be empty".into(), + )) + })?; + Ok(()) } } @@ -192,6 +241,7 @@ pub struct KafkaProducer { audit_events_topic: String, #[cfg(feature = "payouts")] payout_analytics_topic: String, + consolidated_events_topic: String, } struct RdKafkaProducer(ThreadedProducer<DefaultProducerContext>); @@ -233,23 +283,13 @@ impl KafkaProducer { audit_events_topic: conf.audit_events_topic.clone(), #[cfg(feature = "payouts")] payout_analytics_topic: conf.payout_analytics_topic.clone(), + consolidated_events_topic: conf.consolidated_events_topic.clone(), }) } pub fn log_event<T: KafkaMessage>(&self, event: &T) -> MQResult<()> { router_env::logger::debug!("Logging Kafka Event {event:?}"); - let topic = match event.event_type() { - EventType::PaymentIntent => &self.intent_analytics_topic, - EventType::PaymentAttempt => &self.attempt_analytics_topic, - EventType::Refund => &self.refund_analytics_topic, - EventType::ApiLogs => &self.api_logs_topic, - EventType::ConnectorApiLogs => &self.connector_logs_topic, - EventType::OutgoingWebhookLogs => &self.outgoing_webhook_logs_topic, - EventType::Dispute => &self.dispute_analytics_topic, - EventType::AuditEvent => &self.audit_events_topic, - #[cfg(feature = "payouts")] - EventType::Payout => &self.payout_analytics_topic, - }; + let topic = self.get_topic(event.event_type()); self.producer .0 .send( @@ -281,11 +321,18 @@ impl KafkaProducer { format!("Failed to add negative attempt event {negative_event:?}") })?; }; + self.log_event(&KafkaEvent::new( &KafkaPaymentAttempt::from_storage(attempt), tenant_id.clone(), )) - .attach_printable_lazy(|| format!("Failed to add positive attempt event {attempt:?}")) + .attach_printable_lazy(|| format!("Failed to add positive attempt event {attempt:?}"))?; + + self.log_event(&KafkaConsolidatedEvent::new( + &KafkaPaymentAttemptEvent::from_storage(attempt), + tenant_id.clone(), + )) + .attach_printable_lazy(|| format!("Failed to add consolidated attempt event {attempt:?}")) } pub async fn log_payment_attempt_delete( @@ -317,11 +364,18 @@ impl KafkaProducer { format!("Failed to add negative intent event {negative_event:?}") })?; }; + self.log_event(&KafkaEvent::new( &KafkaPaymentIntent::from_storage(intent), tenant_id.clone(), )) - .attach_printable_lazy(|| format!("Failed to add positive intent event {intent:?}")) + .attach_printable_lazy(|| format!("Failed to add positive intent event {intent:?}"))?; + + self.log_event(&KafkaConsolidatedEvent::new( + &KafkaPaymentIntentEvent::from_storage(intent), + tenant_id.clone(), + )) + .attach_printable_lazy(|| format!("Failed to add consolidated intent event {intent:?}")) } pub async fn log_payment_intent_delete( @@ -353,11 +407,18 @@ impl KafkaProducer { format!("Failed to add negative refund event {negative_event:?}") })?; }; + self.log_event(&KafkaEvent::new( &KafkaRefund::from_storage(refund), tenant_id.clone(), )) - .attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}")) + .attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}"))?; + + self.log_event(&KafkaConsolidatedEvent::new( + &KafkaRefundEvent::from_storage(refund), + tenant_id.clone(), + )) + .attach_printable_lazy(|| format!("Failed to add consolidated refund event {refund:?}")) } pub async fn log_refund_delete( @@ -389,11 +450,18 @@ impl KafkaProducer { format!("Failed to add negative dispute event {negative_event:?}") })?; }; + self.log_event(&KafkaEvent::new( &KafkaDispute::from_storage(dispute), tenant_id.clone(), )) - .attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}")) + .attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}"))?; + + self.log_event(&KafkaConsolidatedEvent::new( + &KafkaDisputeEvent::from_storage(dispute), + tenant_id.clone(), + )) + .attach_printable_lazy(|| format!("Failed to add consolidated dispute event {dispute:?}")) } #[cfg(feature = "payouts")] @@ -437,6 +505,7 @@ impl KafkaProducer { EventType::AuditEvent => &self.audit_events_topic, #[cfg(feature = "payouts")] EventType::Payout => &self.payout_analytics_topic, + EventType::Consolidated => &self.consolidated_events_topic, } } } diff --git a/crates/router/src/services/kafka/dispute_event.rs b/crates/router/src/services/kafka/dispute_event.rs new file mode 100644 index 00000000000..71e0a11e04d --- /dev/null +++ b/crates/router/src/services/kafka/dispute_event.rs @@ -0,0 +1,77 @@ +use diesel_models::enums as storage_enums; +use masking::Secret; +use time::OffsetDateTime; + +use crate::types::storage::dispute::Dispute; + +#[serde_with::skip_serializing_none] +#[derive(serde::Serialize, Debug)] +pub struct KafkaDisputeEvent<'a> { + pub dispute_id: &'a String, + pub dispute_amount: i64, + 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::milliseconds::option")] + pub challenge_required_by: Option<OffsetDateTime>, + #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + pub connector_created_at: Option<OffsetDateTime>, + #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + pub connector_updated_at: Option<OffsetDateTime>, + #[serde(default, with = "time::serde::timestamp::milliseconds")] + pub created_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp::milliseconds")] + 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> KafkaDisputeEvent<'a> { + pub fn from_storage(dispute: &'a Dispute) -> Self { + Self { + dispute_id: &dispute.dispute_id, + dispute_amount: dispute.amount.parse::<i64>().unwrap_or_default(), + 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 KafkaDisputeEvent<'a> { + fn key(&self) -> String { + format!( + "{}_{}_{}", + self.merchant_id, self.payment_id, self.dispute_id + ) + } + + fn event_type(&self) -> crate::events::EventType { + crate::events::EventType::Dispute + } +} diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs new file mode 100644 index 00000000000..bb4d69eda27 --- /dev/null +++ b/crates/router/src/services/kafka/payment_attempt_event.rs @@ -0,0 +1,119 @@ +// use diesel_models::enums::MandateDetails; +use common_utils::types::MinorUnit; +use diesel_models::enums as storage_enums; +use hyperswitch_domain_models::{ + mandates::MandateDetails, payments::payment_attempt::PaymentAttempt, +}; +use time::OffsetDateTime; + +#[serde_with::skip_serializing_none] +#[derive(serde::Serialize, Debug)] +pub struct KafkaPaymentAttemptEvent<'a> { + pub payment_id: &'a String, + pub merchant_id: &'a String, + pub attempt_id: &'a String, + pub status: storage_enums::AttemptStatus, + pub amount: MinorUnit, + pub currency: Option<storage_enums::Currency>, + pub save_to_locker: Option<bool>, + pub connector: Option<&'a String>, + pub error_message: Option<&'a String>, + pub offer_amount: Option<MinorUnit>, + pub surcharge_amount: Option<MinorUnit>, + pub tax_amount: Option<MinorUnit>, + pub payment_method_id: Option<&'a String>, + pub payment_method: Option<storage_enums::PaymentMethod>, + pub connector_transaction_id: Option<&'a String>, + pub capture_method: Option<storage_enums::CaptureMethod>, + #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + pub capture_on: Option<OffsetDateTime>, + pub confirm: bool, + pub authentication_type: Option<storage_enums::AuthenticationType>, + #[serde(with = "time::serde::timestamp::milliseconds")] + pub created_at: OffsetDateTime, + #[serde(with = "time::serde::timestamp::milliseconds")] + pub modified_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + pub last_synced: Option<OffsetDateTime>, + pub cancellation_reason: Option<&'a String>, + pub amount_to_capture: Option<MinorUnit>, + pub mandate_id: Option<&'a String>, + pub browser_info: Option<String>, + pub error_code: Option<&'a String>, + pub connector_metadata: Option<String>, + // TODO: These types should implement copy ideally + pub payment_experience: Option<&'a storage_enums::PaymentExperience>, + pub payment_method_type: Option<&'a storage_enums::PaymentMethodType>, + pub payment_method_data: Option<String>, + pub error_reason: Option<&'a String>, + pub multiple_capture_count: Option<i16>, + pub amount_capturable: MinorUnit, + pub merchant_connector_id: Option<&'a String>, + pub net_amount: MinorUnit, + pub unified_code: Option<&'a String>, + pub unified_message: Option<&'a String>, + pub mandate_data: Option<&'a MandateDetails>, + pub client_source: Option<&'a String>, + pub client_version: Option<&'a String>, +} + +impl<'a> KafkaPaymentAttemptEvent<'a> { + pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { + Self { + payment_id: &attempt.payment_id, + merchant_id: &attempt.merchant_id, + attempt_id: &attempt.attempt_id, + status: attempt.status, + amount: attempt.amount, + currency: attempt.currency, + save_to_locker: attempt.save_to_locker, + connector: attempt.connector.as_ref(), + error_message: attempt.error_message.as_ref(), + offer_amount: attempt.offer_amount, + surcharge_amount: attempt.surcharge_amount, + tax_amount: attempt.tax_amount, + payment_method_id: attempt.payment_method_id.as_ref(), + payment_method: attempt.payment_method, + connector_transaction_id: attempt.connector_transaction_id.as_ref(), + capture_method: attempt.capture_method, + capture_on: attempt.capture_on.map(|i| i.assume_utc()), + confirm: attempt.confirm, + authentication_type: attempt.authentication_type, + created_at: attempt.created_at.assume_utc(), + modified_at: attempt.modified_at.assume_utc(), + last_synced: attempt.last_synced.map(|i| i.assume_utc()), + cancellation_reason: attempt.cancellation_reason.as_ref(), + amount_to_capture: attempt.amount_to_capture, + mandate_id: attempt.mandate_id.as_ref(), + browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()), + error_code: attempt.error_code.as_ref(), + connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()), + payment_experience: attempt.payment_experience.as_ref(), + payment_method_type: attempt.payment_method_type.as_ref(), + payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()), + error_reason: attempt.error_reason.as_ref(), + multiple_capture_count: attempt.multiple_capture_count, + amount_capturable: attempt.amount_capturable, + merchant_connector_id: attempt.merchant_connector_id.as_ref(), + net_amount: attempt.net_amount, + unified_code: attempt.unified_code.as_ref(), + unified_message: attempt.unified_message.as_ref(), + mandate_data: attempt.mandate_data.as_ref(), + client_source: attempt.client_source.as_ref(), + client_version: attempt.client_version.as_ref(), + } + } +} + +impl<'a> super::KafkaMessage for KafkaPaymentAttemptEvent<'a> { + fn key(&self) -> String { + format!( + "{}_{}_{}", + self.merchant_id, self.payment_id, self.attempt_id + ) + } + + fn event_type(&self) -> crate::events::EventType { + crate::events::EventType::PaymentAttempt + } +} diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs new file mode 100644 index 00000000000..a3fbd9ddc45 --- /dev/null +++ b/crates/router/src/services/kafka/payment_intent_event.rs @@ -0,0 +1,75 @@ +use common_utils::{id_type, types::MinorUnit}; +use diesel_models::enums as storage_enums; +use hyperswitch_domain_models::payments::PaymentIntent; +use time::OffsetDateTime; + +#[serde_with::skip_serializing_none] +#[derive(serde::Serialize, Debug)] +pub struct KafkaPaymentIntentEvent<'a> { + pub payment_id: &'a String, + pub merchant_id: &'a String, + pub status: storage_enums::IntentStatus, + pub amount: MinorUnit, + pub currency: Option<storage_enums::Currency>, + pub amount_captured: Option<MinorUnit>, + pub customer_id: Option<&'a id_type::CustomerId>, + pub description: Option<&'a String>, + pub return_url: Option<&'a String>, + pub connector_id: Option<&'a String>, + pub statement_descriptor_name: Option<&'a String>, + pub statement_descriptor_suffix: Option<&'a String>, + #[serde(with = "time::serde::timestamp::milliseconds")] + pub created_at: OffsetDateTime, + #[serde(with = "time::serde::timestamp::milliseconds")] + pub modified_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + pub last_synced: Option<OffsetDateTime>, + pub setup_future_usage: Option<storage_enums::FutureUsage>, + pub off_session: Option<bool>, + pub client_secret: Option<&'a String>, + pub active_attempt_id: String, + pub business_country: Option<storage_enums::CountryAlpha2>, + pub business_label: Option<&'a String>, + pub attempt_count: i16, + pub payment_confirm_source: Option<storage_enums::PaymentSource>, +} + +impl<'a> KafkaPaymentIntentEvent<'a> { + pub fn from_storage(intent: &'a PaymentIntent) -> Self { + Self { + payment_id: &intent.payment_id, + merchant_id: &intent.merchant_id, + status: intent.status, + amount: intent.amount, + currency: intent.currency, + amount_captured: intent.amount_captured, + customer_id: intent.customer_id.as_ref(), + description: intent.description.as_ref(), + return_url: intent.return_url.as_ref(), + connector_id: intent.connector_id.as_ref(), + statement_descriptor_name: intent.statement_descriptor_name.as_ref(), + statement_descriptor_suffix: intent.statement_descriptor_suffix.as_ref(), + created_at: intent.created_at.assume_utc(), + modified_at: intent.modified_at.assume_utc(), + last_synced: intent.last_synced.map(|i| i.assume_utc()), + setup_future_usage: intent.setup_future_usage, + off_session: intent.off_session, + client_secret: intent.client_secret.as_ref(), + active_attempt_id: intent.active_attempt.get_id(), + business_country: intent.business_country, + business_label: intent.business_label.as_ref(), + attempt_count: intent.attempt_count, + payment_confirm_source: intent.payment_confirm_source, + } + } +} + +impl<'a> super::KafkaMessage for KafkaPaymentIntentEvent<'a> { + fn key(&self) -> String { + format!("{}_{}", self.merchant_id, self.payment_id) + } + + fn event_type(&self) -> crate::events::EventType { + crate::events::EventType::PaymentIntent + } +} diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs new file mode 100644 index 00000000000..6aa80b243c1 --- /dev/null +++ b/crates/router/src/services/kafka/refund_event.rs @@ -0,0 +1,74 @@ +use common_utils::types::MinorUnit; +use diesel_models::{enums as storage_enums, refund::Refund}; +use time::OffsetDateTime; + +#[serde_with::skip_serializing_none] +#[derive(serde::Serialize, Debug)] +pub struct KafkaRefundEvent<'a> { + pub internal_reference_id: &'a String, + pub refund_id: &'a String, //merchant_reference id + pub payment_id: &'a String, + pub merchant_id: &'a String, + pub connector_transaction_id: &'a String, + pub connector: &'a String, + pub connector_refund_id: Option<&'a String>, + pub external_reference_id: Option<&'a String>, + pub refund_type: &'a storage_enums::RefundType, + pub total_amount: &'a MinorUnit, + pub currency: &'a storage_enums::Currency, + pub refund_amount: &'a MinorUnit, + pub refund_status: &'a storage_enums::RefundStatus, + pub sent_to_gateway: &'a bool, + pub refund_error_message: Option<&'a String>, + pub refund_arn: Option<&'a String>, + #[serde(default, with = "time::serde::timestamp::milliseconds")] + pub created_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp::milliseconds")] + pub modified_at: OffsetDateTime, + pub description: Option<&'a String>, + pub attempt_id: &'a String, + pub refund_reason: Option<&'a String>, + pub refund_error_code: Option<&'a String>, +} + +impl<'a> KafkaRefundEvent<'a> { + pub fn from_storage(refund: &'a Refund) -> Self { + Self { + internal_reference_id: &refund.internal_reference_id, + refund_id: &refund.refund_id, + payment_id: &refund.payment_id, + merchant_id: &refund.merchant_id, + connector_transaction_id: &refund.connector_transaction_id, + connector: &refund.connector, + connector_refund_id: refund.connector_refund_id.as_ref(), + external_reference_id: refund.external_reference_id.as_ref(), + refund_type: &refund.refund_type, + total_amount: &refund.total_amount, + currency: &refund.currency, + refund_amount: &refund.refund_amount, + refund_status: &refund.refund_status, + sent_to_gateway: &refund.sent_to_gateway, + refund_error_message: refund.refund_error_message.as_ref(), + refund_arn: refund.refund_arn.as_ref(), + created_at: refund.created_at.assume_utc(), + modified_at: refund.updated_at.assume_utc(), + description: refund.description.as_ref(), + attempt_id: &refund.attempt_id, + refund_reason: refund.refund_reason.as_ref(), + refund_error_code: refund.refund_error_code.as_ref(), + } + } +} + +impl<'a> super::KafkaMessage for KafkaRefundEvent<'a> { + fn key(&self) -> String { + format!( + "{}_{}_{}_{}", + self.merchant_id, self.payment_id, self.attempt_id, self.refund_id + ) + } + + fn event_type(&self) -> crate::events::EventType { + crate::events::EventType::Refund + } +}
2024-05-28T14:10:35Z
## Description - add consolidated payment events to a single topic for sessionizing - add millisecond precision to timestamp fields ### 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 [#4797](https://github.com/juspay/hyperswitch/issues/4797) ## How did you test it? - Create payment, refund, dispute - check `topic: hyperswitch-consolidated-events` for combined logs for above events ![Screenshot 2024-05-28 at 7 43 24 PM](https://github.com/juspay/hyperswitch/assets/138492857/9cb3bf17-a0aa-4ce0-9a41-30bde996c3ef) ![Screenshot 2024-05-28 at 7 44 04 PM](https://github.com/juspay/hyperswitch/assets/138492857/7573ce27-19f0-4ae7-a138-a28098c3cd3f)
865007717c5c7e617ca1b447ea5f9bb3d274cac3
- Create payment, refund, dispute - check `topic: hyperswitch-consolidated-events` for combined logs for above events ![Screenshot 2024-05-28 at 7 43 24 PM](https://github.com/juspay/hyperswitch/assets/138492857/9cb3bf17-a0aa-4ce0-9a41-30bde996c3ef) ![Screenshot 2024-05-28 at 7 44 04 PM](https://github.com/juspay/hyperswitch/assets/138492857/7573ce27-19f0-4ae7-a138-a28098c3cd3f)
[ "config/config.example.toml", "config/deployments/env_specific.toml", "config/development.toml", "config/docker_compose.toml", "crates/router/src/events.rs", "crates/router/src/services/kafka.rs", "crates/router/src/services/kafka/dispute_event.rs", "crates/router/src/services/kafka/payment_attempt_ev...
juspay/hyperswitch
juspay__hyperswitch-4796
Bug: [FIX] implement `StrongEq` for `StrongSecre<Vec<u8>>`
diff --git a/crates/masking/src/strong_secret.rs b/crates/masking/src/strong_secret.rs index fd1335f6993..51c0f2cb3fe 100644 --- a/crates/masking/src/strong_secret.rs +++ b/crates/masking/src/strong_secret.rs @@ -117,3 +117,12 @@ impl StrongEq for String { bool::from(lhs.ct_eq(rhs)) } } + +impl StrongEq for Vec<u8> { + fn strong_eq(&self, other: &Self) -> bool { + let lhs = &self; + let rhs = &other; + + bool::from(lhs.ct_eq(rhs)) + } +}
2024-05-28T14:04:33Z
## Description <!-- Describe your changes in detail --> Implement `StrongEq` for `Vec<u8>` ## 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). --> Implement `StrongEq` for deriving `Eq` for `StrongSecret<Vec<u8>>`. ## 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)? --> NA. Testing is not needed, compiler guided.
84e032e6c28afc410c82e73e51deb629b0c4a81a
NA. Testing is not needed, compiler guided.
[ "crates/masking/src/strong_secret.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4793
Bug: Filter the apple pay retryable connectors for a specific business profile Currently while fetching the apple pay retry connector list all the enabled merchant connector accounts for that specific merchant id is included. But we need to retry the connector with only the connectors in that specific profile id with which the payment attempt was created.
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 7bc0b532239..b64e7479c4d 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3165,11 +3165,11 @@ where routing_data.business_sub_label = choice.sub_label.clone(); } - #[cfg(feature = "retry")] + #[cfg(all(feature = "retry", feature = "connector_choice_mca_id"))] let should_do_retry = retry::config_should_call_gsm(&*state.store, &merchant_account.merchant_id).await; - #[cfg(feature = "retry")] + #[cfg(all(feature = "retry", feature = "connector_choice_mca_id"))] if payment_data.payment_attempt.payment_method_type == Some(storage_enums::PaymentMethodType::ApplePay) && should_do_retry @@ -3180,15 +3180,15 @@ where payment_data, key_store, connector_data.clone(), - #[cfg(feature = "connector_choice_mca_id")] choice.merchant_connector_id.clone().as_ref(), - #[cfg(not(feature = "connector_choice_mca_id"))] - None, ) .await?; if let Some(connector_data_list) = retryable_connector_data { - return Ok(ConnectorCallType::Retryable(connector_data_list)); + if connector_data_list.len() > 1 { + logger::info!("Constructed apple pay retryable connector list"); + return Ok(ConnectorCallType::Retryable(connector_data_list)); + } } } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 8f7ed4da256..74bfea22f2c 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3961,6 +3961,7 @@ pub fn get_applepay_metadata( }) } +#[cfg(all(feature = "retry", feature = "connector_choice_mca_id"))] pub async fn get_apple_pay_retryable_connectors<F>( state: AppState, merchant_account: &domain::MerchantAccount, @@ -3986,7 +3987,7 @@ where merchant_account.merchant_id.as_str(), payment_data.creds_identifier.to_owned(), key_store, - profile_id, // need to fix this + profile_id, &decided_connector_data.connector_name.to_string(), merchant_connector_id, ) @@ -4008,9 +4009,14 @@ where .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; + let profile_specific_merchant_connector_account_list = filter_mca_based_on_business_profile( + merchant_connector_account_list, + Some(profile_id.to_string()), + ); + let mut connector_data_list = vec![decided_connector_data.clone()]; - for merchant_connector_account in merchant_connector_account_list { + for merchant_connector_account in profile_specific_merchant_connector_account_list { if is_apple_pay_simplified_flow( merchant_connector_account.metadata, Some(&merchant_connector_account.connector_name), @@ -4031,7 +4037,33 @@ where } } } - Some(connector_data_list) + + let fallback_connetors_list = crate::core::routing::helpers::get_merchant_default_config( + &*state.clone().store, + profile_id, + &api_enums::TransactionType::Payment, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get merchant default fallback connectors config")?; + + // connector_data_list is the list of connectors for which Apple Pay simplified flow is configured. + // This list is arranged in the same order as the merchant's default fallback connectors configuration. + let mut ordered_connector_data_list = vec![decided_connector_data.clone()]; + fallback_connetors_list + .iter() + .for_each(|fallback_connector| { + let connector_data = connector_data_list.iter().find(|connector_data| { + fallback_connector.merchant_connector_id == connector_data.merchant_connector_id + && fallback_connector.merchant_connector_id + != decided_connector_data.merchant_connector_id + }); + if let Some(connector_data_details) = connector_data { + ordered_connector_data_list.push(connector_data_details.clone()); + } + }); + + Some(ordered_connector_data_list) } else { None };
2024-05-28T13:56:51Z
## Description <!-- Describe your changes in detail --> Currently while fetching the apple pay retry connector list all the enabled merchant connector accounts for that specific merchant id is included. But we need to retry the connector with only the connectors in that specific profile id with which the payment attempt was created. Also range the apple pay retry connector in the default fallback configuration sequence. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create merchant connector accounts with apple pay simplified configured for some of them. -> Use the below curl to set the default connectors ``` curl --location 'https://sandbox.hyperswitch.io/routing/default/profile/pro_SIWKUcl7KWmcoRroVz1r' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWJjZGIxYWItYmJiMS00YmY0LTgwYjQtNmQyYmM0NzIyZGUzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk5MzUwNTMzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcwMDA1MjQwMCwib3JnX2lkIjoib3JnX0F3bmNqWFNUQW9ncUgwdUpVU2h2In0.WigP7IrTpBhP4LbWcimEJX0lJfnsjgEimOCOiBK1vxs' \ --data '[ { "connector": "adyen", "merchant_connector_id": "mca_NASIts6PGENwK4gd39mW" }, { "connector": "bluesnap", "merchant_connector_id": "mca_E6t0JCvdefLSNoPUSGWh" } ]' ``` <img width="1111" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/839b8e63-910d-4178-99b0-90017668dab3"> -> Create a payment with confirm false ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_XoFL52XqqjWadvSrBkC4Kt91eIH5JUEgg9APgemwbWOnyxVYlT49S3kjDFRuoO65' \ --data-raw '{ "amount": 6500, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "amount_to_capture": 6500, "customer_id": "sai", "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" }' ``` <img width="1142" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9f0baef3-2c35-474b-9741-4d5abe6219e9"> -> Do payment method list for the merchant ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_08tgyPCEZNQrMIvRBzzZ_secret_1MBVp3rgr2vqJfiH5Gyr' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_5d8a78ba4cf84af78765ff59ea249fc6' ``` <img width="1146" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/17c0e1b6-8e35-4509-bc9f-d06109bdd72b"> -> Confirm the payment with apple pay payment data ``` curl --location 'http://localhost:8080/payments/pay_08tgyPCEZNQrMIvRBzzZ/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_XoFL52XqqjWadvSrBkC4Kt91eIH5JUEgg9APgemwbWOnyxVYlT49S3kjDFRuoO65' \ --data '{ "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0VtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRmdzNldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433FCF84AFD01E4E65DD8ADE306300E9D8" } } } }' ``` <img width="1151" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/eea27285-d7dc-49f6-8a81-39a0c73dd8d6"> -> I had configured apple pay simplified flow for stripe, rapyd, adyen and manual flow for cybersource. And my default fallback list is stripe, rapyd, cybersource, adyen. Below is the apple pay retry connector list <img width="1030" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/225c4786-8175-4ce9-bf9b-9a377ef60f8e">
865007717c5c7e617ca1b447ea5f9bb3d274cac3
-> Create merchant connector accounts with apple pay simplified configured for some of them. -> Use the below curl to set the default connectors ``` curl --location 'https://sandbox.hyperswitch.io/routing/default/profile/pro_SIWKUcl7KWmcoRroVz1r' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWJjZGIxYWItYmJiMS00YmY0LTgwYjQtNmQyYmM0NzIyZGUzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk5MzUwNTMzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcwMDA1MjQwMCwib3JnX2lkIjoib3JnX0F3bmNqWFNUQW9ncUgwdUpVU2h2In0.WigP7IrTpBhP4LbWcimEJX0lJfnsjgEimOCOiBK1vxs' \ --data '[ { "connector": "adyen", "merchant_connector_id": "mca_NASIts6PGENwK4gd39mW" }, { "connector": "bluesnap", "merchant_connector_id": "mca_E6t0JCvdefLSNoPUSGWh" } ]' ``` <img width="1111" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/839b8e63-910d-4178-99b0-90017668dab3"> -> Create a payment with confirm false ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_XoFL52XqqjWadvSrBkC4Kt91eIH5JUEgg9APgemwbWOnyxVYlT49S3kjDFRuoO65' \ --data-raw '{ "amount": 6500, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "amount_to_capture": 6500, "customer_id": "sai", "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" }' ``` <img width="1142" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9f0baef3-2c35-474b-9741-4d5abe6219e9"> -> Do payment method list for the merchant ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_08tgyPCEZNQrMIvRBzzZ_secret_1MBVp3rgr2vqJfiH5Gyr' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_5d8a78ba4cf84af78765ff59ea249fc6' ``` <img width="1146" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/17c0e1b6-8e35-4509-bc9f-d06109bdd72b"> -> Confirm the payment with apple pay payment data ``` curl --location 'http://localhost:8080/payments/pay_08tgyPCEZNQrMIvRBzzZ/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_XoFL52XqqjWadvSrBkC4Kt91eIH5JUEgg9APgemwbWOnyxVYlT49S3kjDFRuoO65' \ --data '{ "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0VtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRmdzNldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433FCF84AFD01E4E65DD8ADE306300E9D8" } } } }' ``` <img width="1151" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/eea27285-d7dc-49f6-8a81-39a0c73dd8d6"> -> I had configured apple pay simplified flow for stripe, rapyd, adyen and manual flow for cybersource. And my default fallback list is stripe, rapyd, cybersource, adyen. Below is the apple pay retry connector list <img width="1030" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/225c4786-8175-4ce9-bf9b-9a377ef60f8e">
[ "crates/router/src/core/payments.rs", "crates/router/src/core/payments/helpers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4816
Bug: Code changes to get the certificates from the certificates column with fallback The migration api can be run on the deployment environment only after the 100% deployment of the specific version of hyperswitch, because there are probabilities of merchant account being created even during the deployments. Once deployment beings the apple pay details must be read from the metadata only until the migrations are done. Hence we need a fallback here which tries to read the apple pay data from the newly added column whenever need and if it fails we just log the error and try to read the apple pay data from the metadata. Once the migration is done we can check for the error log lines during the read form newly added column, if there are no logs we can remove the fallback in future. Else we might need to rerun the migrations for the specific merchant connector account.
diff --git a/crates/api_models/src/apple_pay_certificates_migration.rs b/crates/api_models/src/apple_pay_certificates_migration.rs new file mode 100644 index 00000000000..796734f53e4 --- /dev/null +++ b/crates/api_models/src/apple_pay_certificates_migration.rs @@ -0,0 +1,12 @@ +#[derive(Debug, Clone, serde::Serialize)] +pub struct ApplePayCertificatesMigrationResponse { + pub migration_successful: Vec<String>, + pub migration_failed: Vec<String>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +pub struct ApplePayCertificatesMigrationRequest { + pub merchant_ids: Vec<String>, +} + +impl common_utils::events::ApiEventMetric for ApplePayCertificatesMigrationRequest {} diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 9c26576e77b..078c27e6db9 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -1,3 +1,4 @@ +pub mod apple_pay_certificates_migration; pub mod connector_onboarding; pub mod customer; pub mod dispute; diff --git a/crates/api_models/src/events/apple_pay_certificates_migration.rs b/crates/api_models/src/events/apple_pay_certificates_migration.rs new file mode 100644 index 00000000000..f194443bea0 --- /dev/null +++ b/crates/api_models/src/events/apple_pay_certificates_migration.rs @@ -0,0 +1,9 @@ +use common_utils::events::ApiEventMetric; + +use crate::apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse; + +impl ApiEventMetric for ApplePayCertificatesMigrationResponse { + fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { + Some(common_utils::events::ApiEventsType::ApplePayCertificatesMigration) + } +} diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index a0bc6f6362d..d6d6deaa235 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -2,6 +2,7 @@ pub mod admin; pub mod analytics; pub mod api_keys; +pub mod apple_pay_certificates_migration; pub mod blocklist; pub mod cards_info; pub mod conditional_configs; diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index cda13289aa5..8ccfa14eaf6 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4208,6 +4208,23 @@ pub struct SessionTokenInfo { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, + #[serde(flatten)] + pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +#[serde(tag = "payment_processing_details_at")] +pub enum PaymentProcessingDetailsAt { + Hyperswitch(PaymentProcessingDetails), + Connector, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] +pub struct PaymentProcessingDetails { + #[schema(value_type = String)] + pub payment_processing_certificate: Secret<String>, + #[schema(value_type = String)] + pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 3df291d5681..f20d2b821dd 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2284,11 +2284,6 @@ pub enum ReconStatus { Active, Disabled, } -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ApplePayFlow { - Simplified, - Manual, -} #[derive( Clone, diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index 8939e07a76c..1052840dbc8 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -50,6 +50,7 @@ pub enum ApiEventsType { // TODO: This has to be removed once the corresponding apiEventTypes are created Miscellaneous, RustLocker, + ApplePayCertificatesMigration, FraudCheck, Recon, Dispute { diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index d7c505f7942..b411b1a7acd 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -67,7 +67,7 @@ pub enum ConnectorAuthType { #[derive(Debug, Deserialize, serde::Serialize, Clone)] #[serde(untagged)] pub enum ApplePayTomlConfig { - Standard(payments::ApplePayMetadata), + Standard(Box<payments::ApplePayMetadata>), Zen(ZenApplePay), } diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs index e45ef002626..680e3dacc85 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 connector_wallets_details: Option<Encryption>, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -72,6 +73,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 connector_wallets_details: Option<Encryption>, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] @@ -96,6 +98,7 @@ pub struct MerchantConnectorAccountUpdateInternal { pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, pub status: Option<storage_enums::ConnectorStatus>, + pub connector_wallets_details: Option<Encryption>, } impl MerchantConnectorAccountUpdateInternal { diff --git a/crates/diesel_models/src/query/generics.rs b/crates/diesel_models/src/query/generics.rs index 0527ff3a181..682766679fd 100644 --- a/crates/diesel_models/src/query/generics.rs +++ b/crates/diesel_models/src/query/generics.rs @@ -166,7 +166,8 @@ where } Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound)) .attach_printable_lazy(|| format!("Error while updating {debug_values}")), - _ => Err(report!(errors::DatabaseError::Others)) + Err(error) => Err(error) + .change_context(errors::DatabaseError::Others) .attach_printable_lazy(|| format!("Error while updating {debug_values}")), } } @@ -252,7 +253,8 @@ where } Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound)) .attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")), - _ => Err(report!(errors::DatabaseError::Others)) + Err(error) => Err(error) + .change_context(errors::DatabaseError::Others) .attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")), } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 6074fdc10b7..7baaa337259 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -679,6 +679,7 @@ diesel::table! { applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, pm_auth_config -> Nullable<Jsonb>, status -> ConnectorStatus, + connector_wallets_details -> Nullable<Bytea>, } } diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 065290b6b2d..8dca0c86a2a 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -22,6 +22,12 @@ pub enum PaymentMethodData { CardToken(CardToken), } +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ApplePayFlow { + Simplified(api_models::payments::PaymentProcessingDetails), + Manual, +} + impl PaymentMethodData { pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> { match self { diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index b5d96a5c53f..00e13f5fce9 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -3,7 +3,7 @@ use std::{collections::HashMap, marker::PhantomData}; use common_utils::id_type; use masking::Secret; -use crate::payment_address::PaymentAddress; +use crate::{payment_address::PaymentAddress, payment_method_data}; #[derive(Debug, Clone)] pub struct RouterData<Flow, Request, Response> { @@ -22,6 +22,7 @@ pub struct RouterData<Flow, Request, Response> { pub address: PaymentAddress, pub auth_type: common_enums::enums::AuthenticationType, pub connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, + pub connector_wallets_details: Option<common_utils::pii::SecretSerdeValue>, pub amount_captured: Option<i64>, pub access_token: Option<AccessToken>, pub session_token: Option<String>, @@ -56,7 +57,7 @@ pub struct RouterData<Flow, Request, Response> { pub connector_http_status_code: Option<u16>, pub external_latency: Option<u128>, /// Contains apple pay flow type simplified or manual - pub apple_pay_flow: Option<common_enums::enums::ApplePayFlow>, + pub apple_pay_flow: Option<payment_method_data::ApplePayFlow>, pub frm_metadata: Option<common_utils::pii::SecretSerdeValue>, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 237cddcf94e..f4fc5fc8473 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -309,6 +309,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::FeatureMetadata, api_models::payments::ApplepayConnectorMetadataRequest, api_models::payments::SessionTokenInfo, + api_models::payments::PaymentProcessingDetailsAt, + api_models::payments::PaymentProcessingDetails, api_models::payments::SwishQrData, api_models::payments::AirwallexData, api_models::payments::NoonData, diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 02a5873429f..53787fe04ab 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -1,6 +1,7 @@ pub mod admin; pub mod api_keys; pub mod api_locking; +pub mod apple_pay_certificates_migration; pub mod authentication; pub mod blocklist; pub mod cache; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 6b582c2c957..0578945006f 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -937,7 +937,7 @@ pub async fn create_payment_connector( payment_methods_enabled, test_mode: req.test_mode, disabled, - metadata: req.metadata, + metadata: req.metadata.clone(), frm_configs, connector_label: Some(connector_label.clone()), business_country: req.business_country, @@ -961,6 +961,7 @@ pub async fn create_payment_connector( applepay_verified_domains: None, 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?, }; let transaction_type = match req.connector_type { @@ -1200,6 +1201,7 @@ pub async fn update_payment_connector( expected_format: "auth_type and api_key".to_string(), })?; let metadata = req.metadata.clone().or(mca.metadata.clone()); + let connector_name = mca.connector_name.as_ref(); let connector_enum = api_models::enums::Connector::from_str(connector_name) .change_context(errors::ApiErrorResponse::InvalidDataValue { @@ -1275,6 +1277,10 @@ pub async fn update_payment_connector( applepay_verified_domains: None, pm_auth_config: req.pm_auth_config, status: Some(connector_status), + connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details( + &key_store, &metadata, + ) + .await?, }; // Profile id should always be present diff --git a/crates/router/src/core/apple_pay_certificates_migration.rs b/crates/router/src/core/apple_pay_certificates_migration.rs new file mode 100644 index 00000000000..327358bda50 --- /dev/null +++ b/crates/router/src/core/apple_pay_certificates_migration.rs @@ -0,0 +1,109 @@ +use api_models::apple_pay_certificates_migration; +use common_utils::errors::CustomResult; +use error_stack::ResultExt; +use masking::{PeekInterface, Secret}; + +use super::{ + errors::{self, StorageErrorExt}, + payments::helpers, +}; +use crate::{ + routes::SessionState, + services::{self, logger}, + types::{domain::types as domain_types, storage}, +}; + +pub async fn apple_pay_certificates_migration( + state: SessionState, + req: &apple_pay_certificates_migration::ApplePayCertificatesMigrationRequest, +) -> CustomResult< + services::ApplicationResponse< + apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse, + >, + errors::ApiErrorResponse, +> { + let db = state.store.as_ref(); + + let merchant_id_list = &req.merchant_ids; + + let mut migration_successful_merchant_ids = vec![]; + let mut migration_failed_merchant_ids = vec![]; + + for merchant_id in merchant_id_list { + let key_store = state + .store + .get_merchant_key_store_by_merchant_id( + merchant_id, + &state.store.get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + let merchant_connector_accounts = db + .find_merchant_connector_account_by_merchant_id_and_disabled_list( + merchant_id, + true, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; + + let mut mca_to_update = vec![]; + + for connector_account in merchant_connector_accounts { + let connector_apple_pay_metadata = + helpers::get_applepay_metadata(connector_account.clone().metadata) + .map_err(|error| { + logger::error!( + "Apple pay metadata parsing failed for {:?} in certificates migrations api {:?}", + connector_account.clone().connector_name, + error + ) + }) + .ok(); + if let Some(apple_pay_metadata) = connector_apple_pay_metadata { + let encrypted_apple_pay_metadata = domain_types::encrypt( + Secret::new( + serde_json::to_value(apple_pay_metadata) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to serialize apple pay metadata as JSON")?, + ), + key_store.key.get_inner().peek(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt connector apple pay metadata")?; + + let updated_mca = + storage::MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate { + connector_wallets_details: encrypted_apple_pay_metadata, + }; + + mca_to_update.push((connector_account, updated_mca.into())); + } + } + + let merchant_connector_accounts_update = db + .update_multiple_merchant_connector_accounts(mca_to_update) + .await; + + match merchant_connector_accounts_update { + Ok(_) => { + logger::debug!("Merchant connector accounts updated for merchant id {merchant_id}"); + migration_successful_merchant_ids.push(merchant_id.to_string()); + } + Err(error) => { + logger::debug!( + "Merchant connector accounts update failed with error {error} for merchant id {merchant_id}"); + migration_failed_merchant_ids.push(merchant_id.to_string()); + } + }; + } + + Ok(services::api::ApplicationResponse::Json( + apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse { + migration_successful: migration_successful_merchant_ids, + migration_failed: migration_failed_merchant_ids, + }, + )) +} diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs index 2255e1ff582..704784c485e 100644 --- a/crates/router/src/core/authentication/transformers.rs +++ b/crates/router/src/core/authentication/transformers.rs @@ -153,6 +153,7 @@ pub fn construct_router_data<F: Clone, Req, Res>( address, auth_type: common_enums::AuthenticationType::NoThreeDs, connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: None, access_token: None, session_token: None, 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 74353e83b3d..679a5dad29a 100644 --- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs +++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs @@ -67,6 +67,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC address: self.address.clone(), auth_type: storage_enums::AuthenticationType::NoThreeDs, connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, request: FraudCheckCheckoutData { amount: self.payment_attempt.amount.get_amount_as_i64(), diff --git a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs index f91d87c808c..855b87f3ffb 100644 --- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs +++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs @@ -72,6 +72,7 @@ pub async fn construct_fulfillment_router_data<'a>( address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), 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 b8f8810f09b..ac661231ecc 100644 --- a/crates/router/src/core/fraud_check/flows/record_return.rs +++ b/crates/router/src/core/fraud_check/flows/record_return.rs @@ -65,6 +65,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh address: self.address.clone(), auth_type: storage_enums::AuthenticationType::NoThreeDs, connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, request: FraudCheckRecordReturnData { amount: self.payment_attempt.amount.get_amount_as_i64(), 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 b605c540656..6dbde23e3d2 100644 --- a/crates/router/src/core/fraud_check/flows/sale_flow.rs +++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs @@ -62,6 +62,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp address: self.address.clone(), auth_type: storage_enums::AuthenticationType::NoThreeDs, connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, request: FraudCheckSaleData { amount: self.payment_attempt.amount.get_amount_as_i64(), 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 8c496792a81..4f5d0b30aa9 100644 --- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs +++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs @@ -72,6 +72,7 @@ impl address: self.address.clone(), auth_type: storage_enums::AuthenticationType::NoThreeDs, connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, request: FraudCheckTransactionData { amount: self.payment_attempt.amount.get_amount_as_i64(), diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs index ec438ee6d78..811b69e4562 100644 --- a/crates/router/src/core/mandate/utils.rs +++ b/crates/router/src/core/mandate/utils.rs @@ -44,6 +44,7 @@ pub async fn construct_mandate_revoke_router_data( address: PaymentAddress::default(), auth_type: diesel_models::enums::AuthenticationType::default(), connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, access_token: None, session_token: None, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index caaecdc8629..8ee8dce6393 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1475,44 +1475,47 @@ where // Tokenization Action will be DecryptApplePayToken, only when payment method type is Apple Pay // and the connector supports Apple Pay predecrypt - if matches!( - tokenization_action, - TokenizationAction::DecryptApplePayToken - | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt - ) { - let apple_pay_data = match payment_data.payment_method_data.clone() { - Some(payment_data) => { - let domain_data = domain::PaymentMethodData::from(payment_data); - match domain_data { - domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay( - wallet_data, - )) => Some( - ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data)) - .change_context(errors::ApiErrorResponse::InternalServerError)? - .decrypt(state) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?, - ), - _ => None, + match &tokenization_action { + TokenizationAction::DecryptApplePayToken(payment_processing_details) + | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ) => { + let apple_pay_data = match payment_data.payment_method_data.clone() { + Some(payment_method_data) => { + let domain_data = domain::PaymentMethodData::from(payment_method_data); + match domain_data { + domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay( + wallet_data, + )) => Some( + ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data)) + .change_context(errors::ApiErrorResponse::InternalServerError)? + .decrypt( + &payment_processing_details.payment_processing_certificate, + &payment_processing_details.payment_processing_certificate_key, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?, + ), + _ => None, + } } - } - _ => None, - }; - - let apple_pay_predecrypt = apple_pay_data - .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>( - "ApplePayPredecryptData", - ) - .change_context(errors::ApiErrorResponse::InternalServerError)?; + _ => None, + }; - logger::debug!(?apple_pay_predecrypt); + let apple_pay_predecrypt = apple_pay_data + .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>( + "ApplePayPredecryptData", + ) + .change_context(errors::ApiErrorResponse::InternalServerError)?; - router_data.payment_method_token = Some( - hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt(Box::new( - apple_pay_predecrypt, - )), - ); - } + router_data.payment_method_token = Some( + hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt( + Box::new(apple_pay_predecrypt), + ), + ); + } + _ => (), + }; let pm_token = router_data .add_payment_method_token(state, &connector, &tokenization_action) @@ -2053,7 +2056,7 @@ fn is_payment_method_tokenization_enabled_for_connector( connector_name: &str, payment_method: &storage::enums::PaymentMethod, payment_method_type: &Option<storage::enums::PaymentMethodType>, - apple_pay_flow: &Option<enums::ApplePayFlow>, + apple_pay_flow: &Option<domain::ApplePayFlow>, ) -> RouterResult<bool> { let connector_tokenization_filter = state.conf.tokenization.0.get(connector_name); @@ -2078,13 +2081,13 @@ fn is_payment_method_tokenization_enabled_for_connector( fn is_apple_pay_pre_decrypt_type_connector_tokenization( payment_method_type: &Option<storage::enums::PaymentMethodType>, - apple_pay_flow: &Option<enums::ApplePayFlow>, + apple_pay_flow: &Option<domain::ApplePayFlow>, apple_pay_pre_decrypt_flow_filter: Option<ApplePayPreDecryptFlow>, ) -> bool { match (payment_method_type, apple_pay_flow) { ( Some(storage::enums::PaymentMethodType::ApplePay), - Some(enums::ApplePayFlow::Simplified), + Some(domain::ApplePayFlow::Simplified(_)), ) => !matches!( apple_pay_pre_decrypt_flow_filter, Some(ApplePayPreDecryptFlow::NetworkTokenization) @@ -2094,18 +2097,22 @@ fn is_apple_pay_pre_decrypt_type_connector_tokenization( } fn decide_apple_pay_flow( + state: &SessionState, payment_method_type: &Option<enums::PaymentMethodType>, merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>, -) -> Option<enums::ApplePayFlow> { +) -> Option<domain::ApplePayFlow> { payment_method_type.and_then(|pmt| match pmt { - enums::PaymentMethodType::ApplePay => check_apple_pay_metadata(merchant_connector_account), + enums::PaymentMethodType::ApplePay => { + check_apple_pay_metadata(state, merchant_connector_account) + } _ => None, }) } fn check_apple_pay_metadata( + state: &SessionState, merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>, -) -> Option<enums::ApplePayFlow> { +) -> Option<domain::ApplePayFlow> { merchant_connector_account.and_then(|mca| { let metadata = mca.get_metadata(); metadata.and_then(|apple_pay_metadata| { @@ -2139,14 +2146,34 @@ fn check_apple_pay_metadata( apple_pay_combined, ) => match apple_pay_combined { api_models::payments::ApplePayCombinedMetadata::Simplified { .. } => { - enums::ApplePayFlow::Simplified + domain::ApplePayFlow::Simplified(payments_api::PaymentProcessingDetails { + payment_processing_certificate: state + .conf + .applepay_decrypt_keys + .get_inner() + .apple_pay_ppc + .clone(), + payment_processing_certificate_key: state + .conf + .applepay_decrypt_keys + .get_inner() + .apple_pay_ppc_key + .clone(), + }) } - api_models::payments::ApplePayCombinedMetadata::Manual { .. } => { - enums::ApplePayFlow::Manual + api_models::payments::ApplePayCombinedMetadata::Manual { payment_request_data: _, session_token_data } => { + if let Some(manual_payment_processing_details_at) = session_token_data.payment_processing_details_at { + match manual_payment_processing_details_at { + payments_api::PaymentProcessingDetailsAt::Hyperswitch(payment_processing_details) => domain::ApplePayFlow::Simplified(payment_processing_details), + payments_api::PaymentProcessingDetailsAt::Connector => domain::ApplePayFlow::Manual, + } + } else { + domain::ApplePayFlow::Manual + } } }, api_models::payments::ApplepaySessionTokenMetadata::ApplePay(_) => { - enums::ApplePayFlow::Manual + domain::ApplePayFlow::Manual } }) }) @@ -2173,23 +2200,21 @@ async fn decide_payment_method_tokenize_action( payment_method: &storage::enums::PaymentMethod, pm_parent_token: Option<&String>, is_connector_tokenization_enabled: bool, - apple_pay_flow: Option<enums::ApplePayFlow>, + apple_pay_flow: Option<domain::ApplePayFlow>, ) -> RouterResult<TokenizationAction> { - let is_apple_pay_predecrypt_supported = - matches!(apple_pay_flow, Some(enums::ApplePayFlow::Simplified)); - match pm_parent_token { - None => { - if is_connector_tokenization_enabled && is_apple_pay_predecrypt_supported { - Ok(TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt) - } else if is_connector_tokenization_enabled { - Ok(TokenizationAction::TokenizeInConnectorAndRouter) - } else if is_apple_pay_predecrypt_supported { - Ok(TokenizationAction::DecryptApplePayToken) - } else { - Ok(TokenizationAction::TokenizeInRouter) + None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) { + (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { + TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ) } - } + (true, _) => TokenizationAction::TokenizeInConnectorAndRouter, + (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { + TokenizationAction::DecryptApplePayToken(payment_processing_details) + } + (false, _) => TokenizationAction::TokenizeInRouter, + }), Some(token) => { let redis_conn = state .store @@ -2212,17 +2237,18 @@ async fn decide_payment_method_tokenize_action( match connector_token_option { Some(connector_token) => Ok(TokenizationAction::ConnectorToken(connector_token)), - None => { - if is_connector_tokenization_enabled && is_apple_pay_predecrypt_supported { - Ok(TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt) - } else if is_connector_tokenization_enabled { - Ok(TokenizationAction::TokenizeInConnectorAndRouter) - } else if is_apple_pay_predecrypt_supported { - Ok(TokenizationAction::DecryptApplePayToken) - } else { - Ok(TokenizationAction::TokenizeInRouter) + None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) { + (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { + TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ) } - } + (true, _) => TokenizationAction::TokenizeInConnectorAndRouter, + (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { + TokenizationAction::DecryptApplePayToken(payment_processing_details) + } + (false, _) => TokenizationAction::TokenizeInRouter, + }), } } } @@ -2235,8 +2261,8 @@ pub enum TokenizationAction { TokenizeInConnectorAndRouter, ConnectorToken(String), SkipConnectorTokenization, - DecryptApplePayToken, - TokenizeInConnectorAndApplepayPreDecrypt, + DecryptApplePayToken(payments_api::PaymentProcessingDetails), + TokenizeInConnectorAndApplepayPreDecrypt(payments_api::PaymentProcessingDetails), } #[allow(clippy::too_many_arguments)] @@ -2277,7 +2303,7 @@ where let payment_method_type = &payment_data.payment_attempt.payment_method_type; let apple_pay_flow = - decide_apple_pay_flow(payment_method_type, Some(merchant_connector_account)); + decide_apple_pay_flow(state, payment_method_type, Some(merchant_connector_account)); let is_connector_tokenization_enabled = is_payment_method_tokenization_enabled_for_connector( @@ -2346,12 +2372,14 @@ where TokenizationAction::SkipConnectorTokenization => { TokenizationAction::SkipConnectorTokenization } - TokenizationAction::DecryptApplePayToken => { - TokenizationAction::DecryptApplePayToken - } - TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt => { - TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt + TokenizationAction::DecryptApplePayToken(payment_processing_details) => { + TokenizationAction::DecryptApplePayToken(payment_processing_details) } + TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ), }; (payment_data.to_owned(), connector_tokenization_action) } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 76441f40759..14a3b9327dc 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -166,8 +166,20 @@ async fn create_applepay_session_token( ) } else { // Get the apple pay metadata - let apple_pay_metadata = - helpers::get_applepay_metadata(router_data.connector_meta_data.clone())?; + let connector_apple_pay_wallet_details = + helpers::get_applepay_metadata(router_data.connector_wallets_details.clone()) + .map_err(|error| { + logger::debug!( + "Apple pay connector wallets details parsing failed in create_applepay_session_token {:?}", + error + ) + }) + .ok(); + + let apple_pay_metadata = match connector_apple_pay_wallet_details { + Some(apple_pay_wallet_details) => apple_pay_wallet_details, + None => helpers::get_applepay_metadata(router_data.connector_meta_data.clone())?, + }; // Get payment request data , apple pay session request and merchant keys let ( diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index a58a6ae32b2..6610b048606 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -6,6 +6,7 @@ use api_models::{ }; use base64::Engine; use common_utils::{ + crypto::Encryptable, ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt}, fp_utils, generate_id, id_type, pii, types::MinorUnit, @@ -3169,6 +3170,13 @@ impl MerchantConnectorAccountType { } } + pub fn get_connector_wallets_details(&self) -> Option<masking::Secret<serde_json::Value>> { + match self { + Self::DbVal(val) => val.connector_wallets_details.as_deref().cloned(), + Self::CacheVal(_) => None, + } + } + pub fn is_disabled(&self) -> bool { match self { Self::DbVal(ref inner) => inner.disabled.unwrap_or(false), @@ -3368,6 +3376,7 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>( refund_id: router_data.refund_id, dispute_id: router_data.dispute_id, connector_response: router_data.connector_response, + connector_wallets_details: router_data.connector_wallets_details, } } @@ -3905,17 +3914,32 @@ pub fn validate_customer_access( pub fn is_apple_pay_simplified_flow( connector_metadata: Option<pii::SecretSerdeValue>, + connector_wallets_details: Option<pii::SecretSerdeValue>, connector_name: Option<&String>, ) -> CustomResult<bool, errors::ApiErrorResponse> { - let option_apple_pay_metadata = get_applepay_metadata(connector_metadata) - .map_err(|error| { - logger::info!( - "Apple pay metadata parsing for {:?} in is_apple_pay_simplified_flow {:?}", + let connector_apple_pay_wallet_details = + get_applepay_metadata(connector_wallets_details) + .map_err(|error| { + logger::debug!( + "Apple pay connector wallets details parsing failed for {:?} in is_apple_pay_simplified_flow {:?}", + connector_name, + error + ) + }) + .ok(); + + let option_apple_pay_metadata = match connector_apple_pay_wallet_details { + Some(apple_pay_wallet_details) => Some(apple_pay_wallet_details), + None => get_applepay_metadata(connector_metadata) + .map_err(|error| { + logger::debug!( + "Apple pay metadata parsing failed for {:?} in is_apple_pay_simplified_flow {:?}", connector_name, error ) - }) - .ok(); + }) + .ok(), + }; // return true only if the apple flow type is simplified Ok(matches!( @@ -3928,6 +3952,38 @@ pub fn is_apple_pay_simplified_flow( )) } +pub async fn get_encrypted_apple_pay_connector_wallets_details( + key_store: &domain::MerchantKeyStore, + connector_metadata: &Option<masking::Secret<tera::Value>>, +) -> RouterResult<Option<Encryptable<masking::Secret<serde_json::Value>>>> { + let apple_pay_metadata = get_applepay_metadata(connector_metadata.clone()) + .map_err(|error| { + logger::error!( + "Apple pay metadata parsing failed in get_encrypted_apple_pay_connector_wallets_details {:?}", + error + ) + }) + .ok(); + + let connector_apple_pay_details = apple_pay_metadata + .map(|metadata| { + serde_json::to_value(metadata) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to serialize apple pay metadata as JSON") + }) + .transpose()? + .map(masking::Secret::new); + + let encrypted_connector_apple_pay_details = connector_apple_pay_details + .async_lift(|wallets_details| { + types::encrypt_optional(wallets_details, key_store.key.get_inner().peek()) + }) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while encrypting connector wallets details")?; + Ok(encrypted_connector_apple_pay_details) +} + pub fn get_applepay_metadata( connector_metadata: Option<pii::SecretSerdeValue>, ) -> RouterResult<api_models::payments::ApplepaySessionTokenMetadata> { @@ -3991,6 +4047,7 @@ where let connector_data_list = if is_apple_pay_simplified_flow( merchant_connector_account_type.get_metadata(), + merchant_connector_account_type.get_connector_wallets_details(), merchant_connector_account_type .get_connector_name() .as_ref(), @@ -4010,6 +4067,10 @@ where for merchant_connector_account in merchant_connector_account_list { if is_apple_pay_simplified_flow( merchant_connector_account.metadata, + merchant_connector_account + .connector_wallets_details + .as_deref() + .cloned(), Some(&merchant_connector_account.connector_name), )? { let connector_data = api::ConnectorData::get_connector_by_name( @@ -4064,10 +4125,11 @@ impl ApplePayData { pub async fn decrypt( &self, - state: &SessionState, + payment_processing_certificate: &masking::Secret<String>, + payment_processing_certificate_key: &masking::Secret<String>, ) -> CustomResult<serde_json::Value, errors::ApplePayDecryptionError> { - let merchant_id = self.merchant_id(state).await?; - let shared_secret = self.shared_secret(state).await?; + let merchant_id = self.merchant_id(payment_processing_certificate)?; + let shared_secret = self.shared_secret(payment_processing_certificate_key)?; let symmetric_key = self.symmetric_key(&merchant_id, &shared_secret)?; let decrypted = self.decrypt_ciphertext(&symmetric_key)?; let parsed_decrypted: serde_json::Value = serde_json::from_str(&decrypted) @@ -4075,17 +4137,11 @@ impl ApplePayData { Ok(parsed_decrypted) } - pub async fn merchant_id( + pub fn merchant_id( &self, - state: &SessionState, + payment_processing_certificate: &masking::Secret<String>, ) -> CustomResult<String, errors::ApplePayDecryptionError> { - let cert_data = state - .conf - .applepay_decrypt_keys - .get_inner() - .apple_pay_ppc - .clone() - .expose(); + let cert_data = payment_processing_certificate.clone().expose(); let base64_decode_cert_data = BASE64_ENGINE .decode(cert_data) @@ -4120,9 +4176,9 @@ impl ApplePayData { Ok(apple_pay_m_id) } - pub async fn shared_secret( + pub fn shared_secret( &self, - state: &SessionState, + payment_processing_certificate_key: &masking::Secret<String>, ) -> CustomResult<Vec<u8>, errors::ApplePayDecryptionError> { let public_ec_bytes = BASE64_ENGINE .decode(self.header.ephemeral_public_key.peek().as_bytes()) @@ -4132,13 +4188,7 @@ impl ApplePayData { .change_context(errors::ApplePayDecryptionError::KeyDeserializationFailed) .attach_printable("Failed to deserialize the public key")?; - let decrypted_apple_pay_ppc_key = state - .conf - .applepay_decrypt_keys - .get_inner() - .apple_pay_ppc_key - .clone() - .expose(); + let decrypted_apple_pay_ppc_key = payment_processing_certificate_key.clone().expose(); // Create PKey objects from EcKey let private_key = PKey::private_key_from_pem(decrypted_apple_pay_ppc_key.as_bytes()) diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 48637a0d2b3..7016c7542be 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -727,7 +727,7 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>( ) -> RouterResult<Option<String>> { match tokenization_action { payments::TokenizationAction::TokenizeInConnector - | payments::TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt => { + | payments::TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(_) => { let connector_integration: services::BoxedConnectorIntegration< '_, api::PaymentMethodToken, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 8eca589ca28..02115a529c3 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -125,6 +125,7 @@ where }; let apple_pay_flow = payments::decide_apple_pay_flow( + state, &payment_data.payment_attempt.payment_method_type, Some(merchant_connector_account), ); @@ -154,6 +155,7 @@ where .authentication_type .unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), request: T::try_from(additional_data)?, response, amount_captured: payment_data diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 679838a6dd5..8201a8480c0 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -164,6 +164,7 @@ pub async fn construct_payout_router_data<'a, F>( address, auth_type: enums::AuthenticationType::default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: None, payment_method_status: None, request: types::PayoutsData { @@ -316,6 +317,7 @@ pub async fn construct_refund_router_data<'a, F>( address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), @@ -565,6 +567,7 @@ pub async fn construct_accept_dispute_router_data<'a>( address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), @@ -661,6 +664,7 @@ pub async fn construct_submit_evidence_router_data<'a>( address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), @@ -755,6 +759,7 @@ pub async fn construct_upload_file_router_data<'a>( address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), @@ -853,6 +858,7 @@ pub async fn construct_defend_dispute_router_data<'a>( address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), @@ -942,6 +948,7 @@ pub async fn construct_retrieve_file_router_data<'a>( address: PaymentAddress::default(), auth_type: diesel_models::enums::AuthenticationType::default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: None, payment_method_status: None, request: types::RetrieveFileRequestData { diff --git a/crates/router/src/core/verification/utils.rs b/crates/router/src/core/verification/utils.rs index 7518091ee87..bfbc1cb8b44 100644 --- a/crates/router/src/core/verification/utils.rs +++ b/crates/router/src/core/verification/utils.rs @@ -61,6 +61,7 @@ pub async fn check_existence_and_add_domain_to_db( pm_auth_config: None, connector_label: None, status: None, + connector_wallets_details: None, }; state .store diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs index ad1aafd3125..1394c68cfa8 100644 --- a/crates/router/src/core/webhooks/utils.rs +++ b/crates/router/src/core/webhooks/utils.rs @@ -86,6 +86,7 @@ pub async fn construct_webhook_router_data<'a>( address: PaymentAddress::default(), auth_type: diesel_models::enums::AuthenticationType::default(), connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, request: types::VerifyWebhookSourceRequestData { webhook_headers: request_details.headers.clone(), diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 910ad085f63..19603f81486 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -942,6 +942,17 @@ impl FileMetadataInterface for KafkaStore { #[async_trait::async_trait] impl MerchantConnectorAccountInterface for KafkaStore { + async fn update_multiple_merchant_connector_accounts( + &self, + merchant_connector_accounts: Vec<( + domain::MerchantConnectorAccount, + storage::MerchantConnectorAccountUpdateInternal, + )>, + ) -> CustomResult<(), errors::StorageError> { + self.diesel_store + .update_multiple_merchant_connector_accounts(merchant_connector_accounts) + .await + } async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, merchant_id: &str, diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index aea37b517be..ab66b52c32d 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -1,4 +1,6 @@ +use async_bb8_diesel::AsyncConnection; use common_utils::ext_traits::{AsyncExt, ByteSliceExt, Encode}; +use diesel_models::encryption::Encryption; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] @@ -165,6 +167,14 @@ where key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>; + async fn update_multiple_merchant_connector_accounts( + &self, + this: Vec<( + domain::MerchantConnectorAccount, + storage::MerchantConnectorAccountUpdateInternal, + )>, + ) -> CustomResult<(), errors::StorageError>; + async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &str, @@ -381,6 +391,104 @@ impl MerchantConnectorAccountInterface for Store { .await } + #[instrument(skip_all)] + async fn update_multiple_merchant_connector_accounts( + &self, + merchant_connector_accounts: Vec<( + domain::MerchantConnectorAccount, + storage::MerchantConnectorAccountUpdateInternal, + )>, + ) -> CustomResult<(), errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + + async fn update_call( + connection: &diesel_models::PgPooledConn, + (merchant_connector_account, mca_update): ( + domain::MerchantConnectorAccount, + storage::MerchantConnectorAccountUpdateInternal, + ), + ) -> Result<(), error_stack::Report<storage_impl::errors::StorageError>> { + Conversion::convert(merchant_connector_account) + .await + .change_context(errors::StorageError::EncryptionError)? + .update(connection, mca_update) + .await + .map_err(|error| report!(errors::StorageError::from(error)))?; + Ok(()) + } + + conn.transaction_async(|connection_pool| async move { + for (merchant_connector_account, update_merchant_connector_account) in + merchant_connector_accounts + { + let _connector_name = merchant_connector_account.connector_name.clone(); + let _profile_id = merchant_connector_account.profile_id.clone().ok_or( + errors::StorageError::ValueNotFound("profile_id".to_string()), + )?; + + let _merchant_id = merchant_connector_account.merchant_id.clone(); + let _merchant_connector_id = + merchant_connector_account.merchant_connector_id.clone(); + + let update = update_call( + &connection_pool, + ( + merchant_connector_account, + update_merchant_connector_account, + ), + ); + + #[cfg(feature = "accounts_cache")] + // Redact all caches as any of might be used because of backwards compatibility + cache::publish_and_redact_multiple( + self, + [ + cache::CacheKind::Accounts( + format!("{}_{}", _profile_id, _connector_name).into(), + ), + cache::CacheKind::Accounts( + format!("{}_{}", _merchant_id, _merchant_connector_id).into(), + ), + cache::CacheKind::CGraph( + format!("cgraph_{}_{_profile_id}", _merchant_id).into(), + ), + ], + || update, + ) + .await + .map_err(|error| { + // Returning `DatabaseConnectionError` after logging the actual error because + // -> it is not possible to get the underlying from `error_stack::Report<C>` + // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>` + // because of Rust's orphan rules + router_env::logger::error!( + ?error, + "DB transaction for updating multiple merchant connector account failed" + ); + errors::StorageError::DatabaseConnectionError + })?; + + #[cfg(not(feature = "accounts_cache"))] + { + update.await.map_err(|error| { + // Returning `DatabaseConnectionError` after logging the actual error because + // -> it is not possible to get the underlying from `error_stack::Report<C>` + // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>` + // because of Rust's orphan rules + router_env::logger::error!( + ?error, + "DB transaction for updating multiple merchant connector account failed" + ); + errors::StorageError::DatabaseConnectionError + })?; + } + } + Ok::<_, errors::StorageError>(()) + }) + .await?; + Ok(()) + } + #[instrument(skip_all)] async fn update_merchant_connector_account( &self, @@ -417,7 +525,7 @@ impl MerchantConnectorAccountInterface for Store { #[cfg(feature = "accounts_cache")] { - // Redact both the caches as any one or both might be used because of backwards compatibility + // Redact all caches as any of might be used because of backwards compatibility cache::publish_and_redact_multiple( self, [ @@ -502,6 +610,17 @@ impl MerchantConnectorAccountInterface for Store { #[async_trait::async_trait] impl MerchantConnectorAccountInterface for MockDb { + async fn update_multiple_merchant_connector_accounts( + &self, + _merchant_connector_accounts: Vec<( + domain::MerchantConnectorAccount, + storage::MerchantConnectorAccountUpdateInternal, + )>, + ) -> CustomResult<(), errors::StorageError> { + // No need to implement this function for `MockDb` as this function will be removed after the + // apple pay certificate migration + Err(errors::StorageError::MockDbError)? + } async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, merchant_id: &str, @@ -658,6 +777,7 @@ impl MerchantConnectorAccountInterface for MockDb { applepay_verified_domains: t.applepay_verified_domains, pm_auth_config: t.pm_auth_config, status: t.status, + connector_wallets_details: t.connector_wallets_details.map(Encryption::from), }; accounts.push(account.clone()); account @@ -857,6 +977,14 @@ mod merchant_connector_account_cache_tests { applepay_verified_domains: None, pm_auth_config: None, status: common_enums::ConnectorStatus::Inactive, + connector_wallets_details: Some( + domain::types::encrypt( + serde_json::Value::default().into(), + merchant_key.key.get_inner().peek(), + ) + .await + .unwrap(), + ), }; db.insert_merchant_connector_account(mca.clone(), &merchant_key) diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 7344b85d150..73ec0f1635d 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -144,6 +144,7 @@ pub fn mk_app( .service(routes::Routing::server(state.clone())) .service(routes::Blocklist::server(state.clone())) .service(routes::Gsm::server(state.clone())) + .service(routes::ApplePayCertificatesMigration::server(state.clone())) .service(routes::PaymentLink::server(state.clone())) .service(routes::User::server(state.clone())) .service(routes::ConnectorOnboarding::server(state.clone())) diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index 9f13635ca90..cb229b5c802 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -1,6 +1,7 @@ pub mod admin; pub mod api_keys; pub mod app; +pub mod apple_pay_certificates_migration; #[cfg(feature = "olap")] pub mod blocklist; pub mod cache; @@ -58,10 +59,10 @@ pub use self::app::Payouts; #[cfg(all(feature = "olap", feature = "recon"))] pub use self::app::Recon; pub use self::app::{ - ApiKeys, AppState, BusinessProfile, Cache, Cards, Configs, ConnectorOnboarding, Customers, - Disputes, EphemeralKey, Files, Gsm, Health, Mandates, MerchantAccount, - MerchantConnectorAccount, PaymentLink, PaymentMethods, Payments, Poll, Refunds, SessionState, - User, Webhooks, + ApiKeys, AppState, ApplePayCertificatesMigration, BusinessProfile, Cache, Cards, Configs, + ConnectorOnboarding, Customers, Disputes, EphemeralKey, Files, Gsm, Health, Mandates, + MerchantAccount, MerchantConnectorAccount, PaymentLink, PaymentMethods, Payments, Poll, + Refunds, SessionState, User, Webhooks, }; #[cfg(feature = "olap")] pub use self::app::{Blocklist, Routing, Verify, WebhookEvents}; diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 2d1b77460a5..cd392756505 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -413,7 +413,7 @@ pub async fn payment_connector_delete( merchant_connector_id, }) .into_inner(); - api::server_wrap( + Box::pin(api::server_wrap( flow, state, &req, @@ -430,7 +430,7 @@ pub async fn payment_connector_delete( req.headers(), ), api_locking::LockAction::NotApplicable, - ) + )) .await } /// Merchant Account - Toggle KV diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 5af3a2bef25..5438535a15c 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -29,8 +29,8 @@ use super::routing as cloud_routing; use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains}; #[cfg(feature = "olap")] use super::{ - admin::*, api_keys::*, connector_onboarding::*, disputes::*, files::*, gsm::*, payment_link::*, - user::*, user_role::*, webhook_events::*, + admin::*, api_keys::*, apple_pay_certificates_migration, connector_onboarding::*, disputes::*, + files::*, gsm::*, payment_link::*, user::*, user_role::*, webhook_events::*, }; use super::{cache::*, health::*}; #[cfg(any(feature = "olap", feature = "oltp"))] @@ -1117,6 +1117,19 @@ impl Configs { } } +pub struct ApplePayCertificatesMigration; + +#[cfg(feature = "olap")] +impl ApplePayCertificatesMigration { + pub fn server(state: AppState) -> Scope { + web::scope("/apple_pay_certificates_migration") + .app_data(web::Data::new(state)) + .service(web::resource("").route( + web::post().to(apple_pay_certificates_migration::apple_pay_certificates_migration), + )) + } +} + pub struct Poll; #[cfg(feature = "oltp")] diff --git a/crates/router/src/routes/apple_pay_certificates_migration.rs b/crates/router/src/routes/apple_pay_certificates_migration.rs new file mode 100644 index 00000000000..8c9d507ba41 --- /dev/null +++ b/crates/router/src/routes/apple_pay_certificates_migration.rs @@ -0,0 +1,30 @@ +use actix_web::{web, HttpRequest, HttpResponse}; +use router_env::Flow; + +use super::AppState; +use crate::{ + core::{api_locking, apple_pay_certificates_migration}, + services::{api, authentication as auth}, +}; + +pub async fn apple_pay_certificates_migration( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json< + api_models::apple_pay_certificates_migration::ApplePayCertificatesMigrationRequest, + >, +) -> HttpResponse { + let flow = Flow::ApplePayCertificatesMigration; + Box::pin(api::server_wrap( + flow, + state, + &req, + &json_payload.into_inner(), + |state, _, req, _| { + apple_pay_certificates_migration::apple_pay_certificates_migration(state, req) + }, + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index b4b9658a7e0..a64343757b5 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -35,6 +35,7 @@ pub enum ApiIdentifier { ConnectorOnboarding, Recon, Poll, + ApplePayCertificatesMigration, } impl From<Flow> for ApiIdentifier { @@ -186,6 +187,8 @@ impl From<Flow> for ApiIdentifier { | Flow::GsmRuleUpdate | Flow::GsmRuleDelete => Self::Gsm, + Flow::ApplePayCertificatesMigration => Self::ApplePayCertificatesMigration, + Flow::UserConnectAccount | Flow::UserSignUp | Flow::UserSignIn diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index e17ec791637..21aea14caf5 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -805,6 +805,7 @@ impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2) address: data.address.clone(), auth_type: data.auth_type, connector_meta_data: data.connector_meta_data.clone(), + connector_wallets_details: data.connector_wallets_details.clone(), amount_captured: data.amount_captured, access_token: data.access_token.clone(), response: data.response.clone(), @@ -865,6 +866,7 @@ impl<F1, F2> address: data.address.clone(), auth_type: data.auth_type, connector_meta_data: data.connector_meta_data.clone(), + connector_wallets_details: data.connector_wallets_details.clone(), amount_captured: data.amount_captured, access_token: data.access_token.clone(), response: data.response.clone(), diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index 0b932f9aeb1..7e296d0b4a8 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -85,6 +85,7 @@ impl VerifyConnectorData { connector_customer: None, connector_auth_type: self.connector_auth.clone(), connector_meta_data: None, + connector_wallets_details: None, payment_method_token: None, connector_api_version: None, recurring_mandate_payment_data: None, diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs index 0e7f5b081c3..6c2f6a06e1e 100644 --- a/crates/router/src/types/domain/merchant_connector_account.rs +++ b/crates/router/src/types/domain/merchant_connector_account.rs @@ -11,7 +11,10 @@ use diesel_models::{ use error_stack::ResultExt; use masking::{PeekInterface, Secret}; -use super::{behaviour, types::TypeEncryption}; +use super::{ + behaviour, + types::{self, AsyncLift, TypeEncryption}, +}; #[derive(Clone, Debug)] pub struct MerchantConnectorAccount { pub id: Option<i32>, @@ -36,6 +39,7 @@ pub struct MerchantConnectorAccount { pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, pub status: enums::ConnectorStatus, + pub connector_wallets_details: Option<Encryptable<Secret<serde_json::Value>>>, } #[derive(Debug)] @@ -56,6 +60,10 @@ pub enum MerchantConnectorAccountUpdate { pm_auth_config: Option<serde_json::Value>, connector_label: Option<String>, status: Option<enums::ConnectorStatus>, + connector_wallets_details: Option<Encryptable<Secret<serde_json::Value>>>, + }, + ConnectorWalletDetailsUpdate { + connector_wallets_details: Encryptable<Secret<serde_json::Value>>, }, } @@ -92,6 +100,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, status: self.status, + connector_wallets_details: self.connector_wallets_details.map(Encryption::from), }, ) } @@ -132,6 +141,13 @@ impl behaviour::Conversion for MerchantConnectorAccount { applepay_verified_domains: other.applepay_verified_domains, pm_auth_config: other.pm_auth_config, status: other.status, + connector_wallets_details: other + .connector_wallets_details + .async_lift(|inner| types::decrypt(inner, key.peek())) + .await + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting connector wallets details".to_string(), + })?, }) } @@ -160,6 +176,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, status: self.status, + connector_wallets_details: self.connector_wallets_details.map(Encryption::from), }) } } @@ -183,6 +200,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte pm_auth_config, connector_label, status, + connector_wallets_details, } => Self { merchant_id, connector_type, @@ -201,6 +219,29 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte pm_auth_config, connector_label, status, + connector_wallets_details: connector_wallets_details.map(Encryption::from), + }, + MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate { + connector_wallets_details, + } => Self { + connector_wallets_details: Some(Encryption::from(connector_wallets_details)), + merchant_id: None, + connector_type: None, + connector_name: None, + connector_account_details: None, + connector_label: None, + test_mode: None, + disabled: None, + merchant_connector_id: None, + payment_methods_enabled: None, + frm_configs: None, + metadata: None, + modified_at: None, + connector_webhook_details: None, + frm_config: None, + applepay_verified_domains: None, + pm_auth_config: None, + status: None, }, } } diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs index 51d3210a70f..021505c644f 100644 --- a/crates/router/src/types/domain/payments.rs +++ b/crates/router/src/types/domain/payments.rs @@ -1,10 +1,10 @@ pub use hyperswitch_domain_models::payment_method_data::{ - AliPayQr, ApplePayThirdPartySdkData, ApplePayWalletData, ApplepayPaymentMethod, BankDebitData, - BankRedirectData, BankTransferData, BoletoVoucherData, Card, CardRedirectData, CardToken, - CashappQr, CryptoData, GcashRedirection, GiftCardData, GiftCardDetails, GoPayRedirection, - GooglePayPaymentMethodInfo, GooglePayRedirectData, GooglePayThirdPartySdkData, - GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData, KakaoPayRedirection, - MbWayRedirection, PayLaterData, PaymentMethodData, SamsungPayWalletData, + AliPayQr, ApplePayFlow, ApplePayThirdPartySdkData, ApplePayWalletData, ApplepayPaymentMethod, + BankDebitData, BankRedirectData, BankTransferData, BoletoVoucherData, Card, CardRedirectData, + CardToken, CashappQr, CryptoData, GcashRedirection, GiftCardData, GiftCardDetails, + GoPayRedirection, GooglePayPaymentMethodInfo, GooglePayRedirectData, + GooglePayThirdPartySdkData, GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData, + KakaoPayRedirection, MbWayRedirection, PayLaterData, PaymentMethodData, SamsungPayWalletData, SepaAndBacsBillingDetails, SwishQrData, TouchNGoRedirection, UpiCollectData, UpiData, UpiIntentData, VoucherData, WalletData, WeChatPayQr, }; diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index b83d3138b7c..e71219b6a9e 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -707,13 +707,13 @@ impl CustomerAddress for api_models::customers::CustomerRequest { } pub fn add_apple_pay_flow_metrics( - apple_pay_flow: &Option<enums::ApplePayFlow>, + apple_pay_flow: &Option<domain::ApplePayFlow>, connector: Option<String>, merchant_id: String, ) { if let Some(flow) = apple_pay_flow { match flow { - enums::ApplePayFlow::Simplified => metrics::APPLE_PAY_SIMPLIFIED_FLOW.add( + domain::ApplePayFlow::Simplified(_) => metrics::APPLE_PAY_SIMPLIFIED_FLOW.add( &metrics::CONTEXT, 1, &[ @@ -724,7 +724,7 @@ pub fn add_apple_pay_flow_metrics( metrics::request::add_attributes("merchant_id", merchant_id.to_owned()), ], ), - enums::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW.add( + domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW.add( &metrics::CONTEXT, 1, &[ @@ -741,14 +741,14 @@ pub fn add_apple_pay_flow_metrics( pub fn add_apple_pay_payment_status_metrics( payment_attempt_status: enums::AttemptStatus, - apple_pay_flow: Option<enums::ApplePayFlow>, + apple_pay_flow: Option<domain::ApplePayFlow>, connector: Option<String>, merchant_id: String, ) { if payment_attempt_status == enums::AttemptStatus::Charged { if let Some(flow) = apple_pay_flow { match flow { - enums::ApplePayFlow::Simplified => { + domain::ApplePayFlow::Simplified(_) => { metrics::APPLE_PAY_SIMPLIFIED_FLOW_SUCCESSFUL_PAYMENT.add( &metrics::CONTEXT, 1, @@ -761,7 +761,7 @@ pub fn add_apple_pay_payment_status_metrics( ], ) } - enums::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT + domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT .add( &metrics::CONTEXT, 1, @@ -778,7 +778,7 @@ pub fn add_apple_pay_payment_status_metrics( } else if payment_attempt_status == enums::AttemptStatus::Failure { if let Some(flow) = apple_pay_flow { match flow { - enums::ApplePayFlow::Simplified => { + domain::ApplePayFlow::Simplified(_) => { metrics::APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT.add( &metrics::CONTEXT, 1, @@ -791,7 +791,7 @@ pub fn add_apple_pay_payment_status_metrics( ], ) } - enums::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT.add( + domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT.add( &metrics::CONTEXT, 1, &[ diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 10e8b366530..b01c5abb968 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -97,6 +97,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { None, ), connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, access_token: None, session_token: None, @@ -159,6 +160,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { response: Err(types::ErrorResponse::default()), address: PaymentAddress::default(), connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, access_token: None, session_token: None, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 0de19f17b54..be86d377299 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -540,6 +540,7 @@ pub trait ConnectorActions: Connector { connector_meta_data: info .clone() .and_then(|a| a.connector_meta_data.map(Secret::new)), + connector_wallets_details: None, amount_captured: None, access_token: info.clone().and_then(|a| a.access_token), session_token: None, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 110532f524d..51f762e3713 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -298,6 +298,8 @@ pub enum Flow { GsmRuleRetrieve, /// Gsm Rule Update flow GsmRuleUpdate, + /// Apple pay certificates migration + ApplePayCertificatesMigration, /// Gsm Rule Delete flow GsmRuleDelete, /// User Sign Up diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index 4356b6b7997..b153c47b882 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -101,6 +101,12 @@ impl From<error_stack::Report<RedisError>> for StorageError { } } +impl From<diesel::result::Error> for StorageError { + fn from(err: diesel::result::Error) -> Self { + Self::from(error_stack::report!(DatabaseError::from(err))) + } +} + impl From<error_stack::Report<DatabaseError>> for StorageError { fn from(err: error_stack::Report<DatabaseError>) -> Self { Self::DatabaseError(err) diff --git a/migrations/2024-05-28-054439_connector_wallets_details/down.sql b/migrations/2024-05-28-054439_connector_wallets_details/down.sql new file mode 100644 index 00000000000..dea26bbd1eb --- /dev/null +++ b/migrations/2024-05-28-054439_connector_wallets_details/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE merchant_connector_account DROP COLUMN IF EXISTS connector_wallets_details; \ No newline at end of file diff --git a/migrations/2024-05-28-054439_connector_wallets_details/up.sql b/migrations/2024-05-28-054439_connector_wallets_details/up.sql new file mode 100644 index 00000000000..c75de9204df --- /dev/null +++ b/migrations/2024-05-28-054439_connector_wallets_details/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS connector_wallets_details BYTEA DEFAULT NULL; \ No newline at end of file diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index f42481798a4..ba0d8946192 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -13697,6 +13697,63 @@ }, "additionalProperties": false }, + "PaymentProcessingDetails": { + "type": "object", + "required": [ + "payment_processing_certificate", + "payment_processing_certificate_key" + ], + "properties": { + "payment_processing_certificate": { + "type": "string" + }, + "payment_processing_certificate_key": { + "type": "string" + } + } + }, + "PaymentProcessingDetailsAt": { + "oneOf": [ + { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentProcessingDetails" + }, + { + "type": "object", + "required": [ + "payment_processing_details_at" + ], + "properties": { + "payment_processing_details_at": { + "type": "string", + "enum": [ + "Hyperswitch" + ] + } + } + } + ] + }, + { + "type": "object", + "required": [ + "payment_processing_details_at" + ], + "properties": { + "payment_processing_details_at": { + "type": "string", + "enum": [ + "Connector" + ] + } + } + } + ], + "discriminator": { + "propertyName": "payment_processing_details_at" + } + }, "PaymentRetrieveBody": { "type": "object", "properties": { @@ -18394,43 +18451,55 @@ } }, "SessionTokenInfo": { - "type": "object", - "required": [ - "certificate", - "certificate_keys", - "merchant_identifier", - "display_name", - "initiative", - "initiative_context" - ], - "properties": { - "certificate": { - "type": "string" - }, - "certificate_keys": { - "type": "string" - }, - "merchant_identifier": { - "type": "string" - }, - "display_name": { - "type": "string" - }, - "initiative": { - "type": "string" - }, - "initiative_context": { - "type": "string" - }, - "merchant_business_country": { + "allOf": [ + { "allOf": [ { - "$ref": "#/components/schemas/CountryAlpha2" + "$ref": "#/components/schemas/PaymentProcessingDetailsAt" } ], "nullable": true + }, + { + "type": "object", + "required": [ + "certificate", + "certificate_keys", + "merchant_identifier", + "display_name", + "initiative", + "initiative_context" + ], + "properties": { + "certificate": { + "type": "string" + }, + "certificate_keys": { + "type": "string" + }, + "merchant_identifier": { + "type": "string" + }, + "display_name": { + "type": "string" + }, + "initiative": { + "type": "string" + }, + "initiative_context": { + "type": "string" + }, + "merchant_business_country": { + "allOf": [ + { + "$ref": "#/components/schemas/CountryAlpha2" + } + ], + "nullable": true + } + } } - } + ] }, "StraightThroughAlgorithm": { "oneOf": [
2024-05-28T13:19:09Z
## Description <!-- Describe your changes in detail --> Currently apple pay related details are being stored in the connector metadata, as in future we are going to add apple pay decrypted flow support for ios app we will be collecting the apple pay payment processing certificates as well. As this ppc and ppc key needs to be securely stored, we need to move the existing certificates to a new column which stores the encrypted certificates. This pr adds a api end point (`/apple_pay_certificates_migration`) to migrate the apple pay details form the merchant connector account `metadata` to the newly added column connector (`connector_wallets_details`). This api takes list of `merchant_ids` as input and then lists all the configured merchant connector accounts for that merchant id. After which it checks for the apple pay details in the metadata in the merchant connector account, if present it is encrypted by merchant's DEK (Data Encryption Key) and will be stored in the newly added column (`connector_wallets_details`) in the merchant connector account. Response contains the list of merchant_ids for migration succeeded (`migration_successful`) and failed (`migraiton_failed`). ### 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)? --> -> Apple pay certificate migration api ``` curl --location 'http://localhost:8080/apple_pay_certificates_migration' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "merchant_ids": ["merchant_1713176513", "merchant_1714122879"] }' ``` <img width="719" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/bb66cc2c-69f7-4c6e-bb3c-1e184944bbd2"> -> Check the db for connector_wallets_details of mca belonging to above merchants <img width="862" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/24d5c9ed-f091-49cd-983b-839724024118"> -> Create MCA with apple pay `simplified` and manual `flow` metadata for apple pay `simplified` ``` "apple_pay_combined": { "simplified": { "session_token_data": { "initiative_context": "sdk-test-app.netlify.app", "merchant_business_country": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` metadata for apple pay `manual` flow ``` "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "", "display_name": "applepay", "certificate_keys": "", "merchant_business_coountry": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` -> Confirm an apple pay payment with above flows <img width="1159" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/a70ebc44-948a-421d-bcdf-3f9a2adb4361"> -> Create a apple pay payment with the below metadata ``` "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "", "display_name": "applepay", "certificate_keys": "", "payment_processing_details_at": "Hyperswitch", "payment_processing_certificate": "", "payment_processing_certificate_key": "", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "", "merchant_business_coountry": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` -> Confirm apple pay payment <img width="1055" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4460d4e3-24e9-4348-ac1c-c05d6bef5e3e">
d242850b63173f314fb259451139464f09e0a9e9
-> Apple pay certificate migration api ``` curl --location 'http://localhost:8080/apple_pay_certificates_migration' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "merchant_ids": ["merchant_1713176513", "merchant_1714122879"] }' ``` <img width="719" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/bb66cc2c-69f7-4c6e-bb3c-1e184944bbd2"> -> Check the db for connector_wallets_details of mca belonging to above merchants <img width="862" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/24d5c9ed-f091-49cd-983b-839724024118"> -> Create MCA with apple pay `simplified` and manual `flow` metadata for apple pay `simplified` ``` "apple_pay_combined": { "simplified": { "session_token_data": { "initiative_context": "sdk-test-app.netlify.app", "merchant_business_country": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` metadata for apple pay `manual` flow ``` "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "", "display_name": "applepay", "certificate_keys": "", "merchant_business_coountry": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` -> Confirm an apple pay payment with above flows <img width="1159" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/a70ebc44-948a-421d-bcdf-3f9a2adb4361"> -> Create a apple pay payment with the below metadata ``` "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "", "display_name": "applepay", "certificate_keys": "", "payment_processing_details_at": "Hyperswitch", "payment_processing_certificate": "", "payment_processing_certificate_key": "", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "", "merchant_business_coountry": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` -> Confirm apple pay payment <img width="1055" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4460d4e3-24e9-4348-ac1c-c05d6bef5e3e">
[ "crates/api_models/src/apple_pay_certificates_migration.rs", "crates/api_models/src/events.rs", "crates/api_models/src/events/apple_pay_certificates_migration.rs", "crates/api_models/src/lib.rs", "crates/api_models/src/payments.rs", "crates/common_enums/src/enums.rs", "crates/common_utils/src/events.rs"...
juspay/hyperswitch
juspay__hyperswitch-4791
Bug: Add a column (connector_wallets_details) in merchant connector account and develop an api (migrate cert) to store the encrypted certificates in the added column. Currently apple pay related details are being stored in the connector metadata, as in future we are going to add apple pay decrypted flow support for ios app we will be collecting the apple pay payment processing certificates as well. As this ppc and ppc key needs to be securely stored, we need to move the existing certificates to a new column which stores the encrypted certificates.
diff --git a/crates/api_models/src/apple_pay_certificates_migration.rs b/crates/api_models/src/apple_pay_certificates_migration.rs new file mode 100644 index 00000000000..796734f53e4 --- /dev/null +++ b/crates/api_models/src/apple_pay_certificates_migration.rs @@ -0,0 +1,12 @@ +#[derive(Debug, Clone, serde::Serialize)] +pub struct ApplePayCertificatesMigrationResponse { + pub migration_successful: Vec<String>, + pub migration_failed: Vec<String>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +pub struct ApplePayCertificatesMigrationRequest { + pub merchant_ids: Vec<String>, +} + +impl common_utils::events::ApiEventMetric for ApplePayCertificatesMigrationRequest {} diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 9c26576e77b..078c27e6db9 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -1,3 +1,4 @@ +pub mod apple_pay_certificates_migration; pub mod connector_onboarding; pub mod customer; pub mod dispute; diff --git a/crates/api_models/src/events/apple_pay_certificates_migration.rs b/crates/api_models/src/events/apple_pay_certificates_migration.rs new file mode 100644 index 00000000000..f194443bea0 --- /dev/null +++ b/crates/api_models/src/events/apple_pay_certificates_migration.rs @@ -0,0 +1,9 @@ +use common_utils::events::ApiEventMetric; + +use crate::apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse; + +impl ApiEventMetric for ApplePayCertificatesMigrationResponse { + fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { + Some(common_utils::events::ApiEventsType::ApplePayCertificatesMigration) + } +} diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index a0bc6f6362d..d6d6deaa235 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -2,6 +2,7 @@ pub mod admin; pub mod analytics; pub mod api_keys; +pub mod apple_pay_certificates_migration; pub mod blocklist; pub mod cards_info; pub mod conditional_configs; diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index cda13289aa5..8ccfa14eaf6 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4208,6 +4208,23 @@ pub struct SessionTokenInfo { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, + #[serde(flatten)] + pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +#[serde(tag = "payment_processing_details_at")] +pub enum PaymentProcessingDetailsAt { + Hyperswitch(PaymentProcessingDetails), + Connector, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] +pub struct PaymentProcessingDetails { + #[schema(value_type = String)] + pub payment_processing_certificate: Secret<String>, + #[schema(value_type = String)] + pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 3df291d5681..f20d2b821dd 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2284,11 +2284,6 @@ pub enum ReconStatus { Active, Disabled, } -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ApplePayFlow { - Simplified, - Manual, -} #[derive( Clone, diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index 8939e07a76c..1052840dbc8 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -50,6 +50,7 @@ pub enum ApiEventsType { // TODO: This has to be removed once the corresponding apiEventTypes are created Miscellaneous, RustLocker, + ApplePayCertificatesMigration, FraudCheck, Recon, Dispute { diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index d7c505f7942..b411b1a7acd 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -67,7 +67,7 @@ pub enum ConnectorAuthType { #[derive(Debug, Deserialize, serde::Serialize, Clone)] #[serde(untagged)] pub enum ApplePayTomlConfig { - Standard(payments::ApplePayMetadata), + Standard(Box<payments::ApplePayMetadata>), Zen(ZenApplePay), } diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs index e45ef002626..680e3dacc85 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 connector_wallets_details: Option<Encryption>, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -72,6 +73,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 connector_wallets_details: Option<Encryption>, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] @@ -96,6 +98,7 @@ pub struct MerchantConnectorAccountUpdateInternal { pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, pub status: Option<storage_enums::ConnectorStatus>, + pub connector_wallets_details: Option<Encryption>, } impl MerchantConnectorAccountUpdateInternal { diff --git a/crates/diesel_models/src/query/generics.rs b/crates/diesel_models/src/query/generics.rs index 0527ff3a181..682766679fd 100644 --- a/crates/diesel_models/src/query/generics.rs +++ b/crates/diesel_models/src/query/generics.rs @@ -166,7 +166,8 @@ where } Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound)) .attach_printable_lazy(|| format!("Error while updating {debug_values}")), - _ => Err(report!(errors::DatabaseError::Others)) + Err(error) => Err(error) + .change_context(errors::DatabaseError::Others) .attach_printable_lazy(|| format!("Error while updating {debug_values}")), } } @@ -252,7 +253,8 @@ where } Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound)) .attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")), - _ => Err(report!(errors::DatabaseError::Others)) + Err(error) => Err(error) + .change_context(errors::DatabaseError::Others) .attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")), } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 6074fdc10b7..7baaa337259 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -679,6 +679,7 @@ diesel::table! { applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, pm_auth_config -> Nullable<Jsonb>, status -> ConnectorStatus, + connector_wallets_details -> Nullable<Bytea>, } } diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 065290b6b2d..8dca0c86a2a 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -22,6 +22,12 @@ pub enum PaymentMethodData { CardToken(CardToken), } +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ApplePayFlow { + Simplified(api_models::payments::PaymentProcessingDetails), + Manual, +} + impl PaymentMethodData { pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> { match self { diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index b5d96a5c53f..00e13f5fce9 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -3,7 +3,7 @@ use std::{collections::HashMap, marker::PhantomData}; use common_utils::id_type; use masking::Secret; -use crate::payment_address::PaymentAddress; +use crate::{payment_address::PaymentAddress, payment_method_data}; #[derive(Debug, Clone)] pub struct RouterData<Flow, Request, Response> { @@ -22,6 +22,7 @@ pub struct RouterData<Flow, Request, Response> { pub address: PaymentAddress, pub auth_type: common_enums::enums::AuthenticationType, pub connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, + pub connector_wallets_details: Option<common_utils::pii::SecretSerdeValue>, pub amount_captured: Option<i64>, pub access_token: Option<AccessToken>, pub session_token: Option<String>, @@ -56,7 +57,7 @@ pub struct RouterData<Flow, Request, Response> { pub connector_http_status_code: Option<u16>, pub external_latency: Option<u128>, /// Contains apple pay flow type simplified or manual - pub apple_pay_flow: Option<common_enums::enums::ApplePayFlow>, + pub apple_pay_flow: Option<payment_method_data::ApplePayFlow>, pub frm_metadata: Option<common_utils::pii::SecretSerdeValue>, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 237cddcf94e..f4fc5fc8473 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -309,6 +309,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::FeatureMetadata, api_models::payments::ApplepayConnectorMetadataRequest, api_models::payments::SessionTokenInfo, + api_models::payments::PaymentProcessingDetailsAt, + api_models::payments::PaymentProcessingDetails, api_models::payments::SwishQrData, api_models::payments::AirwallexData, api_models::payments::NoonData, diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 02a5873429f..53787fe04ab 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -1,6 +1,7 @@ pub mod admin; pub mod api_keys; pub mod api_locking; +pub mod apple_pay_certificates_migration; pub mod authentication; pub mod blocklist; pub mod cache; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 6b582c2c957..0578945006f 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -937,7 +937,7 @@ pub async fn create_payment_connector( payment_methods_enabled, test_mode: req.test_mode, disabled, - metadata: req.metadata, + metadata: req.metadata.clone(), frm_configs, connector_label: Some(connector_label.clone()), business_country: req.business_country, @@ -961,6 +961,7 @@ pub async fn create_payment_connector( applepay_verified_domains: None, 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?, }; let transaction_type = match req.connector_type { @@ -1200,6 +1201,7 @@ pub async fn update_payment_connector( expected_format: "auth_type and api_key".to_string(), })?; let metadata = req.metadata.clone().or(mca.metadata.clone()); + let connector_name = mca.connector_name.as_ref(); let connector_enum = api_models::enums::Connector::from_str(connector_name) .change_context(errors::ApiErrorResponse::InvalidDataValue { @@ -1275,6 +1277,10 @@ pub async fn update_payment_connector( applepay_verified_domains: None, pm_auth_config: req.pm_auth_config, status: Some(connector_status), + connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details( + &key_store, &metadata, + ) + .await?, }; // Profile id should always be present diff --git a/crates/router/src/core/apple_pay_certificates_migration.rs b/crates/router/src/core/apple_pay_certificates_migration.rs new file mode 100644 index 00000000000..327358bda50 --- /dev/null +++ b/crates/router/src/core/apple_pay_certificates_migration.rs @@ -0,0 +1,109 @@ +use api_models::apple_pay_certificates_migration; +use common_utils::errors::CustomResult; +use error_stack::ResultExt; +use masking::{PeekInterface, Secret}; + +use super::{ + errors::{self, StorageErrorExt}, + payments::helpers, +}; +use crate::{ + routes::SessionState, + services::{self, logger}, + types::{domain::types as domain_types, storage}, +}; + +pub async fn apple_pay_certificates_migration( + state: SessionState, + req: &apple_pay_certificates_migration::ApplePayCertificatesMigrationRequest, +) -> CustomResult< + services::ApplicationResponse< + apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse, + >, + errors::ApiErrorResponse, +> { + let db = state.store.as_ref(); + + let merchant_id_list = &req.merchant_ids; + + let mut migration_successful_merchant_ids = vec![]; + let mut migration_failed_merchant_ids = vec![]; + + for merchant_id in merchant_id_list { + let key_store = state + .store + .get_merchant_key_store_by_merchant_id( + merchant_id, + &state.store.get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + let merchant_connector_accounts = db + .find_merchant_connector_account_by_merchant_id_and_disabled_list( + merchant_id, + true, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; + + let mut mca_to_update = vec![]; + + for connector_account in merchant_connector_accounts { + let connector_apple_pay_metadata = + helpers::get_applepay_metadata(connector_account.clone().metadata) + .map_err(|error| { + logger::error!( + "Apple pay metadata parsing failed for {:?} in certificates migrations api {:?}", + connector_account.clone().connector_name, + error + ) + }) + .ok(); + if let Some(apple_pay_metadata) = connector_apple_pay_metadata { + let encrypted_apple_pay_metadata = domain_types::encrypt( + Secret::new( + serde_json::to_value(apple_pay_metadata) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to serialize apple pay metadata as JSON")?, + ), + key_store.key.get_inner().peek(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt connector apple pay metadata")?; + + let updated_mca = + storage::MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate { + connector_wallets_details: encrypted_apple_pay_metadata, + }; + + mca_to_update.push((connector_account, updated_mca.into())); + } + } + + let merchant_connector_accounts_update = db + .update_multiple_merchant_connector_accounts(mca_to_update) + .await; + + match merchant_connector_accounts_update { + Ok(_) => { + logger::debug!("Merchant connector accounts updated for merchant id {merchant_id}"); + migration_successful_merchant_ids.push(merchant_id.to_string()); + } + Err(error) => { + logger::debug!( + "Merchant connector accounts update failed with error {error} for merchant id {merchant_id}"); + migration_failed_merchant_ids.push(merchant_id.to_string()); + } + }; + } + + Ok(services::api::ApplicationResponse::Json( + apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse { + migration_successful: migration_successful_merchant_ids, + migration_failed: migration_failed_merchant_ids, + }, + )) +} diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs index 2255e1ff582..704784c485e 100644 --- a/crates/router/src/core/authentication/transformers.rs +++ b/crates/router/src/core/authentication/transformers.rs @@ -153,6 +153,7 @@ pub fn construct_router_data<F: Clone, Req, Res>( address, auth_type: common_enums::AuthenticationType::NoThreeDs, connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: None, access_token: None, session_token: None, 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 74353e83b3d..679a5dad29a 100644 --- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs +++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs @@ -67,6 +67,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC address: self.address.clone(), auth_type: storage_enums::AuthenticationType::NoThreeDs, connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, request: FraudCheckCheckoutData { amount: self.payment_attempt.amount.get_amount_as_i64(), diff --git a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs index f91d87c808c..855b87f3ffb 100644 --- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs +++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs @@ -72,6 +72,7 @@ pub async fn construct_fulfillment_router_data<'a>( address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), 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 b8f8810f09b..ac661231ecc 100644 --- a/crates/router/src/core/fraud_check/flows/record_return.rs +++ b/crates/router/src/core/fraud_check/flows/record_return.rs @@ -65,6 +65,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh address: self.address.clone(), auth_type: storage_enums::AuthenticationType::NoThreeDs, connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, request: FraudCheckRecordReturnData { amount: self.payment_attempt.amount.get_amount_as_i64(), 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 b605c540656..6dbde23e3d2 100644 --- a/crates/router/src/core/fraud_check/flows/sale_flow.rs +++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs @@ -62,6 +62,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp address: self.address.clone(), auth_type: storage_enums::AuthenticationType::NoThreeDs, connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, request: FraudCheckSaleData { amount: self.payment_attempt.amount.get_amount_as_i64(), 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 8c496792a81..4f5d0b30aa9 100644 --- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs +++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs @@ -72,6 +72,7 @@ impl address: self.address.clone(), auth_type: storage_enums::AuthenticationType::NoThreeDs, connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, request: FraudCheckTransactionData { amount: self.payment_attempt.amount.get_amount_as_i64(), diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs index ec438ee6d78..811b69e4562 100644 --- a/crates/router/src/core/mandate/utils.rs +++ b/crates/router/src/core/mandate/utils.rs @@ -44,6 +44,7 @@ pub async fn construct_mandate_revoke_router_data( address: PaymentAddress::default(), auth_type: diesel_models::enums::AuthenticationType::default(), connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, access_token: None, session_token: None, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index caaecdc8629..8ee8dce6393 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1475,44 +1475,47 @@ where // Tokenization Action will be DecryptApplePayToken, only when payment method type is Apple Pay // and the connector supports Apple Pay predecrypt - if matches!( - tokenization_action, - TokenizationAction::DecryptApplePayToken - | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt - ) { - let apple_pay_data = match payment_data.payment_method_data.clone() { - Some(payment_data) => { - let domain_data = domain::PaymentMethodData::from(payment_data); - match domain_data { - domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay( - wallet_data, - )) => Some( - ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data)) - .change_context(errors::ApiErrorResponse::InternalServerError)? - .decrypt(state) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?, - ), - _ => None, + match &tokenization_action { + TokenizationAction::DecryptApplePayToken(payment_processing_details) + | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ) => { + let apple_pay_data = match payment_data.payment_method_data.clone() { + Some(payment_method_data) => { + let domain_data = domain::PaymentMethodData::from(payment_method_data); + match domain_data { + domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay( + wallet_data, + )) => Some( + ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data)) + .change_context(errors::ApiErrorResponse::InternalServerError)? + .decrypt( + &payment_processing_details.payment_processing_certificate, + &payment_processing_details.payment_processing_certificate_key, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?, + ), + _ => None, + } } - } - _ => None, - }; - - let apple_pay_predecrypt = apple_pay_data - .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>( - "ApplePayPredecryptData", - ) - .change_context(errors::ApiErrorResponse::InternalServerError)?; + _ => None, + }; - logger::debug!(?apple_pay_predecrypt); + let apple_pay_predecrypt = apple_pay_data + .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>( + "ApplePayPredecryptData", + ) + .change_context(errors::ApiErrorResponse::InternalServerError)?; - router_data.payment_method_token = Some( - hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt(Box::new( - apple_pay_predecrypt, - )), - ); - } + router_data.payment_method_token = Some( + hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt( + Box::new(apple_pay_predecrypt), + ), + ); + } + _ => (), + }; let pm_token = router_data .add_payment_method_token(state, &connector, &tokenization_action) @@ -2053,7 +2056,7 @@ fn is_payment_method_tokenization_enabled_for_connector( connector_name: &str, payment_method: &storage::enums::PaymentMethod, payment_method_type: &Option<storage::enums::PaymentMethodType>, - apple_pay_flow: &Option<enums::ApplePayFlow>, + apple_pay_flow: &Option<domain::ApplePayFlow>, ) -> RouterResult<bool> { let connector_tokenization_filter = state.conf.tokenization.0.get(connector_name); @@ -2078,13 +2081,13 @@ fn is_payment_method_tokenization_enabled_for_connector( fn is_apple_pay_pre_decrypt_type_connector_tokenization( payment_method_type: &Option<storage::enums::PaymentMethodType>, - apple_pay_flow: &Option<enums::ApplePayFlow>, + apple_pay_flow: &Option<domain::ApplePayFlow>, apple_pay_pre_decrypt_flow_filter: Option<ApplePayPreDecryptFlow>, ) -> bool { match (payment_method_type, apple_pay_flow) { ( Some(storage::enums::PaymentMethodType::ApplePay), - Some(enums::ApplePayFlow::Simplified), + Some(domain::ApplePayFlow::Simplified(_)), ) => !matches!( apple_pay_pre_decrypt_flow_filter, Some(ApplePayPreDecryptFlow::NetworkTokenization) @@ -2094,18 +2097,22 @@ fn is_apple_pay_pre_decrypt_type_connector_tokenization( } fn decide_apple_pay_flow( + state: &SessionState, payment_method_type: &Option<enums::PaymentMethodType>, merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>, -) -> Option<enums::ApplePayFlow> { +) -> Option<domain::ApplePayFlow> { payment_method_type.and_then(|pmt| match pmt { - enums::PaymentMethodType::ApplePay => check_apple_pay_metadata(merchant_connector_account), + enums::PaymentMethodType::ApplePay => { + check_apple_pay_metadata(state, merchant_connector_account) + } _ => None, }) } fn check_apple_pay_metadata( + state: &SessionState, merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>, -) -> Option<enums::ApplePayFlow> { +) -> Option<domain::ApplePayFlow> { merchant_connector_account.and_then(|mca| { let metadata = mca.get_metadata(); metadata.and_then(|apple_pay_metadata| { @@ -2139,14 +2146,34 @@ fn check_apple_pay_metadata( apple_pay_combined, ) => match apple_pay_combined { api_models::payments::ApplePayCombinedMetadata::Simplified { .. } => { - enums::ApplePayFlow::Simplified + domain::ApplePayFlow::Simplified(payments_api::PaymentProcessingDetails { + payment_processing_certificate: state + .conf + .applepay_decrypt_keys + .get_inner() + .apple_pay_ppc + .clone(), + payment_processing_certificate_key: state + .conf + .applepay_decrypt_keys + .get_inner() + .apple_pay_ppc_key + .clone(), + }) } - api_models::payments::ApplePayCombinedMetadata::Manual { .. } => { - enums::ApplePayFlow::Manual + api_models::payments::ApplePayCombinedMetadata::Manual { payment_request_data: _, session_token_data } => { + if let Some(manual_payment_processing_details_at) = session_token_data.payment_processing_details_at { + match manual_payment_processing_details_at { + payments_api::PaymentProcessingDetailsAt::Hyperswitch(payment_processing_details) => domain::ApplePayFlow::Simplified(payment_processing_details), + payments_api::PaymentProcessingDetailsAt::Connector => domain::ApplePayFlow::Manual, + } + } else { + domain::ApplePayFlow::Manual + } } }, api_models::payments::ApplepaySessionTokenMetadata::ApplePay(_) => { - enums::ApplePayFlow::Manual + domain::ApplePayFlow::Manual } }) }) @@ -2173,23 +2200,21 @@ async fn decide_payment_method_tokenize_action( payment_method: &storage::enums::PaymentMethod, pm_parent_token: Option<&String>, is_connector_tokenization_enabled: bool, - apple_pay_flow: Option<enums::ApplePayFlow>, + apple_pay_flow: Option<domain::ApplePayFlow>, ) -> RouterResult<TokenizationAction> { - let is_apple_pay_predecrypt_supported = - matches!(apple_pay_flow, Some(enums::ApplePayFlow::Simplified)); - match pm_parent_token { - None => { - if is_connector_tokenization_enabled && is_apple_pay_predecrypt_supported { - Ok(TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt) - } else if is_connector_tokenization_enabled { - Ok(TokenizationAction::TokenizeInConnectorAndRouter) - } else if is_apple_pay_predecrypt_supported { - Ok(TokenizationAction::DecryptApplePayToken) - } else { - Ok(TokenizationAction::TokenizeInRouter) + None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) { + (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { + TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ) } - } + (true, _) => TokenizationAction::TokenizeInConnectorAndRouter, + (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { + TokenizationAction::DecryptApplePayToken(payment_processing_details) + } + (false, _) => TokenizationAction::TokenizeInRouter, + }), Some(token) => { let redis_conn = state .store @@ -2212,17 +2237,18 @@ async fn decide_payment_method_tokenize_action( match connector_token_option { Some(connector_token) => Ok(TokenizationAction::ConnectorToken(connector_token)), - None => { - if is_connector_tokenization_enabled && is_apple_pay_predecrypt_supported { - Ok(TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt) - } else if is_connector_tokenization_enabled { - Ok(TokenizationAction::TokenizeInConnectorAndRouter) - } else if is_apple_pay_predecrypt_supported { - Ok(TokenizationAction::DecryptApplePayToken) - } else { - Ok(TokenizationAction::TokenizeInRouter) + None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) { + (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { + TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ) } - } + (true, _) => TokenizationAction::TokenizeInConnectorAndRouter, + (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { + TokenizationAction::DecryptApplePayToken(payment_processing_details) + } + (false, _) => TokenizationAction::TokenizeInRouter, + }), } } } @@ -2235,8 +2261,8 @@ pub enum TokenizationAction { TokenizeInConnectorAndRouter, ConnectorToken(String), SkipConnectorTokenization, - DecryptApplePayToken, - TokenizeInConnectorAndApplepayPreDecrypt, + DecryptApplePayToken(payments_api::PaymentProcessingDetails), + TokenizeInConnectorAndApplepayPreDecrypt(payments_api::PaymentProcessingDetails), } #[allow(clippy::too_many_arguments)] @@ -2277,7 +2303,7 @@ where let payment_method_type = &payment_data.payment_attempt.payment_method_type; let apple_pay_flow = - decide_apple_pay_flow(payment_method_type, Some(merchant_connector_account)); + decide_apple_pay_flow(state, payment_method_type, Some(merchant_connector_account)); let is_connector_tokenization_enabled = is_payment_method_tokenization_enabled_for_connector( @@ -2346,12 +2372,14 @@ where TokenizationAction::SkipConnectorTokenization => { TokenizationAction::SkipConnectorTokenization } - TokenizationAction::DecryptApplePayToken => { - TokenizationAction::DecryptApplePayToken - } - TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt => { - TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt + TokenizationAction::DecryptApplePayToken(payment_processing_details) => { + TokenizationAction::DecryptApplePayToken(payment_processing_details) } + TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ), }; (payment_data.to_owned(), connector_tokenization_action) } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 76441f40759..14a3b9327dc 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -166,8 +166,20 @@ async fn create_applepay_session_token( ) } else { // Get the apple pay metadata - let apple_pay_metadata = - helpers::get_applepay_metadata(router_data.connector_meta_data.clone())?; + let connector_apple_pay_wallet_details = + helpers::get_applepay_metadata(router_data.connector_wallets_details.clone()) + .map_err(|error| { + logger::debug!( + "Apple pay connector wallets details parsing failed in create_applepay_session_token {:?}", + error + ) + }) + .ok(); + + let apple_pay_metadata = match connector_apple_pay_wallet_details { + Some(apple_pay_wallet_details) => apple_pay_wallet_details, + None => helpers::get_applepay_metadata(router_data.connector_meta_data.clone())?, + }; // Get payment request data , apple pay session request and merchant keys let ( diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index a58a6ae32b2..6610b048606 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -6,6 +6,7 @@ use api_models::{ }; use base64::Engine; use common_utils::{ + crypto::Encryptable, ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt}, fp_utils, generate_id, id_type, pii, types::MinorUnit, @@ -3169,6 +3170,13 @@ impl MerchantConnectorAccountType { } } + pub fn get_connector_wallets_details(&self) -> Option<masking::Secret<serde_json::Value>> { + match self { + Self::DbVal(val) => val.connector_wallets_details.as_deref().cloned(), + Self::CacheVal(_) => None, + } + } + pub fn is_disabled(&self) -> bool { match self { Self::DbVal(ref inner) => inner.disabled.unwrap_or(false), @@ -3368,6 +3376,7 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>( refund_id: router_data.refund_id, dispute_id: router_data.dispute_id, connector_response: router_data.connector_response, + connector_wallets_details: router_data.connector_wallets_details, } } @@ -3905,17 +3914,32 @@ pub fn validate_customer_access( pub fn is_apple_pay_simplified_flow( connector_metadata: Option<pii::SecretSerdeValue>, + connector_wallets_details: Option<pii::SecretSerdeValue>, connector_name: Option<&String>, ) -> CustomResult<bool, errors::ApiErrorResponse> { - let option_apple_pay_metadata = get_applepay_metadata(connector_metadata) - .map_err(|error| { - logger::info!( - "Apple pay metadata parsing for {:?} in is_apple_pay_simplified_flow {:?}", + let connector_apple_pay_wallet_details = + get_applepay_metadata(connector_wallets_details) + .map_err(|error| { + logger::debug!( + "Apple pay connector wallets details parsing failed for {:?} in is_apple_pay_simplified_flow {:?}", + connector_name, + error + ) + }) + .ok(); + + let option_apple_pay_metadata = match connector_apple_pay_wallet_details { + Some(apple_pay_wallet_details) => Some(apple_pay_wallet_details), + None => get_applepay_metadata(connector_metadata) + .map_err(|error| { + logger::debug!( + "Apple pay metadata parsing failed for {:?} in is_apple_pay_simplified_flow {:?}", connector_name, error ) - }) - .ok(); + }) + .ok(), + }; // return true only if the apple flow type is simplified Ok(matches!( @@ -3928,6 +3952,38 @@ pub fn is_apple_pay_simplified_flow( )) } +pub async fn get_encrypted_apple_pay_connector_wallets_details( + key_store: &domain::MerchantKeyStore, + connector_metadata: &Option<masking::Secret<tera::Value>>, +) -> RouterResult<Option<Encryptable<masking::Secret<serde_json::Value>>>> { + let apple_pay_metadata = get_applepay_metadata(connector_metadata.clone()) + .map_err(|error| { + logger::error!( + "Apple pay metadata parsing failed in get_encrypted_apple_pay_connector_wallets_details {:?}", + error + ) + }) + .ok(); + + let connector_apple_pay_details = apple_pay_metadata + .map(|metadata| { + serde_json::to_value(metadata) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to serialize apple pay metadata as JSON") + }) + .transpose()? + .map(masking::Secret::new); + + let encrypted_connector_apple_pay_details = connector_apple_pay_details + .async_lift(|wallets_details| { + types::encrypt_optional(wallets_details, key_store.key.get_inner().peek()) + }) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while encrypting connector wallets details")?; + Ok(encrypted_connector_apple_pay_details) +} + pub fn get_applepay_metadata( connector_metadata: Option<pii::SecretSerdeValue>, ) -> RouterResult<api_models::payments::ApplepaySessionTokenMetadata> { @@ -3991,6 +4047,7 @@ where let connector_data_list = if is_apple_pay_simplified_flow( merchant_connector_account_type.get_metadata(), + merchant_connector_account_type.get_connector_wallets_details(), merchant_connector_account_type .get_connector_name() .as_ref(), @@ -4010,6 +4067,10 @@ where for merchant_connector_account in merchant_connector_account_list { if is_apple_pay_simplified_flow( merchant_connector_account.metadata, + merchant_connector_account + .connector_wallets_details + .as_deref() + .cloned(), Some(&merchant_connector_account.connector_name), )? { let connector_data = api::ConnectorData::get_connector_by_name( @@ -4064,10 +4125,11 @@ impl ApplePayData { pub async fn decrypt( &self, - state: &SessionState, + payment_processing_certificate: &masking::Secret<String>, + payment_processing_certificate_key: &masking::Secret<String>, ) -> CustomResult<serde_json::Value, errors::ApplePayDecryptionError> { - let merchant_id = self.merchant_id(state).await?; - let shared_secret = self.shared_secret(state).await?; + let merchant_id = self.merchant_id(payment_processing_certificate)?; + let shared_secret = self.shared_secret(payment_processing_certificate_key)?; let symmetric_key = self.symmetric_key(&merchant_id, &shared_secret)?; let decrypted = self.decrypt_ciphertext(&symmetric_key)?; let parsed_decrypted: serde_json::Value = serde_json::from_str(&decrypted) @@ -4075,17 +4137,11 @@ impl ApplePayData { Ok(parsed_decrypted) } - pub async fn merchant_id( + pub fn merchant_id( &self, - state: &SessionState, + payment_processing_certificate: &masking::Secret<String>, ) -> CustomResult<String, errors::ApplePayDecryptionError> { - let cert_data = state - .conf - .applepay_decrypt_keys - .get_inner() - .apple_pay_ppc - .clone() - .expose(); + let cert_data = payment_processing_certificate.clone().expose(); let base64_decode_cert_data = BASE64_ENGINE .decode(cert_data) @@ -4120,9 +4176,9 @@ impl ApplePayData { Ok(apple_pay_m_id) } - pub async fn shared_secret( + pub fn shared_secret( &self, - state: &SessionState, + payment_processing_certificate_key: &masking::Secret<String>, ) -> CustomResult<Vec<u8>, errors::ApplePayDecryptionError> { let public_ec_bytes = BASE64_ENGINE .decode(self.header.ephemeral_public_key.peek().as_bytes()) @@ -4132,13 +4188,7 @@ impl ApplePayData { .change_context(errors::ApplePayDecryptionError::KeyDeserializationFailed) .attach_printable("Failed to deserialize the public key")?; - let decrypted_apple_pay_ppc_key = state - .conf - .applepay_decrypt_keys - .get_inner() - .apple_pay_ppc_key - .clone() - .expose(); + let decrypted_apple_pay_ppc_key = payment_processing_certificate_key.clone().expose(); // Create PKey objects from EcKey let private_key = PKey::private_key_from_pem(decrypted_apple_pay_ppc_key.as_bytes()) diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 48637a0d2b3..7016c7542be 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -727,7 +727,7 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>( ) -> RouterResult<Option<String>> { match tokenization_action { payments::TokenizationAction::TokenizeInConnector - | payments::TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt => { + | payments::TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(_) => { let connector_integration: services::BoxedConnectorIntegration< '_, api::PaymentMethodToken, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 8eca589ca28..02115a529c3 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -125,6 +125,7 @@ where }; let apple_pay_flow = payments::decide_apple_pay_flow( + state, &payment_data.payment_attempt.payment_method_type, Some(merchant_connector_account), ); @@ -154,6 +155,7 @@ where .authentication_type .unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), request: T::try_from(additional_data)?, response, amount_captured: payment_data diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 679838a6dd5..8201a8480c0 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -164,6 +164,7 @@ pub async fn construct_payout_router_data<'a, F>( address, auth_type: enums::AuthenticationType::default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: None, payment_method_status: None, request: types::PayoutsData { @@ -316,6 +317,7 @@ pub async fn construct_refund_router_data<'a, F>( address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), @@ -565,6 +567,7 @@ pub async fn construct_accept_dispute_router_data<'a>( address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), @@ -661,6 +664,7 @@ pub async fn construct_submit_evidence_router_data<'a>( address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), @@ -755,6 +759,7 @@ pub async fn construct_upload_file_router_data<'a>( address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), @@ -853,6 +858,7 @@ pub async fn construct_defend_dispute_router_data<'a>( address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), @@ -942,6 +948,7 @@ pub async fn construct_retrieve_file_router_data<'a>( address: PaymentAddress::default(), auth_type: diesel_models::enums::AuthenticationType::default(), connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: None, payment_method_status: None, request: types::RetrieveFileRequestData { diff --git a/crates/router/src/core/verification/utils.rs b/crates/router/src/core/verification/utils.rs index 7518091ee87..bfbc1cb8b44 100644 --- a/crates/router/src/core/verification/utils.rs +++ b/crates/router/src/core/verification/utils.rs @@ -61,6 +61,7 @@ pub async fn check_existence_and_add_domain_to_db( pm_auth_config: None, connector_label: None, status: None, + connector_wallets_details: None, }; state .store diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs index ad1aafd3125..1394c68cfa8 100644 --- a/crates/router/src/core/webhooks/utils.rs +++ b/crates/router/src/core/webhooks/utils.rs @@ -86,6 +86,7 @@ pub async fn construct_webhook_router_data<'a>( address: PaymentAddress::default(), auth_type: diesel_models::enums::AuthenticationType::default(), connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, request: types::VerifyWebhookSourceRequestData { webhook_headers: request_details.headers.clone(), diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 910ad085f63..19603f81486 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -942,6 +942,17 @@ impl FileMetadataInterface for KafkaStore { #[async_trait::async_trait] impl MerchantConnectorAccountInterface for KafkaStore { + async fn update_multiple_merchant_connector_accounts( + &self, + merchant_connector_accounts: Vec<( + domain::MerchantConnectorAccount, + storage::MerchantConnectorAccountUpdateInternal, + )>, + ) -> CustomResult<(), errors::StorageError> { + self.diesel_store + .update_multiple_merchant_connector_accounts(merchant_connector_accounts) + .await + } async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, merchant_id: &str, diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index aea37b517be..ab66b52c32d 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -1,4 +1,6 @@ +use async_bb8_diesel::AsyncConnection; use common_utils::ext_traits::{AsyncExt, ByteSliceExt, Encode}; +use diesel_models::encryption::Encryption; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] @@ -165,6 +167,14 @@ where key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>; + async fn update_multiple_merchant_connector_accounts( + &self, + this: Vec<( + domain::MerchantConnectorAccount, + storage::MerchantConnectorAccountUpdateInternal, + )>, + ) -> CustomResult<(), errors::StorageError>; + async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &str, @@ -381,6 +391,104 @@ impl MerchantConnectorAccountInterface for Store { .await } + #[instrument(skip_all)] + async fn update_multiple_merchant_connector_accounts( + &self, + merchant_connector_accounts: Vec<( + domain::MerchantConnectorAccount, + storage::MerchantConnectorAccountUpdateInternal, + )>, + ) -> CustomResult<(), errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + + async fn update_call( + connection: &diesel_models::PgPooledConn, + (merchant_connector_account, mca_update): ( + domain::MerchantConnectorAccount, + storage::MerchantConnectorAccountUpdateInternal, + ), + ) -> Result<(), error_stack::Report<storage_impl::errors::StorageError>> { + Conversion::convert(merchant_connector_account) + .await + .change_context(errors::StorageError::EncryptionError)? + .update(connection, mca_update) + .await + .map_err(|error| report!(errors::StorageError::from(error)))?; + Ok(()) + } + + conn.transaction_async(|connection_pool| async move { + for (merchant_connector_account, update_merchant_connector_account) in + merchant_connector_accounts + { + let _connector_name = merchant_connector_account.connector_name.clone(); + let _profile_id = merchant_connector_account.profile_id.clone().ok_or( + errors::StorageError::ValueNotFound("profile_id".to_string()), + )?; + + let _merchant_id = merchant_connector_account.merchant_id.clone(); + let _merchant_connector_id = + merchant_connector_account.merchant_connector_id.clone(); + + let update = update_call( + &connection_pool, + ( + merchant_connector_account, + update_merchant_connector_account, + ), + ); + + #[cfg(feature = "accounts_cache")] + // Redact all caches as any of might be used because of backwards compatibility + cache::publish_and_redact_multiple( + self, + [ + cache::CacheKind::Accounts( + format!("{}_{}", _profile_id, _connector_name).into(), + ), + cache::CacheKind::Accounts( + format!("{}_{}", _merchant_id, _merchant_connector_id).into(), + ), + cache::CacheKind::CGraph( + format!("cgraph_{}_{_profile_id}", _merchant_id).into(), + ), + ], + || update, + ) + .await + .map_err(|error| { + // Returning `DatabaseConnectionError` after logging the actual error because + // -> it is not possible to get the underlying from `error_stack::Report<C>` + // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>` + // because of Rust's orphan rules + router_env::logger::error!( + ?error, + "DB transaction for updating multiple merchant connector account failed" + ); + errors::StorageError::DatabaseConnectionError + })?; + + #[cfg(not(feature = "accounts_cache"))] + { + update.await.map_err(|error| { + // Returning `DatabaseConnectionError` after logging the actual error because + // -> it is not possible to get the underlying from `error_stack::Report<C>` + // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>` + // because of Rust's orphan rules + router_env::logger::error!( + ?error, + "DB transaction for updating multiple merchant connector account failed" + ); + errors::StorageError::DatabaseConnectionError + })?; + } + } + Ok::<_, errors::StorageError>(()) + }) + .await?; + Ok(()) + } + #[instrument(skip_all)] async fn update_merchant_connector_account( &self, @@ -417,7 +525,7 @@ impl MerchantConnectorAccountInterface for Store { #[cfg(feature = "accounts_cache")] { - // Redact both the caches as any one or both might be used because of backwards compatibility + // Redact all caches as any of might be used because of backwards compatibility cache::publish_and_redact_multiple( self, [ @@ -502,6 +610,17 @@ impl MerchantConnectorAccountInterface for Store { #[async_trait::async_trait] impl MerchantConnectorAccountInterface for MockDb { + async fn update_multiple_merchant_connector_accounts( + &self, + _merchant_connector_accounts: Vec<( + domain::MerchantConnectorAccount, + storage::MerchantConnectorAccountUpdateInternal, + )>, + ) -> CustomResult<(), errors::StorageError> { + // No need to implement this function for `MockDb` as this function will be removed after the + // apple pay certificate migration + Err(errors::StorageError::MockDbError)? + } async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, merchant_id: &str, @@ -658,6 +777,7 @@ impl MerchantConnectorAccountInterface for MockDb { applepay_verified_domains: t.applepay_verified_domains, pm_auth_config: t.pm_auth_config, status: t.status, + connector_wallets_details: t.connector_wallets_details.map(Encryption::from), }; accounts.push(account.clone()); account @@ -857,6 +977,14 @@ mod merchant_connector_account_cache_tests { applepay_verified_domains: None, pm_auth_config: None, status: common_enums::ConnectorStatus::Inactive, + connector_wallets_details: Some( + domain::types::encrypt( + serde_json::Value::default().into(), + merchant_key.key.get_inner().peek(), + ) + .await + .unwrap(), + ), }; db.insert_merchant_connector_account(mca.clone(), &merchant_key) diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 7344b85d150..73ec0f1635d 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -144,6 +144,7 @@ pub fn mk_app( .service(routes::Routing::server(state.clone())) .service(routes::Blocklist::server(state.clone())) .service(routes::Gsm::server(state.clone())) + .service(routes::ApplePayCertificatesMigration::server(state.clone())) .service(routes::PaymentLink::server(state.clone())) .service(routes::User::server(state.clone())) .service(routes::ConnectorOnboarding::server(state.clone())) diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index 9f13635ca90..cb229b5c802 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -1,6 +1,7 @@ pub mod admin; pub mod api_keys; pub mod app; +pub mod apple_pay_certificates_migration; #[cfg(feature = "olap")] pub mod blocklist; pub mod cache; @@ -58,10 +59,10 @@ pub use self::app::Payouts; #[cfg(all(feature = "olap", feature = "recon"))] pub use self::app::Recon; pub use self::app::{ - ApiKeys, AppState, BusinessProfile, Cache, Cards, Configs, ConnectorOnboarding, Customers, - Disputes, EphemeralKey, Files, Gsm, Health, Mandates, MerchantAccount, - MerchantConnectorAccount, PaymentLink, PaymentMethods, Payments, Poll, Refunds, SessionState, - User, Webhooks, + ApiKeys, AppState, ApplePayCertificatesMigration, BusinessProfile, Cache, Cards, Configs, + ConnectorOnboarding, Customers, Disputes, EphemeralKey, Files, Gsm, Health, Mandates, + MerchantAccount, MerchantConnectorAccount, PaymentLink, PaymentMethods, Payments, Poll, + Refunds, SessionState, User, Webhooks, }; #[cfg(feature = "olap")] pub use self::app::{Blocklist, Routing, Verify, WebhookEvents}; diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 2d1b77460a5..cd392756505 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -413,7 +413,7 @@ pub async fn payment_connector_delete( merchant_connector_id, }) .into_inner(); - api::server_wrap( + Box::pin(api::server_wrap( flow, state, &req, @@ -430,7 +430,7 @@ pub async fn payment_connector_delete( req.headers(), ), api_locking::LockAction::NotApplicable, - ) + )) .await } /// Merchant Account - Toggle KV diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 5af3a2bef25..5438535a15c 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -29,8 +29,8 @@ use super::routing as cloud_routing; use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains}; #[cfg(feature = "olap")] use super::{ - admin::*, api_keys::*, connector_onboarding::*, disputes::*, files::*, gsm::*, payment_link::*, - user::*, user_role::*, webhook_events::*, + admin::*, api_keys::*, apple_pay_certificates_migration, connector_onboarding::*, disputes::*, + files::*, gsm::*, payment_link::*, user::*, user_role::*, webhook_events::*, }; use super::{cache::*, health::*}; #[cfg(any(feature = "olap", feature = "oltp"))] @@ -1117,6 +1117,19 @@ impl Configs { } } +pub struct ApplePayCertificatesMigration; + +#[cfg(feature = "olap")] +impl ApplePayCertificatesMigration { + pub fn server(state: AppState) -> Scope { + web::scope("/apple_pay_certificates_migration") + .app_data(web::Data::new(state)) + .service(web::resource("").route( + web::post().to(apple_pay_certificates_migration::apple_pay_certificates_migration), + )) + } +} + pub struct Poll; #[cfg(feature = "oltp")] diff --git a/crates/router/src/routes/apple_pay_certificates_migration.rs b/crates/router/src/routes/apple_pay_certificates_migration.rs new file mode 100644 index 00000000000..8c9d507ba41 --- /dev/null +++ b/crates/router/src/routes/apple_pay_certificates_migration.rs @@ -0,0 +1,30 @@ +use actix_web::{web, HttpRequest, HttpResponse}; +use router_env::Flow; + +use super::AppState; +use crate::{ + core::{api_locking, apple_pay_certificates_migration}, + services::{api, authentication as auth}, +}; + +pub async fn apple_pay_certificates_migration( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json< + api_models::apple_pay_certificates_migration::ApplePayCertificatesMigrationRequest, + >, +) -> HttpResponse { + let flow = Flow::ApplePayCertificatesMigration; + Box::pin(api::server_wrap( + flow, + state, + &req, + &json_payload.into_inner(), + |state, _, req, _| { + apple_pay_certificates_migration::apple_pay_certificates_migration(state, req) + }, + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index b4b9658a7e0..a64343757b5 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -35,6 +35,7 @@ pub enum ApiIdentifier { ConnectorOnboarding, Recon, Poll, + ApplePayCertificatesMigration, } impl From<Flow> for ApiIdentifier { @@ -186,6 +187,8 @@ impl From<Flow> for ApiIdentifier { | Flow::GsmRuleUpdate | Flow::GsmRuleDelete => Self::Gsm, + Flow::ApplePayCertificatesMigration => Self::ApplePayCertificatesMigration, + Flow::UserConnectAccount | Flow::UserSignUp | Flow::UserSignIn diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index e17ec791637..21aea14caf5 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -805,6 +805,7 @@ impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2) address: data.address.clone(), auth_type: data.auth_type, connector_meta_data: data.connector_meta_data.clone(), + connector_wallets_details: data.connector_wallets_details.clone(), amount_captured: data.amount_captured, access_token: data.access_token.clone(), response: data.response.clone(), @@ -865,6 +866,7 @@ impl<F1, F2> address: data.address.clone(), auth_type: data.auth_type, connector_meta_data: data.connector_meta_data.clone(), + connector_wallets_details: data.connector_wallets_details.clone(), amount_captured: data.amount_captured, access_token: data.access_token.clone(), response: data.response.clone(), diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index 0b932f9aeb1..7e296d0b4a8 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -85,6 +85,7 @@ impl VerifyConnectorData { connector_customer: None, connector_auth_type: self.connector_auth.clone(), connector_meta_data: None, + connector_wallets_details: None, payment_method_token: None, connector_api_version: None, recurring_mandate_payment_data: None, diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs index 0e7f5b081c3..6c2f6a06e1e 100644 --- a/crates/router/src/types/domain/merchant_connector_account.rs +++ b/crates/router/src/types/domain/merchant_connector_account.rs @@ -11,7 +11,10 @@ use diesel_models::{ use error_stack::ResultExt; use masking::{PeekInterface, Secret}; -use super::{behaviour, types::TypeEncryption}; +use super::{ + behaviour, + types::{self, AsyncLift, TypeEncryption}, +}; #[derive(Clone, Debug)] pub struct MerchantConnectorAccount { pub id: Option<i32>, @@ -36,6 +39,7 @@ pub struct MerchantConnectorAccount { pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, pub status: enums::ConnectorStatus, + pub connector_wallets_details: Option<Encryptable<Secret<serde_json::Value>>>, } #[derive(Debug)] @@ -56,6 +60,10 @@ pub enum MerchantConnectorAccountUpdate { pm_auth_config: Option<serde_json::Value>, connector_label: Option<String>, status: Option<enums::ConnectorStatus>, + connector_wallets_details: Option<Encryptable<Secret<serde_json::Value>>>, + }, + ConnectorWalletDetailsUpdate { + connector_wallets_details: Encryptable<Secret<serde_json::Value>>, }, } @@ -92,6 +100,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, status: self.status, + connector_wallets_details: self.connector_wallets_details.map(Encryption::from), }, ) } @@ -132,6 +141,13 @@ impl behaviour::Conversion for MerchantConnectorAccount { applepay_verified_domains: other.applepay_verified_domains, pm_auth_config: other.pm_auth_config, status: other.status, + connector_wallets_details: other + .connector_wallets_details + .async_lift(|inner| types::decrypt(inner, key.peek())) + .await + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting connector wallets details".to_string(), + })?, }) } @@ -160,6 +176,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, status: self.status, + connector_wallets_details: self.connector_wallets_details.map(Encryption::from), }) } } @@ -183,6 +200,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte pm_auth_config, connector_label, status, + connector_wallets_details, } => Self { merchant_id, connector_type, @@ -201,6 +219,29 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte pm_auth_config, connector_label, status, + connector_wallets_details: connector_wallets_details.map(Encryption::from), + }, + MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate { + connector_wallets_details, + } => Self { + connector_wallets_details: Some(Encryption::from(connector_wallets_details)), + merchant_id: None, + connector_type: None, + connector_name: None, + connector_account_details: None, + connector_label: None, + test_mode: None, + disabled: None, + merchant_connector_id: None, + payment_methods_enabled: None, + frm_configs: None, + metadata: None, + modified_at: None, + connector_webhook_details: None, + frm_config: None, + applepay_verified_domains: None, + pm_auth_config: None, + status: None, }, } } diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs index 51d3210a70f..021505c644f 100644 --- a/crates/router/src/types/domain/payments.rs +++ b/crates/router/src/types/domain/payments.rs @@ -1,10 +1,10 @@ pub use hyperswitch_domain_models::payment_method_data::{ - AliPayQr, ApplePayThirdPartySdkData, ApplePayWalletData, ApplepayPaymentMethod, BankDebitData, - BankRedirectData, BankTransferData, BoletoVoucherData, Card, CardRedirectData, CardToken, - CashappQr, CryptoData, GcashRedirection, GiftCardData, GiftCardDetails, GoPayRedirection, - GooglePayPaymentMethodInfo, GooglePayRedirectData, GooglePayThirdPartySdkData, - GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData, KakaoPayRedirection, - MbWayRedirection, PayLaterData, PaymentMethodData, SamsungPayWalletData, + AliPayQr, ApplePayFlow, ApplePayThirdPartySdkData, ApplePayWalletData, ApplepayPaymentMethod, + BankDebitData, BankRedirectData, BankTransferData, BoletoVoucherData, Card, CardRedirectData, + CardToken, CashappQr, CryptoData, GcashRedirection, GiftCardData, GiftCardDetails, + GoPayRedirection, GooglePayPaymentMethodInfo, GooglePayRedirectData, + GooglePayThirdPartySdkData, GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData, + KakaoPayRedirection, MbWayRedirection, PayLaterData, PaymentMethodData, SamsungPayWalletData, SepaAndBacsBillingDetails, SwishQrData, TouchNGoRedirection, UpiCollectData, UpiData, UpiIntentData, VoucherData, WalletData, WeChatPayQr, }; diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index b83d3138b7c..e71219b6a9e 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -707,13 +707,13 @@ impl CustomerAddress for api_models::customers::CustomerRequest { } pub fn add_apple_pay_flow_metrics( - apple_pay_flow: &Option<enums::ApplePayFlow>, + apple_pay_flow: &Option<domain::ApplePayFlow>, connector: Option<String>, merchant_id: String, ) { if let Some(flow) = apple_pay_flow { match flow { - enums::ApplePayFlow::Simplified => metrics::APPLE_PAY_SIMPLIFIED_FLOW.add( + domain::ApplePayFlow::Simplified(_) => metrics::APPLE_PAY_SIMPLIFIED_FLOW.add( &metrics::CONTEXT, 1, &[ @@ -724,7 +724,7 @@ pub fn add_apple_pay_flow_metrics( metrics::request::add_attributes("merchant_id", merchant_id.to_owned()), ], ), - enums::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW.add( + domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW.add( &metrics::CONTEXT, 1, &[ @@ -741,14 +741,14 @@ pub fn add_apple_pay_flow_metrics( pub fn add_apple_pay_payment_status_metrics( payment_attempt_status: enums::AttemptStatus, - apple_pay_flow: Option<enums::ApplePayFlow>, + apple_pay_flow: Option<domain::ApplePayFlow>, connector: Option<String>, merchant_id: String, ) { if payment_attempt_status == enums::AttemptStatus::Charged { if let Some(flow) = apple_pay_flow { match flow { - enums::ApplePayFlow::Simplified => { + domain::ApplePayFlow::Simplified(_) => { metrics::APPLE_PAY_SIMPLIFIED_FLOW_SUCCESSFUL_PAYMENT.add( &metrics::CONTEXT, 1, @@ -761,7 +761,7 @@ pub fn add_apple_pay_payment_status_metrics( ], ) } - enums::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT + domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT .add( &metrics::CONTEXT, 1, @@ -778,7 +778,7 @@ pub fn add_apple_pay_payment_status_metrics( } else if payment_attempt_status == enums::AttemptStatus::Failure { if let Some(flow) = apple_pay_flow { match flow { - enums::ApplePayFlow::Simplified => { + domain::ApplePayFlow::Simplified(_) => { metrics::APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT.add( &metrics::CONTEXT, 1, @@ -791,7 +791,7 @@ pub fn add_apple_pay_payment_status_metrics( ], ) } - enums::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT.add( + domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT.add( &metrics::CONTEXT, 1, &[ diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 10e8b366530..b01c5abb968 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -97,6 +97,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { None, ), connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, access_token: None, session_token: None, @@ -159,6 +160,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { response: Err(types::ErrorResponse::default()), address: PaymentAddress::default(), connector_meta_data: None, + connector_wallets_details: None, amount_captured: None, access_token: None, session_token: None, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 0de19f17b54..be86d377299 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -540,6 +540,7 @@ pub trait ConnectorActions: Connector { connector_meta_data: info .clone() .and_then(|a| a.connector_meta_data.map(Secret::new)), + connector_wallets_details: None, amount_captured: None, access_token: info.clone().and_then(|a| a.access_token), session_token: None, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 110532f524d..51f762e3713 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -298,6 +298,8 @@ pub enum Flow { GsmRuleRetrieve, /// Gsm Rule Update flow GsmRuleUpdate, + /// Apple pay certificates migration + ApplePayCertificatesMigration, /// Gsm Rule Delete flow GsmRuleDelete, /// User Sign Up diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index 4356b6b7997..b153c47b882 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -101,6 +101,12 @@ impl From<error_stack::Report<RedisError>> for StorageError { } } +impl From<diesel::result::Error> for StorageError { + fn from(err: diesel::result::Error) -> Self { + Self::from(error_stack::report!(DatabaseError::from(err))) + } +} + impl From<error_stack::Report<DatabaseError>> for StorageError { fn from(err: error_stack::Report<DatabaseError>) -> Self { Self::DatabaseError(err) diff --git a/migrations/2024-05-28-054439_connector_wallets_details/down.sql b/migrations/2024-05-28-054439_connector_wallets_details/down.sql new file mode 100644 index 00000000000..dea26bbd1eb --- /dev/null +++ b/migrations/2024-05-28-054439_connector_wallets_details/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE merchant_connector_account DROP COLUMN IF EXISTS connector_wallets_details; \ No newline at end of file diff --git a/migrations/2024-05-28-054439_connector_wallets_details/up.sql b/migrations/2024-05-28-054439_connector_wallets_details/up.sql new file mode 100644 index 00000000000..c75de9204df --- /dev/null +++ b/migrations/2024-05-28-054439_connector_wallets_details/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS connector_wallets_details BYTEA DEFAULT NULL; \ No newline at end of file diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index f42481798a4..ba0d8946192 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -13697,6 +13697,63 @@ }, "additionalProperties": false }, + "PaymentProcessingDetails": { + "type": "object", + "required": [ + "payment_processing_certificate", + "payment_processing_certificate_key" + ], + "properties": { + "payment_processing_certificate": { + "type": "string" + }, + "payment_processing_certificate_key": { + "type": "string" + } + } + }, + "PaymentProcessingDetailsAt": { + "oneOf": [ + { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentProcessingDetails" + }, + { + "type": "object", + "required": [ + "payment_processing_details_at" + ], + "properties": { + "payment_processing_details_at": { + "type": "string", + "enum": [ + "Hyperswitch" + ] + } + } + } + ] + }, + { + "type": "object", + "required": [ + "payment_processing_details_at" + ], + "properties": { + "payment_processing_details_at": { + "type": "string", + "enum": [ + "Connector" + ] + } + } + } + ], + "discriminator": { + "propertyName": "payment_processing_details_at" + } + }, "PaymentRetrieveBody": { "type": "object", "properties": { @@ -18394,43 +18451,55 @@ } }, "SessionTokenInfo": { - "type": "object", - "required": [ - "certificate", - "certificate_keys", - "merchant_identifier", - "display_name", - "initiative", - "initiative_context" - ], - "properties": { - "certificate": { - "type": "string" - }, - "certificate_keys": { - "type": "string" - }, - "merchant_identifier": { - "type": "string" - }, - "display_name": { - "type": "string" - }, - "initiative": { - "type": "string" - }, - "initiative_context": { - "type": "string" - }, - "merchant_business_country": { + "allOf": [ + { "allOf": [ { - "$ref": "#/components/schemas/CountryAlpha2" + "$ref": "#/components/schemas/PaymentProcessingDetailsAt" } ], "nullable": true + }, + { + "type": "object", + "required": [ + "certificate", + "certificate_keys", + "merchant_identifier", + "display_name", + "initiative", + "initiative_context" + ], + "properties": { + "certificate": { + "type": "string" + }, + "certificate_keys": { + "type": "string" + }, + "merchant_identifier": { + "type": "string" + }, + "display_name": { + "type": "string" + }, + "initiative": { + "type": "string" + }, + "initiative_context": { + "type": "string" + }, + "merchant_business_country": { + "allOf": [ + { + "$ref": "#/components/schemas/CountryAlpha2" + } + ], + "nullable": true + } + } } - } + ] }, "StraightThroughAlgorithm": { "oneOf": [
2024-05-28T13:19:09Z
## Description <!-- Describe your changes in detail --> Currently apple pay related details are being stored in the connector metadata, as in future we are going to add apple pay decrypted flow support for ios app we will be collecting the apple pay payment processing certificates as well. As this ppc and ppc key needs to be securely stored, we need to move the existing certificates to a new column which stores the encrypted certificates. This pr adds a api end point (`/apple_pay_certificates_migration`) to migrate the apple pay details form the merchant connector account `metadata` to the newly added column connector (`connector_wallets_details`). This api takes list of `merchant_ids` as input and then lists all the configured merchant connector accounts for that merchant id. After which it checks for the apple pay details in the metadata in the merchant connector account, if present it is encrypted by merchant's DEK (Data Encryption Key) and will be stored in the newly added column (`connector_wallets_details`) in the merchant connector account. Response contains the list of merchant_ids for migration succeeded (`migration_successful`) and failed (`migraiton_failed`). ### 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)? --> -> Apple pay certificate migration api ``` curl --location 'http://localhost:8080/apple_pay_certificates_migration' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "merchant_ids": ["merchant_1713176513", "merchant_1714122879"] }' ``` <img width="719" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/bb66cc2c-69f7-4c6e-bb3c-1e184944bbd2"> -> Check the db for connector_wallets_details of mca belonging to above merchants <img width="862" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/24d5c9ed-f091-49cd-983b-839724024118"> -> Create MCA with apple pay `simplified` and manual `flow` metadata for apple pay `simplified` ``` "apple_pay_combined": { "simplified": { "session_token_data": { "initiative_context": "sdk-test-app.netlify.app", "merchant_business_country": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` metadata for apple pay `manual` flow ``` "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "", "display_name": "applepay", "certificate_keys": "", "merchant_business_coountry": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` -> Confirm an apple pay payment with above flows <img width="1159" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/a70ebc44-948a-421d-bcdf-3f9a2adb4361"> -> Create a apple pay payment with the below metadata ``` "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "", "display_name": "applepay", "certificate_keys": "", "payment_processing_details_at": "Hyperswitch", "payment_processing_certificate": "", "payment_processing_certificate_key": "", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "", "merchant_business_coountry": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` -> Confirm apple pay payment <img width="1055" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4460d4e3-24e9-4348-ac1c-c05d6bef5e3e">
d242850b63173f314fb259451139464f09e0a9e9
-> Apple pay certificate migration api ``` curl --location 'http://localhost:8080/apple_pay_certificates_migration' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "merchant_ids": ["merchant_1713176513", "merchant_1714122879"] }' ``` <img width="719" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/bb66cc2c-69f7-4c6e-bb3c-1e184944bbd2"> -> Check the db for connector_wallets_details of mca belonging to above merchants <img width="862" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/24d5c9ed-f091-49cd-983b-839724024118"> -> Create MCA with apple pay `simplified` and manual `flow` metadata for apple pay `simplified` ``` "apple_pay_combined": { "simplified": { "session_token_data": { "initiative_context": "sdk-test-app.netlify.app", "merchant_business_country": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` metadata for apple pay `manual` flow ``` "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "", "display_name": "applepay", "certificate_keys": "", "merchant_business_coountry": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` -> Confirm an apple pay payment with above flows <img width="1159" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/a70ebc44-948a-421d-bcdf-3f9a2adb4361"> -> Create a apple pay payment with the below metadata ``` "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": "", "display_name": "applepay", "certificate_keys": "", "payment_processing_details_at": "Hyperswitch", "payment_processing_certificate": "", "payment_processing_certificate_key": "", "initiative_context": "sdk-test-app.netlify.app", "merchant_identifier": "", "merchant_business_coountry": "US" }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } ``` -> Confirm apple pay payment <img width="1055" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4460d4e3-24e9-4348-ac1c-c05d6bef5e3e">
[ "crates/api_models/src/apple_pay_certificates_migration.rs", "crates/api_models/src/events.rs", "crates/api_models/src/events/apple_pay_certificates_migration.rs", "crates/api_models/src/lib.rs", "crates/api_models/src/payments.rs", "crates/common_enums/src/enums.rs", "crates/common_utils/src/events.rs"...
juspay/hyperswitch
juspay__hyperswitch-4783
Bug: [REFACTOR] retrieve extended card info config during business profile get call During business profile get call, send the extended card info config of merchant in the response so that dashboard can make use of it
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 12d9832ada6..dc64947bf08 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -1010,6 +1010,9 @@ pub struct BusinessProfileResponse { // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, + + /// Merchant's config to support extended card info feature + pub extended_card_info_config: Option<ExtendedCardInfoConfig>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 8fc3ebb721f..20083afb1c9 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -8,7 +8,7 @@ pub use api_models::admin::{ }; use common_utils::ext_traits::{Encode, ValueExt}; use error_stack::ResultExt; -use masking::Secret; +use masking::{ExposeInterface, Secret}; use crate::{ core::errors, @@ -81,6 +81,10 @@ impl ForeignTryFrom<storage::business_profile::BusinessProfile> for BusinessProf }) .transpose()?, use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing, + extended_card_info_config: item + .extended_card_info_config + .map(|config| config.expose().parse_value("ExtendedCardInfoConfig")) + .transpose()?, }) } } diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index b87b516de28..18ec7577a98 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -6949,6 +6949,14 @@ "use_billing_as_payment_method_billing": { "type": "boolean", "nullable": true + }, + "extended_card_info_config": { + "allOf": [ + { + "$ref": "#/components/schemas/ExtendedCardInfoConfig" + } + ], + "nullable": true } } },
2024-05-28T07:55:13Z
## Description <!-- Describe your changes in detail --> During business profile get call, send the extended card info config of merchant (public key and ttl) in the response so that dashboard can make use of it ### 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)? --> 1. Create merchant account (get default profile_id) 2. Create api key 3. Use update endpoint of business profile to pass config. ``` curl --location 'http://localhost:8080/account/merchant_1716883344/business_profile/pro_5PdcjX4zYfC8X2PFjCel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "extended_card_info_config": { "ttl_in_secs": 300, "public_key": "pub_key" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/67787f0e-724c-4bed-ae37-a2636093e481) 4. Retrieve the business profile and the config should be returned in the response ``` curl --location 'http://localhost:8080/account/merchant_1716883344/business_profile/pro_5PdcjX4zYfC8X2PFjCel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/eefcd267-ad39-447f-aa7a-8536537f935d)
c9fa94febe7a1fcd24e8d723d14b78f8a73da0e3
1. Create merchant account (get default profile_id) 2. Create api key 3. Use update endpoint of business profile to pass config. ``` curl --location 'http://localhost:8080/account/merchant_1716883344/business_profile/pro_5PdcjX4zYfC8X2PFjCel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "extended_card_info_config": { "ttl_in_secs": 300, "public_key": "pub_key" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/67787f0e-724c-4bed-ae37-a2636093e481) 4. Retrieve the business profile and the config should be returned in the response ``` curl --location 'http://localhost:8080/account/merchant_1716883344/business_profile/pro_5PdcjX4zYfC8X2PFjCel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/eefcd267-ad39-447f-aa7a-8536537f935d)
[ "crates/api_models/src/admin.rs", "crates/router/src/types/api/admin.rs", "openapi/openapi_spec.json" ]
juspay/hyperswitch
juspay__hyperswitch-4778
Bug: [FEATURE] [CRYPTOPAY] Pass network details in payment request ### Feature Description The customer should be able to choose the supported network in case of doing cryptocurrency payments via Cryptopay. ### Possible Implementation The supported networks will be shown on SDK and the chosen network will be passed on to Cryptopay. If no network is chosen then Cryptopay will choose the default network for that transaction. https://developers.cryptopay.me/guides/currencies/currencies ### 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 cd405e3ca98..fe46d342161 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -2118,6 +2118,7 @@ pub struct SepaAndBacsBillingDetails { #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, + pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 7517918ed95..065290b6b2d 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -285,6 +285,7 @@ pub enum BankRedirectData { #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, + pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] @@ -693,8 +694,14 @@ impl From<api_models::payments::BankRedirectData> for BankRedirectData { impl From<api_models::payments::CryptoData> for CryptoData { fn from(value: api_models::payments::CryptoData) -> Self { - let api_models::payments::CryptoData { pay_currency } = value; - Self { pay_currency } + let api_models::payments::CryptoData { + pay_currency, + network, + } = value; + Self { + pay_currency, + network, + } } } diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 0405f318071..a582a00ee19 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -8195,7 +8195,6 @@ impl Default for super::settings::RequiredFields { "TRX".to_string(), "DOGE".to_string(), "BNB".to_string(), - "BUSD".to_string(), "USDT".to_string(), "USDC".to_string(), "DAI".to_string(), @@ -8204,6 +8203,15 @@ impl Default for super::settings::RequiredFields { value: None, } ), + ( + "payment_method_data.crypto.network".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.crypto.network".to_string(), + display_name: "network".to_string(), + field_type: enums::FieldType::Text, + value: None, + } + ), ]), common : HashMap::new(), } diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index 1a1f23b93bf..bcbc9a043a1 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -42,6 +42,8 @@ pub struct CryptopayPaymentsRequest { price_amount: String, price_currency: enums::Currency, pay_currency: String, + #[serde(skip_serializing_if = "Option::is_none")] + network: Option<String>, success_redirect_url: Option<String>, unsuccess_redirect_url: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] @@ -63,6 +65,7 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> price_amount: item.amount.to_owned(), price_currency: item.router_data.request.currency, pay_currency, + network: cryptodata.network.to_owned(), success_redirect_url: item.router_data.request.router_return_url.clone(), unsuccess_redirect_url: item.router_data.request.router_return_url.clone(), //Cryptopay only accepts metadata as Object. If any other type, payment will fail with error. diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs index 85026c9c447..69c6bfac61d 100644 --- a/crates/router/tests/connectors/bitpay.rs +++ b/crates/router/tests/connectors/bitpay.rs @@ -70,6 +70,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { currency: enums::Currency::USD, payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: None, + network: None, }), confirm: true, statement_descriptor_suffix: None, diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs index 306255c94c5..569b2222e8b 100644 --- a/crates/router/tests/connectors/coinbase.rs +++ b/crates/router/tests/connectors/coinbase.rs @@ -72,6 +72,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { currency: enums::Currency::USD, payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: None, + network: None, }), confirm: true, statement_descriptor_suffix: None, diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs index 6d52a174b58..20c727756e7 100644 --- a/crates/router/tests/connectors/cryptopay.rs +++ b/crates/router/tests/connectors/cryptopay.rs @@ -71,6 +71,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { currency: enums::Currency::USD, payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: Some("XRP".to_string()), + network: None, }), confirm: true, statement_descriptor_suffix: None, diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs index 91162b829e2..df54f0caf85 100644 --- a/crates/router/tests/connectors/opennode.rs +++ b/crates/router/tests/connectors/opennode.rs @@ -71,6 +71,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { currency: enums::Currency::USD, payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: None, + network: None, }), confirm: true, statement_descriptor_suffix: None, diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 30bd356cd45..2fb02edb149 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -7907,6 +7907,10 @@ "pay_currency": { "type": "string", "nullable": true + }, + "network": { + "type": "string", + "nullable": true } } },
2024-05-27T11:46:13Z
## Description <!-- Describe your changes in detail --> The customer will be able to choose the supported network in case of doing cryptocurrency payments via Cryptopay. The supported networks will be shown on SDK and the chosen network will be passed on to Cryptopay. If no network is chosen then Cryptopay will choose the default network for that transaction. Also the currency `BUSD` is no longer supported by Cryptopay, hence it is being removed from list of supported crypto currencies. Reference: https://developers.cryptopay.me/guides/currencies/currencies ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/4778 ## 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)? --> Payments Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 120, "currency": "USD", "confirm": true, "email": "guest@example.com", "return_url": "https://google.com", "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_experience": "redirect_to_url", "payment_method_data": { "crypto": { "pay_currency": "LTC", "network": "bnb_smart_chain" } } }' ``` Payments Response: ``` { "payment_id": "pay_7v0mzPuohoNWvobOcUlV", "merchant_id": "merchant_1713942708", "status": "requires_customer_action", "amount": 120, "net_amount": 120, "amount_capturable": 120, "amount_received": 120, "connector": "cryptopay", "client_secret": "pay_7v0mzPuohoNWvobOcUlV_secret_QaYlaPPZ07arI9NStJNQ", "created": "2024-05-27T11:36:42.124Z", "currency": "USD", "customer_id": null, "customer": null, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "crypto", "payment_method_data": { "crypto": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_7v0mzPuohoNWvobOcUlV/merchant_1713942708/pay_7v0mzPuohoNWvobOcUlV_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": "redirect_to_url", "payment_method_type": "crypto_currency", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "25bf87e4-55bd-4dc7-a807-8998c95cb496", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_7v0mzPuohoNWvobOcUlV_1", "payment_link": null, "profile_id": "pro_HgGSGQyaRys8iaDsi7OX", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_z8isFAS0iNcgES4VN5Lm", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-27T11:51:42.124Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-27T11:36:42.715Z", "charges": null, "frm_metadata": null } ``` List payment methods for a Merchant Request: ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_BUUFr1ZME4rkMHDeGapK_secret_WhDFJZOH4FBIU9p4Xbzp' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' ``` List payment methods for a Merchant Response: ``` { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "crypto", "payment_method_types": [ { "payment_method_type": "crypto_currency", "payment_experience": [ { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "cryptopay" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.crypto.pay_currency": { "required_field": "payment_method_data.crypto.pay_currency", "display_name": "currency", "field_type": { "user_currency": { "options": [ "BTC", "LTC", "ETH", "XRP", "XLM", "BCH", "ADA", "SOL", "SHIB", "TRX", "DOGE", "BNB", "USDT", "USDC", "DAI" ] } }, "value": null }, "payment_method_data.crypto.network": { "required_field": "payment_method_data.crypto.network", "display_name": "network", "field_type": "text", "value": null } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal" } ```
7645edfa2e00500da3f8f117cc1a485fe1f41ab5
Payments Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 120, "currency": "USD", "confirm": true, "email": "guest@example.com", "return_url": "https://google.com", "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_experience": "redirect_to_url", "payment_method_data": { "crypto": { "pay_currency": "LTC", "network": "bnb_smart_chain" } } }' ``` Payments Response: ``` { "payment_id": "pay_7v0mzPuohoNWvobOcUlV", "merchant_id": "merchant_1713942708", "status": "requires_customer_action", "amount": 120, "net_amount": 120, "amount_capturable": 120, "amount_received": 120, "connector": "cryptopay", "client_secret": "pay_7v0mzPuohoNWvobOcUlV_secret_QaYlaPPZ07arI9NStJNQ", "created": "2024-05-27T11:36:42.124Z", "currency": "USD", "customer_id": null, "customer": null, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "crypto", "payment_method_data": { "crypto": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_7v0mzPuohoNWvobOcUlV/merchant_1713942708/pay_7v0mzPuohoNWvobOcUlV_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": "redirect_to_url", "payment_method_type": "crypto_currency", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "25bf87e4-55bd-4dc7-a807-8998c95cb496", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_7v0mzPuohoNWvobOcUlV_1", "payment_link": null, "profile_id": "pro_HgGSGQyaRys8iaDsi7OX", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_z8isFAS0iNcgES4VN5Lm", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-27T11:51:42.124Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-27T11:36:42.715Z", "charges": null, "frm_metadata": null } ``` List payment methods for a Merchant Request: ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_BUUFr1ZME4rkMHDeGapK_secret_WhDFJZOH4FBIU9p4Xbzp' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' ``` List payment methods for a Merchant Response: ``` { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "crypto", "payment_method_types": [ { "payment_method_type": "crypto_currency", "payment_experience": [ { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "cryptopay" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.crypto.pay_currency": { "required_field": "payment_method_data.crypto.pay_currency", "display_name": "currency", "field_type": { "user_currency": { "options": [ "BTC", "LTC", "ETH", "XRP", "XLM", "BCH", "ADA", "SOL", "SHIB", "TRX", "DOGE", "BNB", "USDT", "USDC", "DAI" ] } }, "value": null }, "payment_method_data.crypto.network": { "required_field": "payment_method_data.crypto.network", "display_name": "network", "field_type": "text", "value": null } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal" } ```
[ "crates/api_models/src/payments.rs", "crates/hyperswitch_domain_models/src/payment_method_data.rs", "crates/router/src/configs/defaults.rs", "crates/router/src/connector/cryptopay/transformers.rs", "crates/router/tests/connectors/bitpay.rs", "crates/router/tests/connectors/coinbase.rs", "crates/router/t...
juspay/hyperswitch
juspay__hyperswitch-4775
Bug: fix: Ability to change TOTP issuer name depending on the env As of now, the issuer name in TOTP is always "Hyperswitch" independent of env. As TOTP will be present in multiple environments, we need to have different issuer names for all the environments, so that user can easily identify the TOTP.
diff --git a/config/config.example.toml b/config/config.example.toml index 8aa0ca9e52f..ac428298e73 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -351,8 +351,9 @@ email_role_arn = "" # The amazon resource name ( arn ) of the role which sts_role_session_name = "" # An identifier for the assumed role session, used to uniquely identify a session. [user] -password_validity_in_days = 90 # Number of days after which password should be updated -two_factor_auth_expiry_in_secs = 300 # Number of seconds after which 2FA should be done again if doing update/change from inside +password_validity_in_days = 90 # Number of days after which password should be updated +two_factor_auth_expiry_in_secs = 300 # Number of seconds after which 2FA should be done again if doing update/change from inside +totp_issuer_name = "Hyperswitch" # Name of the issuer for TOTP #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index f6ed3ca5ea5..8d76771f897 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -114,6 +114,7 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw [user] password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 +totp_issuer_name = "Hyperswitch Integ" [frm] enabled = true diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 37b35eb47e7..65f8d87215a 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -121,6 +121,7 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw [user] password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 +totp_issuer_name = "Hyperswitch Production" [frm] enabled = false diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index fc496e34fc3..94f6d4b3430 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -121,6 +121,7 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw [user] password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 +totp_issuer_name = "Hyperswitch Sandbox" [frm] enabled = true diff --git a/config/development.toml b/config/development.toml index d12a667b631..25fe55e6057 100644 --- a/config/development.toml +++ b/config/development.toml @@ -270,6 +270,7 @@ sts_role_session_name = "" [user] password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 +totp_issuer_name = "Hyperswitch Dev" [bank_config.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" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 3f6c9523e93..f43ceca893d 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -54,6 +54,7 @@ recon_admin_api_key = "recon_test_admin" [user] password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 +totp_issuer_name = "Hyperswitch" [locker] host = "" diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index c71ed4496b0..9aa879a4387 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -436,6 +436,7 @@ pub struct Secrets { pub struct UserSettings { pub password_validity_in_days: u16, pub two_factor_auth_expiry_in_secs: i64, + pub totp_issuer_name: String, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index 3c6cd8b6ccd..c7615aa4be4 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -1,15 +1,17 @@ pub const MAX_NAME_LENGTH: usize = 70; pub const MAX_COMPANY_NAME_LENGTH: usize = 70; pub const BUSINESS_EMAIL: &str = "biz@hyperswitch.io"; + pub const RECOVERY_CODES_COUNT: usize = 8; pub const RECOVERY_CODE_LENGTH: usize = 8; // This is without counting the hyphen in between -pub const TOTP_ISSUER_NAME: &str = "Hyperswitch"; + /// The number of digits composing the auth code. pub const TOTP_DIGITS: usize = 6; /// Duration in seconds of a step. pub const TOTP_VALIDITY_DURATION_IN_SECONDS: u64 = 30; /// Number of totps allowed as network delay. 1 would mean one totp before current totp and one totp after are valids. pub const TOTP_TOLERANCE: u8 = 1; + pub const MAX_PASSWORD_LENGTH: usize = 70; pub const MIN_PASSWORD_LENGTH: usize = 8; diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index c259e87c93d..f4751c3a55a 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1635,7 +1635,11 @@ pub async fn begin_totp( })); } - let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), None)?; + let totp = tfa_utils::generate_default_totp( + user_from_db.get_email(), + None, + state.conf.user.totp_issuer_name.clone(), + )?; let secret = totp.get_secret_base32().into(); tfa_utils::insert_totp_secret_in_redis(&state, &user_token.user_id, &secret).await?; @@ -1668,7 +1672,12 @@ pub async fn reset_totp( return Err(UserErrors::TwoFactorAuthRequired.into()); } - let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), None)?; + let totp = tfa_utils::generate_default_totp( + user_from_db.get_email(), + None, + state.conf.user.totp_issuer_name.clone(), + )?; + let secret = totp.get_secret_base32().into(); tfa_utils::insert_totp_secret_in_redis(&state, &user_token.user_id, &secret).await?; @@ -1701,7 +1710,11 @@ pub async fn verify_totp( .await? .ok_or(UserErrors::InternalServerError)?; - let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), Some(user_totp_secret))?; + let totp = tfa_utils::generate_default_totp( + user_from_db.get_email(), + Some(user_totp_secret), + state.conf.user.totp_issuer_name.clone(), + )?; if totp .generate_current() @@ -1732,7 +1745,11 @@ pub async fn update_totp( .await? .ok_or(UserErrors::TotpSecretNotFound)?; - let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), Some(new_totp_secret))?; + let totp = tfa_utils::generate_default_totp( + user_from_db.get_email(), + Some(new_totp_secret), + state.conf.user.totp_issuer_name.clone(), + )?; if totp .generate_current() diff --git a/crates/router/src/utils/user/two_factor_auth.rs b/crates/router/src/utils/user/two_factor_auth.rs index a0915f3ed86..f64eda4dc5a 100644 --- a/crates/router/src/utils/user/two_factor_auth.rs +++ b/crates/router/src/utils/user/two_factor_auth.rs @@ -12,6 +12,7 @@ use crate::{ pub fn generate_default_totp( email: pii::Email, secret: Option<masking::Secret<String>>, + issuer: String, ) -> UserResult<TOTP> { let secret = secret .map(|sec| totp_rs::Secret::Encoded(sec.expose())) @@ -25,7 +26,7 @@ pub fn generate_default_totp( consts::user::TOTP_TOLERANCE, consts::user::TOTP_VALIDITY_DURATION_IN_SECONDS, secret, - Some(consts::user::TOTP_ISSUER_NAME.to_string()), + Some(issuer), email.expose().expose(), ) .change_context(UserErrors::InternalServerError) diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 2abe90f6086..e46a710054e 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -31,6 +31,7 @@ jwt_secret = "secret" [user] password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 +totp_issuer_name = "Hyperswitch" [locker] host = ""
2024-05-27T09:50:23Z
## Description <!-- Describe your changes in detail --> This PR adds configs for TOTP Issuer (to easily change issuer name of TOTP) ### 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` 3. `crates/router/src/configs` 4. `loadtest/config` --> 1. `config/config.example.toml` 2. `config/deployments/integration_test.toml` 3. `config/deployments/production.toml` 4. `config/deployments/sandbox.toml` 5. `config/development.toml` 6. `config/docker_compose.toml` 7. `loadtest/config/development.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). --> Closes #4775. ## 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/2fa/totp/begin' \ --header 'Authorization: Bearer SPT with Purpose as TOTP' \ ``` ``` { "secret": { "secret": "INY6LEAFGX3OWJFVBXBUM7OMH4KLNI76", "totp_url": "otpauth://totp/Hyper:mani.dchandra%40juspay.in?secret=INY6LEAFGX3OWJFVBXBUM7OMH4KLNI76&issuer=Hyper" } } ``` The `totp_url` field in the above response contains issuer as `Hyper` and this is coming from config. - In integ, issuer name will be: `Hyperswitch Integ` - In sandbox, issuer name will be: `Hyperswitch Sandbox` - In production, issuer name will be: `Hyperswitch Prod` - In local, issuer name will be: `Hyperswitch Deb`
15d6c3e846a77dec6b6a5165d86044a9b9fd52f1
``` curl --location 'http://localhost:8080/user/2fa/totp/begin' \ --header 'Authorization: Bearer SPT with Purpose as TOTP' \ ``` ``` { "secret": { "secret": "INY6LEAFGX3OWJFVBXBUM7OMH4KLNI76", "totp_url": "otpauth://totp/Hyper:mani.dchandra%40juspay.in?secret=INY6LEAFGX3OWJFVBXBUM7OMH4KLNI76&issuer=Hyper" } } ``` The `totp_url` field in the above response contains issuer as `Hyper` and this is coming from config. - In integ, issuer name will be: `Hyperswitch Integ` - In sandbox, issuer name will be: `Hyperswitch Sandbox` - In production, issuer name will be: `Hyperswitch Prod` - In local, issuer name will be: `Hyperswitch Deb`
[ "config/config.example.toml", "config/deployments/integration_test.toml", "config/deployments/production.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/router/src/configs/settings.rs", "crates/router/src/consts/user.rs", "crates/router/src/...
juspay/hyperswitch
juspay__hyperswitch-4059
Bug: [REFACTOR]: [Fiserv] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/fiserv/transformer.rs` ### :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?
diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs index 2dedb92d1dd..8945f7814b2 100644 --- a/crates/router/src/connector/fiserv/transformers.rs +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -386,7 +386,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, FiservSyncResponse, T, types::Pa ) -> Result<Self, Self::Error> { let gateway_resp = match item.response.sync_responses.first() { Some(gateway_response) => gateway_response, - _ => Err(errors::ConnectorError::ResponseHandlingFailed)?, + None => Err(errors::ConnectorError::ResponseHandlingFailed)?, }; Ok(Self {
2024-05-26T16:39:04Z
## Description <!-- Describe your changes in detail --> This PR closes #4059 removes the default case handling in `hyperswitch/crates/router/src/connector/fiserv/transformer.rs`. ### 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` --> `hyperswitch/crates/router/src/connector/fiserv/transformer.rs` ## 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? No testing required
b847606d665388fba898425b31dd5f207f60a56e
No testing required
[ "crates/router/src/connector/fiserv/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4764
Bug: feat: Use redis in Begin and Verify TOTP - Currently begin TOTP is directly replacing the secret in the db. This will cause issues when user didn't complete generating recovery codes. So we should keep the new secret in redis temporarily. - And Verify TOTP should not complete the TOTP flow as user should complete the generation of recovery codes. - There should be a new API which verifies the TOTP with the redis's secret and update the DB.
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 5423fc830a5..0c8678d2ef8 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -255,12 +255,11 @@ pub struct BeginTotpResponse { pub struct TotpSecret { pub secret: Secret<String>, pub totp_url: Secret<String>, - pub recovery_codes: Vec<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyTotpRequest { - pub totp: Option<Secret<String>>, + pub totp: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index 2f347dc3d3e..3c6cd8b6ccd 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -13,5 +13,7 @@ pub const TOTP_TOLERANCE: u8 = 1; pub const MAX_PASSWORD_LENGTH: usize = 70; pub const MIN_PASSWORD_LENGTH: usize = 8; -pub const TOTP_PREFIX: &str = "TOTP_"; +pub const REDIS_TOTP_PREFIX: &str = "TOTP_"; pub const REDIS_RECOVERY_CODE_PREFIX: &str = "RC_"; +pub const REDIS_TOTP_SECRET_PREFIX: &str = "TOTP_SEC_"; +pub const REDIS_TOTP_SECRET_TTL_IN_SECS: i64 = 5 * 60; // 5 minutes diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index adcf8794b83..865bc1d4124 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -78,6 +78,8 @@ pub enum UserErrors { TwoFactorAuthRequired, #[error("TwoFactorAuthNotSetup")] TwoFactorAuthNotSetup, + #[error("TOTP secret not found")] + TotpSecretNotFound, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -199,6 +201,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::TwoFactorAuthNotSetup => { AER::BadRequest(ApiError::new(sub_code, 41, self.get_error_message(), None)) } + Self::TotpSecretNotFound => { + AER::BadRequest(ApiError::new(sub_code, 42, self.get_error_message(), None)) + } } } } @@ -241,6 +246,7 @@ impl UserErrors { Self::InvalidRecoveryCode => "Invalid Recovery Code", Self::TwoFactorAuthRequired => "Two factor auth required", Self::TwoFactorAuthNotSetup => "Two factor auth not setup", + Self::TotpSecretNotFound => "TOTP secret not found", } } } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 4fd9fa865cd..7b6e8ebd365 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1633,41 +1633,14 @@ pub async fn begin_totp( } let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), None)?; - let recovery_codes = domain::RecoveryCodes::generate_new(); - - let key_store = user_from_db.get_or_create_key_store(&state).await?; + let secret = totp.get_secret_base32().into(); - state - .store - .update_user_by_user_id( - user_from_db.get_user_id(), - storage_user::UserUpdate::TotpUpdate { - totp_status: Some(TotpStatus::InProgress), - totp_secret: Some( - // TODO: Impl conversion trait for User and move this there - domain::types::encrypt::<String, masking::WithType>( - totp.get_secret_base32().into(), - key_store.key.peek(), - ) - .await - .change_context(UserErrors::InternalServerError)? - .into(), - ), - totp_recovery_codes: Some( - recovery_codes - .get_hashed() - .change_context(UserErrors::InternalServerError)?, - ), - }, - ) - .await - .change_context(UserErrors::InternalServerError)?; + tfa_utils::insert_totp_secret_in_redis(&state, &user_token.user_id, &secret).await?; Ok(ApplicationResponse::Json(user_api::BeginTotpResponse { secret: Some(user_api::TotpSecret { - secret: totp.get_secret_base32().into(), + secret, totp_url: totp.get_url().into(), - recovery_codes: recovery_codes.into_inner(), }), })) } @@ -1684,54 +1657,93 @@ pub async fn verify_totp( .change_context(UserErrors::InternalServerError)? .into(); - if let Some(user_totp) = req.totp { - if user_from_db.get_totp_status() == TotpStatus::NotSet { - return Err(UserErrors::TotpNotSetup.into()); - } + if user_from_db.get_totp_status() != TotpStatus::Set { + return Err(UserErrors::TotpNotSetup.into()); + } - let user_totp_secret = user_from_db - .decrypt_and_get_totp_secret(&state) - .await? - .ok_or(UserErrors::InternalServerError)?; + let user_totp_secret = user_from_db + .decrypt_and_get_totp_secret(&state) + .await? + .ok_or(UserErrors::InternalServerError)?; - let totp = - tfa_utils::generate_default_totp(user_from_db.get_email(), Some(user_totp_secret))?; + let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), Some(user_totp_secret))?; - if totp - .generate_current() - .change_context(UserErrors::InternalServerError)? - != user_totp.expose() - { - return Err(UserErrors::InvalidTotp.into()); - } + if totp + .generate_current() + .change_context(UserErrors::InternalServerError)? + != req.totp.expose() + { + return Err(UserErrors::InvalidTotp.into()); + } - if user_from_db.get_totp_status() == TotpStatus::InProgress { - state - .store - .update_user_by_user_id( - user_from_db.get_user_id(), - storage_user::UserUpdate::TotpUpdate { - totp_status: Some(TotpStatus::Set), - totp_secret: None, - totp_recovery_codes: None, - }, - ) - .await - .change_context(UserErrors::InternalServerError)?; - } + tfa_utils::insert_totp_in_redis(&state, &user_token.user_id).await?; + + Ok(ApplicationResponse::StatusOk) +} + +pub async fn update_totp( + state: AppState, + user_token: auth::UserFromSinglePurposeToken, + req: user_api::VerifyTotpRequest, +) -> UserResponse<()> { + let user_from_db: domain::UserFromStorage = state + .store + .find_user_by_id(&user_token.user_id) + .await + .change_context(UserErrors::InternalServerError)? + .into(); + + let new_totp_secret = tfa_utils::get_totp_secret_from_redis(&state, &user_token.user_id) + .await? + .ok_or(UserErrors::TotpSecretNotFound)?; + + let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), Some(new_totp_secret))?; + + if totp + .generate_current() + .change_context(UserErrors::InternalServerError)? + != req.totp.expose() + { + return Err(UserErrors::InvalidTotp.into()); } - let current_flow = domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::TOTP.into())?; - let next_flow = current_flow.next(user_from_db, &state).await?; - let token = next_flow.get_token(&state).await?; + let key_store = user_from_db.get_or_create_key_store(&state).await?; - auth::cookies::set_cookie_response( - user_api::TokenResponse { - token: token.clone(), - token_type: next_flow.get_flow().into(), - }, - token, - ) + state + .store + .update_user_by_user_id( + &user_token.user_id, + storage_user::UserUpdate::TotpUpdate { + totp_status: None, + totp_secret: Some( + // TODO: Impl conversion trait for User and move this there + domain::types::encrypt::<String, masking::WithType>( + totp.get_secret_base32().into(), + key_store.key.peek(), + ) + .await + .change_context(UserErrors::InternalServerError)? + .into(), + ), + + totp_recovery_codes: None, + }, + ) + .await + .change_context(UserErrors::InternalServerError)?; + + let _ = tfa_utils::delete_totp_secret_from_redis(&state, &user_token.user_id) + .await + .map_err(|e| logger::error!(?e)); + + // This is not the main task of this API, so we don't throw error if this fails. + // Any following API which requires TOTP will throw error if TOTP is not set in redis + // and FE will ask user to enter TOTP again + let _ = tfa_utils::insert_totp_in_redis(&state, &user_token.user_id) + .await + .map_err(|e| logger::error!(?e)); + + Ok(ApplicationResponse::StatusOk) } pub async fn generate_recovery_codes( diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index bad5ab5a926..b38479cd2b6 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1209,17 +1209,33 @@ impl User { web::resource("/data") .route(web::get().to(get_multiple_dashboard_metadata)) .route(web::post().to(set_dashboard_metadata)), - ) - .service(web::resource("/totp/begin").route(web::get().to(totp_begin))) - .service(web::resource("/totp/verify").route(web::post().to(totp_verify))) - .service( - web::resource("/2fa/terminate").route(web::get().to(terminate_two_factor_auth)), ); + // Two factor auth routes route = route.service( - web::scope("/recovery_code") - .service(web::resource("/verify").route(web::post().to(verify_recovery_code))) - .service(web::resource("/generate").route(web::post().to(generate_recovery_codes))), + web::scope("/2fa") + .service( + web::scope("/totp") + .service(web::resource("/begin").route(web::get().to(totp_begin))) + .service( + web::resource("/verify") + .route(web::post().to(totp_verify)) + .route(web::put().to(totp_update)), + ), + ) + .service( + web::scope("/recovery_code") + .service( + web::resource("/verify").route(web::post().to(verify_recovery_code)), + ) + .service( + web::resource("/generate") + .route(web::get().to(generate_recovery_codes)), + ), + ) + .service( + web::resource("/terminate").route(web::get().to(terminate_two_factor_auth)), + ), ); #[cfg(feature = "email")] diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 75821bbd2ba..9e53eb35473 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -215,9 +215,11 @@ impl From<Flow> for ApiIdentifier { | Flow::UpdateUserAccountDetails | Flow::TotpBegin | Flow::TotpVerify + | Flow::TotpUpdate | Flow::RecoveryCodeVerify | Flow::RecoveryCodesGenerate | Flow::TerminateTwoFactorAuth => Self::User, + Flow::ListRoles | Flow::GetRole | Flow::GetRoleFromToken diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 6b8015ac3e5..5ba7ec8da25 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -684,6 +684,24 @@ pub async fn verify_recovery_code( .await } +pub async fn totp_update( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_api::VerifyTotpRequest>, +) -> HttpResponse { + let flow = Flow::TotpUpdate; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, user, req_body, _| user_core::update_totp(state, user, req_body), + &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP), + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn generate_recovery_codes(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::RecoveryCodesGenerate; Box::pin(api::server_wrap( diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 9c67dbfcab5..db1d0ea2508 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -1,9 +1,10 @@ -use std::collections::HashMap; +use std::{collections::HashMap, sync::Arc}; 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 redis_interface::RedisConnectionPool; use crate::{ core::errors::{StorageError, UserErrors, UserResult}, @@ -191,3 +192,11 @@ pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> maskin user_api::SignInResponse::MerchantSelect(data) => data.token.clone(), } } + +pub fn get_redis_connection(state: &AppState) -> UserResult<Arc<RedisConnectionPool>> { + state + .store + .get_redis_conn() + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get redis connection") +} diff --git a/crates/router/src/utils/user/two_factor_auth.rs b/crates/router/src/utils/user/two_factor_auth.rs index e9e3f66005c..6bd693c07f5 100644 --- a/crates/router/src/utils/user/two_factor_auth.rs +++ b/crates/router/src/utils/user/two_factor_auth.rs @@ -1,9 +1,6 @@ -use std::sync::Arc; - use common_utils::pii; use error_stack::ResultExt; -use masking::ExposeInterface; -use redis_interface::RedisConnectionPool; +use masking::{ExposeInterface, PeekInterface}; use totp_rs::{Algorithm, TOTP}; use crate::{ @@ -35,8 +32,8 @@ pub fn generate_default_totp( } pub async fn check_totp_in_redis(state: &AppState, user_id: &str) -> UserResult<bool> { - let redis_conn = get_redis_connection(state)?; - let key = format!("{}{}", consts::user::TOTP_PREFIX, user_id); + let redis_conn = super::get_redis_connection(state)?; + let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn .exists::<()>(&key) .await @@ -44,7 +41,7 @@ pub async fn check_totp_in_redis(state: &AppState, user_id: &str) -> UserResult< } pub async fn check_recovery_code_in_redis(state: &AppState, user_id: &str) -> UserResult<bool> { - let redis_conn = get_redis_connection(state)?; + let redis_conn = super::get_redis_connection(state)?; let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn .exists::<()>(&key) @@ -52,16 +49,62 @@ pub async fn check_recovery_code_in_redis(state: &AppState, user_id: &str) -> Us .change_context(UserErrors::InternalServerError) } -fn get_redis_connection(state: &AppState) -> UserResult<Arc<RedisConnectionPool>> { - state - .store - .get_redis_conn() +pub async fn insert_totp_in_redis(state: &AppState, user_id: &str) -> UserResult<()> { + let redis_conn = super::get_redis_connection(state)?; + let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); + redis_conn + .set_key_with_expiry( + key.as_str(), + common_utils::date_time::now_unix_timestamp(), + state.conf.user.two_factor_auth_expiry_in_secs, + ) + .await .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to get redis connection") +} + +pub async fn insert_totp_secret_in_redis( + state: &AppState, + user_id: &str, + secret: &masking::Secret<String>, +) -> UserResult<()> { + let redis_conn = super::get_redis_connection(state)?; + redis_conn + .set_key_with_expiry( + &get_totp_secret_key(user_id), + secret.peek(), + consts::user::REDIS_TOTP_SECRET_TTL_IN_SECS, + ) + .await + .change_context(UserErrors::InternalServerError) +} + +pub async fn get_totp_secret_from_redis( + state: &AppState, + user_id: &str, +) -> UserResult<Option<masking::Secret<String>>> { + let redis_conn = super::get_redis_connection(state)?; + redis_conn + .get_key::<Option<String>>(&get_totp_secret_key(user_id)) + .await + .change_context(UserErrors::InternalServerError) + .map(|secret| secret.map(Into::into)) +} + +pub async fn delete_totp_secret_from_redis(state: &AppState, user_id: &str) -> UserResult<()> { + let redis_conn = super::get_redis_connection(state)?; + redis_conn + .delete_key(&get_totp_secret_key(user_id)) + .await + .change_context(UserErrors::InternalServerError) + .map(|_| ()) +} + +fn get_totp_secret_key(user_id: &str) -> String { + format!("{}{}", consts::user::REDIS_TOTP_SECRET_PREFIX, user_id) } pub async fn insert_recovery_code_in_redis(state: &AppState, user_id: &str) -> UserResult<()> { - let redis_conn = get_redis_connection(state)?; + let redis_conn = super::get_redis_connection(state)?; let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn .set_key_with_expiry( diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 35b55b6fb97..1bfc20ff1ca 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -406,6 +406,8 @@ pub enum Flow { TotpBegin, /// Verify TOTP TotpVerify, + /// Update TOTP secret + TotpUpdate, /// Verify Access Code RecoveryCodeVerify, /// Generate or Regenerate recovery codes
2024-05-24T12:57:30Z
## Description <!-- Describe your changes in detail --> - Begin TOTP will now insert the TOTP secret in redis instead of DB directly, which allows the old secret to stay if it exists and recovery codes are also removed from Begin TOTP. - Verify TOTP will now send 200 OK and puts the timestamp in the redis when the TOTP is verified. - Update TOTP is a new API which will take the TOTP and verifies the TOTP against the redis secret instead of db secret. If the TOTP is correct, it will replace the redis secret in the db. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #4764. Closes #4707. ## 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. TOTP Routes 1. Begin TOTP ```curl curl --location 'http://localhost:8080/user/2fa/totp/begin' \ --header 'Authorization: Bearer SPT with Purpose as TOTP' ``` ``` { "secret": { "secret": "Q54GEKFSVTP4FU3YHDFMEN5KMGD2P3IN", "totp_url": "otpauth://totp/Hyperswitch:mani.dchandra%40juspay.in?secret=Q54GEKFSVTP4FU3YHDFMEN5KMGD2P3IN&issuer=Hyperswitch" } } ``` 2. Verify TOTP ``` curl --location 'http://localhost:8080/user/2fa/totp/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer SPT with Purpose as TOTP' \ --data '{ "totp": "701394" }' ``` Response will be 200 OK if the TOTP is correct. 2. Recovery Codes Routes 1. Verify Recovery Code ``` curl --location 'http://localhost:8080/user/2fa/recovery_code/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer SPT with Purpose as TOTP' \ --data '{ "recovery_code": "m14a-0ni6" }' ``` Response will be 200 OK if the Recovery code is correct. 2. Generate Recovery codes ``` curl --location 'http://localhost:8080/user/2fa/recovery_code/generate' \ --header 'Authorization: Bearer SPT with Purpose as TOTP' \ ``` ``` { "recovery_codes": [ "w5fM-NLm0", "TumH-oyXE", "wDIr-zEmu", "HZjm-e16M", "Q4qB-MupL", "5BtN-vRuY", "4vG6-URGf", "Dbq8-n5V1" ] } ```
d686ec7acda6ce852fac8d7413f9ba903adcee1d
1. TOTP Routes 1. Begin TOTP ```curl curl --location 'http://localhost:8080/user/2fa/totp/begin' \ --header 'Authorization: Bearer SPT with Purpose as TOTP' ``` ``` { "secret": { "secret": "Q54GEKFSVTP4FU3YHDFMEN5KMGD2P3IN", "totp_url": "otpauth://totp/Hyperswitch:mani.dchandra%40juspay.in?secret=Q54GEKFSVTP4FU3YHDFMEN5KMGD2P3IN&issuer=Hyperswitch" } } ``` 2. Verify TOTP ``` curl --location 'http://localhost:8080/user/2fa/totp/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer SPT with Purpose as TOTP' \ --data '{ "totp": "701394" }' ``` Response will be 200 OK if the TOTP is correct. 2. Recovery Codes Routes 1. Verify Recovery Code ``` curl --location 'http://localhost:8080/user/2fa/recovery_code/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer SPT with Purpose as TOTP' \ --data '{ "recovery_code": "m14a-0ni6" }' ``` Response will be 200 OK if the Recovery code is correct. 2. Generate Recovery codes ``` curl --location 'http://localhost:8080/user/2fa/recovery_code/generate' \ --header 'Authorization: Bearer SPT with Purpose as TOTP' \ ``` ``` { "recovery_codes": [ "w5fM-NLm0", "TumH-oyXE", "wDIr-zEmu", "HZjm-e16M", "Q4qB-MupL", "5BtN-vRuY", "4vG6-URGf", "Dbq8-n5V1" ] } ```
[ "crates/api_models/src/user.rs", "crates/router/src/consts/user.rs", "crates/router/src/core/errors/user.rs", "crates/router/src/core/user.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/user.rs", "crates/router/src/utils/user.rs", "crates/...
juspay/hyperswitch
juspay__hyperswitch-4673
Bug: Add audit events for PaymentConfirm update
diff --git a/config/development.toml b/config/development.toml index 25fe55e6057..78b10192f1e 100644 --- a/config/development.toml +++ b/config/development.toml @@ -634,4 +634,4 @@ sdk_eligible_payment_methods = "card" enabled = false [multitenancy.tenants] -public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = ""} \ No newline at end of file +public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = ""} diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index ea5f2c0ecb4..cff51ed8091 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -29,6 +29,7 @@ use crate::{ utils as core_utils, }, db::StorageInterface, + events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ @@ -935,7 +936,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen async fn update_trackers<'b>( &'b self, state: &'b SessionState, - _req_state: ReqState, + req_state: ReqState, mut payment_data: PaymentData<F>, customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, @@ -1294,6 +1295,19 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen payment_data.payment_intent = payment_intent; payment_data.payment_attempt = payment_attempt; + let client_src = payment_data.payment_attempt.client_source.clone(); + let client_ver = payment_data.payment_attempt.client_version.clone(); + + let frm_message = payment_data.frm_message.clone(); + req_state + .event_context + .event(AuditEvent::new(AuditEventType::PaymentConfirm { + client_src, + client_ver, + frm_message, + })) + .with(payment_data.to_event()) + .emit(); Ok((Box::new(self), payment_data)) } } diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs index 0f186e691b9..6fc19018655 100644 --- a/crates/router/src/events/audit_events.rs +++ b/crates/router/src/events/audit_events.rs @@ -1,18 +1,27 @@ +use diesel_models::fraud_check::FraudCheck; use events::{Event, EventInfo}; use serde::Serialize; use time::PrimitiveDateTime; - #[derive(Debug, Clone, Serialize)] #[serde(tag = "event_type")] pub enum AuditEventType { - Error { error_message: String }, + Error { + error_message: String, + }, PaymentCreated, ConnectorDecided, ConnectorCalled, RefundCreated, RefundSuccess, RefundFail, - PaymentCancelled { cancellation_reason: Option<String> }, + PaymentConfirm { + client_src: Option<String>, + client_ver: Option<String>, + frm_message: Option<FraudCheck>, + }, + PaymentCancelled { + cancellation_reason: Option<String>, + }, } #[derive(Debug, Clone, Serialize)] @@ -43,6 +52,7 @@ impl Event for AuditEvent { let event_type = match &self.event_type { AuditEventType::Error { .. } => "error", AuditEventType::PaymentCreated => "payment_created", + AuditEventType::PaymentConfirm { .. } => "payment_confirm", AuditEventType::ConnectorDecided => "connector_decided", AuditEventType::ConnectorCalled => "connector_called", AuditEventType::RefundCreated => "refund_created",
2024-05-24T11:57:10Z
## Description - Pass along request_state to payment_core - Update `updatetrackers` trait to accept request state - Update the paymentconfirm implementation of updatetracker to generate an event ### 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). --> - Generating domain events that can be used to track the high level overview of any process ## How did you test it? ### Test Case Description - Implemented an event trigger that activates whenever the payment confirm API is utilized. This event triggers an audit event, the details of which are subsequently reflected in the Kafka UI. - Create a payment & then confirm it - Fields that need to be tested are: `client_src`, `client_ver`and `frm_message`. ``` {"topic" = "hyperswitch-audit-events"} ``` <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ![image](https://github.com/juspay/hyperswitch/assets/89402434/c24bf03b-3002-41b2-ab25-d786285ea233)
ba0a1e95b72c0acf5bde81d424aa8fe220c40a22
### Test Case Description - Implemented an event trigger that activates whenever the payment confirm API is utilized. This event triggers an audit event, the details of which are subsequently reflected in the Kafka UI. - Create a payment & then confirm it - Fields that need to be tested are: `client_src`, `client_ver`and `frm_message`. ``` {"topic" = "hyperswitch-audit-events"} ``` ![image](https://github.com/juspay/hyperswitch/assets/89402434/c24bf03b-3002-41b2-ab25-d786285ea233)
[ "config/development.toml", "crates/router/src/core/payments/operations/payment_confirm.rs", "crates/router/src/events/audit_events.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4824
Bug: [BUG] FIx routing field validation in payments request ### Feature Description As of now, routing field in the payments request wasn't being validated, have to add validations for the same ### Possible Implementation Jus have to add validations in payments create, update and confirm ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index a3ed16def0c..b8b3ea3a971 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -1336,6 +1336,16 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir .clone() .ok_or(report!(errors::ApiErrorResponse::PaymentNotFound))?; + let _request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request + .routing + .clone() + .map(|val| val.parse_value("RoutingAlgorithm")) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "Invalid straight through routing rules format".to_string(), + }) + .attach_printable("Invalid straight through routing rules format")?; + Ok(( Box::new(self), operations::ValidateResult { diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 68f8b7056c0..1a0e27a7d68 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -735,6 +735,16 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate )?; } + let _request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request + .routing + .clone() + .map(|val| val.parse_value("RoutingAlgorithm")) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "Invalid straight through routing rules format".to_string(), + }) + .attach_printable("Invalid straight through routing rules format")?; + Ok(( Box::new(self), operations::ValidateResult { diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index d7351b3b5ba..a671a6b5596 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -782,6 +782,16 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate &request.mandate_id, )?; + let _request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request + .routing + .clone() + .map(|val| val.parse_value("RoutingAlgorithm")) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "Invalid straight through routing rules format".to_string(), + }) + .attach_printable("Invalid straight through routing rules format")?; + Ok(( Box::new(self), operations::ValidateResult {
2024-05-24T11:54:21Z
## Description <!-- Describe your changes in detail --> Added validation for straight through routing in payments request ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. By using invalid req body for `routing` field (4xx should be thrown instead of 5xx) ``` curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_wnIRnsZGiq0NHNq3WskWv4Kw7Eg7InEHASiXrAXA4zM2MoJMvL2fCMDWNt8Ieg5I' \ --data-raw '{ "amount": 200, "currency": "EUR", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer1", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "routing":{ "type": "single", "data": {"connector": "strip", "merchant_connector_id": "mca_123"} }, "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "2025", "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": "john", "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": "8056594430", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response - ``` { "error": { "type": "invalid_request", "message": "Invalid straight through routing rules format", "code": "IR_06" } } ```
e41d5e25dfd4d3113edac11b249e847f8718b263
1. By using invalid req body for `routing` field (4xx should be thrown instead of 5xx) ``` curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_wnIRnsZGiq0NHNq3WskWv4Kw7Eg7InEHASiXrAXA4zM2MoJMvL2fCMDWNt8Ieg5I' \ --data-raw '{ "amount": 200, "currency": "EUR", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer1", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "routing":{ "type": "single", "data": {"connector": "strip", "merchant_connector_id": "mca_123"} }, "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "2025", "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": "john", "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": "8056594430", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response - ``` { "error": { "type": "invalid_request", "message": "Invalid straight through routing rules format", "code": "IR_06" } } ```
[ "crates/router/src/core/payments/operations/payment_confirm.rs", "crates/router/src/core/payments/operations/payment_create.rs", "crates/router/src/core/payments/operations/payment_update.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4703
Bug: [FEATURE] [AUTHORIZEDOTNET] Implement non-zero mandates ### Feature Description Non-zero dollar mandates need to be implemented for connector Authorizedotnet. ### Possible Implementation Non-zero dollar mandates need to be implemented for connector Authorizedotnet. ### 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/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index a9e000b82b9..8d0c1db37a2 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -79,6 +79,16 @@ impl ConnectorValidation for Authorizedotnet { ), } } + + fn validate_mandate_payment( + &self, + pm_type: Option<types::storage::enums::PaymentMethodType>, + pm_data: types::domain::payments::PaymentMethodData, + ) -> CustomResult<(), errors::ConnectorError> { + let mandate_supported_pmd = + std::collections::HashSet::from([crate::connector::utils::PaymentMethodDataType::Card]); + connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) + } } impl api::Payment for Authorizedotnet {} diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 3e4d0a382e6..de68438edc4 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -133,20 +133,36 @@ pub enum WalletMethod { struct TransactionRequest { transaction_type: TransactionType, amount: f64, - currency_code: String, - #[serde(skip_serializing_if = "Option::is_none")] - profile: Option<CustomerProfileDetails>, + currency_code: common_enums::Currency, #[serde(skip_serializing_if = "Option::is_none")] payment: Option<PaymentDetails>, + #[serde(skip_serializing_if = "Option::is_none")] + profile: Option<ProfileDetails>, order: Order, #[serde(skip_serializing_if = "Option::is_none")] + customer: Option<CustomerDetails>, + #[serde(skip_serializing_if = "Option::is_none")] bill_to: Option<BillTo>, + #[serde(skip_serializing_if = "Option::is_none")] processing_options: Option<ProcessingOptions>, #[serde(skip_serializing_if = "Option::is_none")] subsequent_auth_information: Option<SubsequentAuthInformation>, authorization_indicator_type: Option<AuthorizationIndicator>, } +#[derive(Serialize, Deserialize, Debug)] +#[serde(untagged)] +enum ProfileDetails { + CreateProfileDetails(CreateProfileDetails), + CustomerProfileDetails(CustomerProfileDetails), +} + +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct CreateProfileDetails { + create_profile: bool, +} + #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct CustomerProfileDetails { @@ -160,6 +176,12 @@ struct PaymentProfileDetails { payment_profile_id: Secret<String>, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CustomerDetails { + id: String, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProcessingOptions { @@ -461,37 +483,37 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>> fn try_from( item: &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { - let (payment_details, processing_options, subsequent_auth_information, profile) = match item + let merchant_authentication = + AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?; + + let ref_id = if item.router_data.connector_request_reference_id.len() <= 20 { + Some(item.router_data.connector_request_reference_id.clone()) + } else { + None + }; + + let transaction_request = match item .router_data .request .mandate_id - .to_owned() + .clone() .and_then(|mandate_ids| mandate_ids.mandate_reference_id) { Some(api_models::payments::MandateReferenceId::NetworkMandateId(network_trans_id)) => { - let processing_options = Some(ProcessingOptions { - is_subsequent_auth: true, - }); - let subsequent_auth_info = Some(SubsequentAuthInformation { - original_network_trans_id: Secret::new(network_trans_id), - reason: Reason::Resubmission, - }); - match item.router_data.request.payment_method_data { - domain::PaymentMethodData::Card(ref ccard) => { - let payment_details = PaymentDetails::CreditCard(CreditCardDetails { - card_number: (*ccard.card_number).clone(), - expiration_date: ccard.get_expiry_date_as_yyyymm("-"), - card_code: None, - }); - ( - Some(payment_details), - processing_options, - subsequent_auth_info, - None, - ) + TransactionRequest::try_from((item, network_trans_id))? + } + Some(api_models::payments::MandateReferenceId::ConnectorMandateId( + connector_mandate_id, + )) => TransactionRequest::try_from((item, connector_mandate_id))?, + None => { + match &item.router_data.request.payment_method_data { + domain::PaymentMethodData::Card(ccard) => { + TransactionRequest::try_from((item, ccard)) + } + domain::PaymentMethodData::Wallet(wallet_data) => { + TransactionRequest::try_from((item, wallet_data)) } domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Wallet(_) | domain::PaymentMethodData::PayLater(_) | domain::PaymentMethodData::BankRedirect(_) | domain::PaymentMethodData::BankDebit(_) @@ -510,16 +532,116 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>> ))? } } - } - Some(api_models::payments::MandateReferenceId::ConnectorMandateId( - connector_mandate_id, - )) => ( - None, - Some(ProcessingOptions { - is_subsequent_auth: true, + }?, + }; + Ok(Self { + create_transaction_request: AuthorizedotnetPaymentsRequest { + merchant_authentication, + ref_id, + transaction_request, + }, + }) + } +} + +impl + TryFrom<( + &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>, + String, + )> for TransactionRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, network_trans_id): ( + &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>, + String, + ), + ) -> Result<Self, Self::Error> { + Ok(Self { + transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, + amount: item.amount, + currency_code: item.router_data.request.currency, + payment: Some(match item.router_data.request.payment_method_data { + domain::PaymentMethodData::Card(ref ccard) => { + PaymentDetails::CreditCard(CreditCardDetails { + card_number: (*ccard.card_number).clone(), + expiration_date: ccard.get_expiry_date_as_yyyymm("-"), + card_code: None, + }) + } + domain::PaymentMethodData::CardRedirect(_) + | domain::PaymentMethodData::Wallet(_) + | domain::PaymentMethodData::PayLater(_) + | domain::PaymentMethodData::BankRedirect(_) + | domain::PaymentMethodData::BankDebit(_) + | domain::PaymentMethodData::BankTransfer(_) + | domain::PaymentMethodData::Crypto(_) + | domain::PaymentMethodData::MandatePayment + | domain::PaymentMethodData::Reward + | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("authorizedotnet"), + ))? + } + }), + profile: None, + order: Order { + description: item.router_data.connector_request_reference_id.clone(), + }, + customer: None, + bill_to: item + .router_data + .get_optional_billing() + .and_then(|billing_address| billing_address.address.as_ref()) + .map(|address| BillTo { + first_name: address.first_name.clone(), + last_name: address.last_name.clone(), + address: address.line1.clone(), + city: address.city.clone(), + state: address.state.clone(), + zip: address.zip.clone(), + country: address.country, + }), + processing_options: Some(ProcessingOptions { + is_subsequent_auth: true, + }), + subsequent_auth_information: Some(SubsequentAuthInformation { + original_network_trans_id: Secret::new(network_trans_id), + reason: Reason::Resubmission, + }), + authorization_indicator_type: match item.router_data.request.capture_method { + Some(capture_method) => Some(AuthorizationIndicator { + authorization_indicator: capture_method.try_into()?, }), - None, - Some(CustomerProfileDetails { + None => None, + }, + }) + } +} + +impl + TryFrom<( + &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>, + api_models::payments::ConnectorMandateReferenceId, + )> for TransactionRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, connector_mandate_id): ( + &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>, + api_models::payments::ConnectorMandateReferenceId, + ), + ) -> Result<Self, Self::Error> { + Ok(Self { + transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, + amount: item.amount, + currency_code: item.router_data.request.currency, + payment: None, + profile: Some(ProfileDetails::CustomerProfileDetails( + CustomerProfileDetails { customer_profile_id: Secret::from( connector_mandate_id .connector_mandate_id @@ -532,64 +654,86 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>> .ok_or(errors::ConnectorError::MissingConnectorMandateID)?, ), }, - }), - ), - None => { - match item.router_data.request.payment_method_data { - domain::PaymentMethodData::Card(ref ccard) => { - ( - Some(PaymentDetails::CreditCard(CreditCardDetails { - card_number: (*ccard.card_number).clone(), - // expiration_date: format!("{expiry_year}-{expiry_month}").into(), - expiration_date: ccard.get_expiry_date_as_yyyymm("-"), - card_code: Some(ccard.card_cvc.clone()), - })), - Some(ProcessingOptions { - is_subsequent_auth: true, - }), - None, - None, - ) - } - domain::PaymentMethodData::Wallet(ref wallet_data) => ( - Some(get_wallet_data( - wallet_data, - &item.router_data.request.complete_authorize_url, - )?), - None, - None, - None, - ), - domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message( - "authorizedotnet", - ), - ))? - } - } - } - }; - let authorization_indicator_type = match item.router_data.request.capture_method { - Some(capture_method) => Some(AuthorizationIndicator { - authorization_indicator: capture_method.try_into()?, + }, + )), + order: Order { + description: item.router_data.connector_request_reference_id.clone(), + }, + customer: None, + bill_to: None, + processing_options: Some(ProcessingOptions { + is_subsequent_auth: true, }), - None => None, + subsequent_auth_information: None, + authorization_indicator_type: match item.router_data.request.capture_method { + Some(capture_method) => Some(AuthorizationIndicator { + authorization_indicator: capture_method.try_into()?, + }), + None => None, + }, + }) + } +} + +impl + TryFrom<( + &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>, + &domain::Card, + )> for TransactionRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, ccard): ( + &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>, + &domain::Card, + ), + ) -> Result<Self, Self::Error> { + let (profile, customer) = if item + .router_data + .request + .setup_future_usage + .map_or(false, |future_usage| { + matches!(future_usage, common_enums::FutureUsage::OffSession) + }) + && (item.router_data.request.customer_acceptance.is_some() + || item + .router_data + .request + .setup_mandate_details + .clone() + .map_or(false, |mandate_details| { + mandate_details.customer_acceptance.is_some() + })) { + ( + Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails { + create_profile: true, + })), + Some(CustomerDetails { + id: item + .router_data + .customer_id + .clone() + .ok_or_else(missing_field_err("customer_id"))?, + }), + ) + } else { + (None, None) }; - let bill_to = match profile { - Some(_) => None, - None => item + Ok(Self { + transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, + amount: item.amount, + currency_code: item.router_data.request.currency, + payment: Some(PaymentDetails::CreditCard(CreditCardDetails { + card_number: (*ccard.card_number).clone(), + expiration_date: ccard.get_expiry_date_as_yyyymm("-"), + card_code: Some(ccard.card_cvc.clone()), + })), + profile, + order: Order { + description: item.router_data.connector_request_reference_id.clone(), + }, + customer, + bill_to: item .router_data .get_optional_billing() .and_then(|billing_address| billing_address.address.as_ref()) @@ -602,34 +746,64 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>> zip: address.zip.clone(), country: address.country, }), - }; - let transaction_request = TransactionRequest { + processing_options: None, + subsequent_auth_information: None, + authorization_indicator_type: match item.router_data.request.capture_method { + Some(capture_method) => Some(AuthorizationIndicator { + authorization_indicator: capture_method.try_into()?, + }), + None => None, + }, + }) + } +} + +impl + TryFrom<( + &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>, + &domain::WalletData, + )> for TransactionRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, wallet_data): ( + &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>, + &domain::WalletData, + ), + ) -> Result<Self, Self::Error> { + Ok(Self { transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, amount: item.amount, - currency_code: item.router_data.request.currency.to_string(), - profile, - payment: payment_details, + currency_code: item.router_data.request.currency, + payment: Some(get_wallet_data( + wallet_data, + &item.router_data.request.complete_authorize_url, + )?), + profile: None, order: Order { description: item.router_data.connector_request_reference_id.clone(), }, - bill_to, - processing_options, - subsequent_auth_information, - authorization_indicator_type, - }; - - let merchant_authentication = - AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?; - let ref_id = if item.router_data.connector_request_reference_id.len() <= 20 { - Some(item.router_data.connector_request_reference_id.clone()) - } else { - None - }; - Ok(Self { - create_transaction_request: AuthorizedotnetPaymentsRequest { - merchant_authentication, - ref_id, - transaction_request, + customer: None, + bill_to: item + .router_data + .get_optional_billing() + .and_then(|billing_address| billing_address.address.as_ref()) + .map(|address| BillTo { + first_name: address.first_name.clone(), + last_name: address.last_name.clone(), + address: address.line1.clone(), + city: address.city.clone(), + state: address.state.clone(), + zip: address.zip.clone(), + country: address.country, + }), + processing_options: None, + subsequent_auth_information: None, + authorization_indicator_type: match item.router_data.request.capture_method { + Some(capture_method) => Some(AuthorizationIndicator { + authorization_indicator: capture_method.try_into()?, + }), + None => None, }, }) } @@ -804,6 +978,15 @@ pub struct SecureAcceptance { #[serde(rename_all = "camelCase")] pub struct AuthorizedotnetPaymentsResponse { pub transaction_response: Option<TransactionResponse>, + pub profile_response: Option<AuthorizedotnetNonZeroMandateResponse>, + pub messages: ResponseMessages, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthorizedotnetNonZeroMandateResponse { + customer_profile_id: Option<String>, + customer_payment_profile_id_list: Option<Vec<String>>, pub messages: ResponseMessages, } @@ -913,7 +1096,16 @@ impl<F, T> transaction_response.transaction_id.clone(), ), redirection_data, - mandate_reference: None, + mandate_reference: item.response.profile_response.map( + |profile_response| types::MandateReference { + connector_mandate_id: profile_response.customer_profile_id, + payment_method_id: profile_response + .customer_payment_profile_id_list + .and_then(|customer_payment_profile_id_list| { + customer_payment_profile_id_list.first().cloned() + }), + }, + ), connector_metadata: metadata, network_txn_id: transaction_response .network_trans_id
2024-05-24T09:28:49Z
## Description <!-- Describe your changes in detail --> Non-zero dollar mandates are implemented for connector Authorizedotnet. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/4703 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Payment Intent Create (Non-Zero Mandate): Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 370, "currency": "USD", "confirm": false, "customer_id": "cust6", "email": "something2@gmail.com", "name": "Joseph Doe", "description": "Its my first payment request", "setup_future_usage":"off_session" }' ``` Response: ``` { "payment_id": "pay_lx2DcRsYllb2QenBQfze", "merchant_id": "merchant_1716370796", "status": "requires_payment_method", "amount": 370, "net_amount": 370, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_lx2DcRsYllb2QenBQfze_secret_X1riA15AgjzqEahbR8mv", "created": "2024-05-27T11:07:15.600Z", "currency": "USD", "customer_id": "cust6", "customer": { "id": "cust6", "name": "Joseph Doe", "email": "something2@gmail.com", "phone": null, "phone_country_code": null }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "something2@gmail.com", "name": "Joseph Doe", "phone": null, "return_url": null, "authentication_type": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cust6", "created_at": 1716808035, "expires": 1716811635, "secret": "epk_339c8ebb1d9f430796cf8273ef72f78f" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_ZjmEyV32O7pOQkBlB510", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-27T11:22:15.600Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-27T11:07:15.690Z", "charges": null, "frm_metadata": null } ``` - Payment Confirm: Request: ``` curl --location 'http://localhost:8080/payments/pay_lx2DcRsYllb2QenBQfze/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "card_cvc": "123" } }, "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 68607706, "currency": "USD", "start_date": "2023-04-21T00:00:00Z", "end_date": "2023-05-21T00:00:00Z", "metadata": { "frequency": "13" } } } } }' ``` Response: ``` { "payment_id": "pay_lx2DcRsYllb2QenBQfze", "merchant_id": "merchant_1716370796", "status": "succeeded", "amount": 370, "net_amount": 370, "amount_capturable": 0, "amount_received": 370, "connector": "authorizedotnet", "client_secret": "pay_lx2DcRsYllb2QenBQfze_secret_X1riA15AgjzqEahbR8mv", "created": "2024-05-27T11:07:15.600Z", "currency": "USD", "customer_id": "cust6", "customer": { "id": "cust6", "name": "Joseph Doe", "email": "something2@gmail.com", "phone": null, "phone_country_code": null }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": "man_wxTMvSxaQPFC5uvg7Qmm", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 68607706, "currency": "USD", "start_date": "2023-04-21T00:00:00.000Z", "end_date": "2023-05-21T00:00:00.000Z", "metadata": { "frequency": "13" } } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "something2@gmail.com", "name": "Joseph Doe", "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "80019080368", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80019080368", "payment_link": null, "profile_id": "pro_ZjmEyV32O7pOQkBlB510", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_6wtrG4tIah8tNezhNkT9", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-27T11:22:15.600Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_ZN7bB0d33KWNWIUgVWod", "payment_method_status": null, "updated": "2024-05-27T11:07:32.165Z", "charges": null, "frm_metadata": null } ``` - Payment Create (Using Mandate ID): Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 141, "currency": "USD", "confirm": true, "customer_id": "cust6", "capture_method": "automatic", "mandate_id": "man_wxTMvSxaQPFC5uvg7Qmm", "off_session": true }' ``` Response: ``` { "payment_id": "pay_8aI2C6oCZosMy1CQf2X9", "merchant_id": "merchant_1716370796", "status": "succeeded", "amount": 141, "net_amount": 141, "amount_capturable": 0, "amount_received": 141, "connector": "authorizedotnet", "client_secret": "pay_8aI2C6oCZosMy1CQf2X9_secret_gnro3S1Hlru3sUsAcdik", "created": "2024-05-27T11:07:53.638Z", "currency": "USD", "customer_id": "cust6", "customer": { "id": "cust6", "name": "Joseph Doe", "email": "something2@gmail.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": "man_wxTMvSxaQPFC5uvg7Qmm", "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "fa0a6a44-2e80-4953-971d-c70702e889d7", "shipping": null, "billing": null, "order_details": null, "email": "something2@gmail.com", "name": "Joseph Doe", "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cust6", "created_at": 1716808073, "expires": 1716811673, "secret": "epk_95141b60e629482ea657f64053afa3d2" }, "manual_retry_allowed": false, "connector_transaction_id": "80019080384", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80019080384", "payment_link": null, "profile_id": "pro_ZjmEyV32O7pOQkBlB510", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_6wtrG4tIah8tNezhNkT9", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-27T11:22:53.638Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_ZN7bB0d33KWNWIUgVWod", "payment_method_status": "active", "updated": "2024-05-27T11:07:54.663Z", "charges": null, "frm_metadata": null } ```
8d9c7bc45ce2515759b9e2a36eb2d8a8a2c813ad
- Payment Intent Create (Non-Zero Mandate): Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 370, "currency": "USD", "confirm": false, "customer_id": "cust6", "email": "something2@gmail.com", "name": "Joseph Doe", "description": "Its my first payment request", "setup_future_usage":"off_session" }' ``` Response: ``` { "payment_id": "pay_lx2DcRsYllb2QenBQfze", "merchant_id": "merchant_1716370796", "status": "requires_payment_method", "amount": 370, "net_amount": 370, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_lx2DcRsYllb2QenBQfze_secret_X1riA15AgjzqEahbR8mv", "created": "2024-05-27T11:07:15.600Z", "currency": "USD", "customer_id": "cust6", "customer": { "id": "cust6", "name": "Joseph Doe", "email": "something2@gmail.com", "phone": null, "phone_country_code": null }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "something2@gmail.com", "name": "Joseph Doe", "phone": null, "return_url": null, "authentication_type": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cust6", "created_at": 1716808035, "expires": 1716811635, "secret": "epk_339c8ebb1d9f430796cf8273ef72f78f" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_ZjmEyV32O7pOQkBlB510", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-27T11:22:15.600Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-27T11:07:15.690Z", "charges": null, "frm_metadata": null } ``` - Payment Confirm: Request: ``` curl --location 'http://localhost:8080/payments/pay_lx2DcRsYllb2QenBQfze/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "card_cvc": "123" } }, "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 68607706, "currency": "USD", "start_date": "2023-04-21T00:00:00Z", "end_date": "2023-05-21T00:00:00Z", "metadata": { "frequency": "13" } } } } }' ``` Response: ``` { "payment_id": "pay_lx2DcRsYllb2QenBQfze", "merchant_id": "merchant_1716370796", "status": "succeeded", "amount": 370, "net_amount": 370, "amount_capturable": 0, "amount_received": 370, "connector": "authorizedotnet", "client_secret": "pay_lx2DcRsYllb2QenBQfze_secret_X1riA15AgjzqEahbR8mv", "created": "2024-05-27T11:07:15.600Z", "currency": "USD", "customer_id": "cust6", "customer": { "id": "cust6", "name": "Joseph Doe", "email": "something2@gmail.com", "phone": null, "phone_country_code": null }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": "man_wxTMvSxaQPFC5uvg7Qmm", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 68607706, "currency": "USD", "start_date": "2023-04-21T00:00:00.000Z", "end_date": "2023-05-21T00:00:00.000Z", "metadata": { "frequency": "13" } } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "something2@gmail.com", "name": "Joseph Doe", "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "80019080368", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80019080368", "payment_link": null, "profile_id": "pro_ZjmEyV32O7pOQkBlB510", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_6wtrG4tIah8tNezhNkT9", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-27T11:22:15.600Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_ZN7bB0d33KWNWIUgVWod", "payment_method_status": null, "updated": "2024-05-27T11:07:32.165Z", "charges": null, "frm_metadata": null } ``` - Payment Create (Using Mandate ID): Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 141, "currency": "USD", "confirm": true, "customer_id": "cust6", "capture_method": "automatic", "mandate_id": "man_wxTMvSxaQPFC5uvg7Qmm", "off_session": true }' ``` Response: ``` { "payment_id": "pay_8aI2C6oCZosMy1CQf2X9", "merchant_id": "merchant_1716370796", "status": "succeeded", "amount": 141, "net_amount": 141, "amount_capturable": 0, "amount_received": 141, "connector": "authorizedotnet", "client_secret": "pay_8aI2C6oCZosMy1CQf2X9_secret_gnro3S1Hlru3sUsAcdik", "created": "2024-05-27T11:07:53.638Z", "currency": "USD", "customer_id": "cust6", "customer": { "id": "cust6", "name": "Joseph Doe", "email": "something2@gmail.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": "man_wxTMvSxaQPFC5uvg7Qmm", "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "fa0a6a44-2e80-4953-971d-c70702e889d7", "shipping": null, "billing": null, "order_details": null, "email": "something2@gmail.com", "name": "Joseph Doe", "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cust6", "created_at": 1716808073, "expires": 1716811673, "secret": "epk_95141b60e629482ea657f64053afa3d2" }, "manual_retry_allowed": false, "connector_transaction_id": "80019080384", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80019080384", "payment_link": null, "profile_id": "pro_ZjmEyV32O7pOQkBlB510", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_6wtrG4tIah8tNezhNkT9", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-27T11:22:53.638Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_ZN7bB0d33KWNWIUgVWod", "payment_method_status": "active", "updated": "2024-05-27T11:07:54.663Z", "charges": null, "frm_metadata": null } ```
[ "crates/router/src/connector/authorizedotnet.rs", "crates/router/src/connector/authorizedotnet/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4757
Bug: [FIX] Fix the functionality to show both the disabled and enabled connectors while List Merchant Connector Account ### Feature Description Fix the functionality to show both the disabled and enabled connectors while List Merchant Connector Account ### Possible Implementation Fix the functionality to show both the disabled and enabled connectors while List Merchant Connector Account ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/diesel_models/src/query/merchant_connector_account.rs b/crates/diesel_models/src/query/merchant_connector_account.rs index cc73bd7a532..bd24d12ec22 100644 --- a/crates/diesel_models/src/query/merchant_connector_account.rs +++ b/crates/diesel_models/src/query/merchant_connector_account.rs @@ -124,9 +124,7 @@ impl MerchantConnectorAccount { if get_disabled { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, - dsl::merchant_id - .eq(merchant_id.to_owned()) - .and(dsl::disabled.eq(true)), + dsl::merchant_id.eq(merchant_id.to_owned()), None, None, Some(dsl::created_at.asc()), diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 5a12334c385..9fe8d899ea3 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3700,7 +3700,12 @@ pub async fn get_mca_status( .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_id.to_string(), })?; + let mut mca_ids = HashSet::new(); + let mcas = mcas + .into_iter() + .filter(|mca| mca.disabled == Some(true)) + .collect::<Vec<_>>(); for mca in mcas { mca_ids.insert(mca.merchant_connector_id);
2024-05-24T08:36:45Z
## Description revert the filter for getting the mcas which are disabled, and explicitly get the Mca that are disabled ### 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? - All the MCA's either disabled/enabled will show in the LIST MCAs ``` Response [ { "connector_type": "fiz_operations", "connector_name": "cybersource", "connector_label": "cybersource_US_default_2", "merchant_connector_id": "mca_JfI8xFhxTnL5q2bFhpUW", "profile_id": "pro_NMDohQHyrqzAkUjBjDmB", "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "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": "google_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": { "merchant_secret": "samraat", "additional_secret": null }, "metadata": { "google_pay": { "merchant_info": { "merchant_id": "vbewlji", "merchant_name": "bluesnap" }, "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": "bluesnap", "gateway_merchant_id": "1087905" } } } ] }, "terminal_id": "10000001", "account_name": "transaction_processing" }, "test_mode": true, "disabled": true, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active" }, { "connector_type": "fiz_operations", "connector_name": "stripe", "connector_label": "stripe_US_default7", "merchant_connector_id": "mca_mETGK4Fi1JQG7ggXzUnd", "profile_id": "pro_NMDohQHyrqzAkUjBjDmB", "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 200000, "recurring_enabled": false, "installment_payment_enabled": false }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "JCB" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 200000, "recurring_enabled": false, "installment_payment_enabled": false } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 50000, "recurring_enabled": false, "installment_payment_enabled": false }, { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 600, "maximum_amount": 800, "recurring_enabled": false, "installment_payment_enabled": false } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 50000, "recurring_enabled": false, "installment_payment_enabled": false } ] } ], "connector_webhook_details": null, "metadata": { "city": "NY", "unit": "245" }, "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" }, { "connector_type": "fiz_operations", "connector_name": "cybersource", "connector_label": "cybersource_US_default_default", "merchant_connector_id": "mca_Ec6WKYkD3tP5m4HwSmxd", "profile_id": "pro_NMDohQHyrqzAkUjBjDmB", ment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard", "DinersClub", "Discover" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard", "DinersClub", "Discover" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": { "merchant_secret": "MyWebhookSecret", "additional_secret": null }, }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active" } ] ```
55ccce61898083992afeab03ba1690954b1b45ef
- All the MCA's either disabled/enabled will show in the LIST MCAs ``` Response [ { "connector_type": "fiz_operations", "connector_name": "cybersource", "connector_label": "cybersource_US_default_2", "merchant_connector_id": "mca_JfI8xFhxTnL5q2bFhpUW", "profile_id": "pro_NMDohQHyrqzAkUjBjDmB", "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "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": "google_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": { "merchant_secret": "samraat", "additional_secret": null }, "metadata": { "google_pay": { "merchant_info": { "merchant_id": "vbewlji", "merchant_name": "bluesnap" }, "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": "bluesnap", "gateway_merchant_id": "1087905" } } } ] }, "terminal_id": "10000001", "account_name": "transaction_processing" }, "test_mode": true, "disabled": true, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active" }, { "connector_type": "fiz_operations", "connector_name": "stripe", "connector_label": "stripe_US_default7", "merchant_connector_id": "mca_mETGK4Fi1JQG7ggXzUnd", "profile_id": "pro_NMDohQHyrqzAkUjBjDmB", "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 200000, "recurring_enabled": false, "installment_payment_enabled": false }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "JCB" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 200000, "recurring_enabled": false, "installment_payment_enabled": false } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 50000, "recurring_enabled": false, "installment_payment_enabled": false }, { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 600, "maximum_amount": 800, "recurring_enabled": false, "installment_payment_enabled": false } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 50000, "recurring_enabled": false, "installment_payment_enabled": false } ] } ], "connector_webhook_details": null, "metadata": { "city": "NY", "unit": "245" }, "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" }, { "connector_type": "fiz_operations", "connector_name": "cybersource", "connector_label": "cybersource_US_default_default", "merchant_connector_id": "mca_Ec6WKYkD3tP5m4HwSmxd", "profile_id": "pro_NMDohQHyrqzAkUjBjDmB", ment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard", "DinersClub", "Discover" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard", "DinersClub", "Discover" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": { "merchant_secret": "MyWebhookSecret", "additional_secret": null }, }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active" } ] ```
[ "crates/diesel_models/src/query/merchant_connector_account.rs", "crates/router/src/core/payment_methods/cards.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4752
Bug: mask the email address being logged in the payment_method_list response logs As of now the payment method list response logs contains the email address, this needs to be mased <img width="1448" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4c219a49-13d3-4fa1-804a-21c215aa5675">
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index dd7791ee2d2..5a19a225dee 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -531,7 +531,8 @@ pub struct RequiredFieldInfo { #[schema(value_type = FieldType)] pub field_type: api_enums::FieldType, - pub value: Option<String>, + #[schema(value_type = Option<String>)] + pub value: Option<masking::Secret<String>>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index d3870a9e598..741a0e246b6 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2267,7 +2267,7 @@ pub async fn list_payment_methods( .as_ref() .and_then(|r| get_val(key.to_owned(), r)); if let Some(s) = temp { - val.value = Some(s) + val.value = Some(s.into()) }; } }
2024-05-23T14:07:07Z
## Description <!-- Describe your changes in detail --> https://github.com/juspay/hyperswitch/pull/4749 This pr is to mask the email address being logged in the payment method list response. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a merchant account and mca -> Create a payment with confirm false ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_jviyQiUsX9uHI99VXUlF_secret_lHrA6q5GKvNvd5a0blUQ' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_df002da8beb74682ac3e8677a4b82217' ``` in the below log we can see the email address being logged (this is without the changes in this pr) <img width="1448" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0900eba7-09e0-4db7-95aa-bcd102cb49d6"> after the changes the email is being masked <img width="1466" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67164e06-9953-4b17-83e1-3ccdad17d129">
f79c12d4f78ac622300e56f7159ca72d65a4ac0d
-> Create a merchant account and mca -> Create a payment with confirm false ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_jviyQiUsX9uHI99VXUlF_secret_lHrA6q5GKvNvd5a0blUQ' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_df002da8beb74682ac3e8677a4b82217' ``` in the below log we can see the email address being logged (this is without the changes in this pr) <img width="1448" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0900eba7-09e0-4db7-95aa-bcd102cb49d6"> after the changes the email is being masked <img width="1466" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67164e06-9953-4b17-83e1-3ccdad17d129">
[ "crates/api_models/src/payment_methods.rs", "crates/router/src/core/payment_methods/cards.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4751
Bug: mask the email address being logged in the payment_method_list response logs As of now the payment method list response logs contains the email address, this needs to be mased <img width="1448" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4c219a49-13d3-4fa1-804a-21c215aa5675">
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index d26a2deac18..d63d2b085b6 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -531,7 +531,8 @@ pub struct RequiredFieldInfo { #[schema(value_type = FieldType)] pub field_type: api_enums::FieldType, - pub value: Option<String>, + #[schema(value_type = Option<String>)] + pub value: Option<masking::Secret<String>>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 28121ecc801..5a12334c385 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2268,7 +2268,7 @@ pub async fn list_payment_methods( .as_ref() .and_then(|r| get_val(key.to_owned(), r)); if let Some(s) = temp { - val.value = Some(s) + val.value = Some(s.into()) }; } }
2024-05-23T13:36:58Z
## Description <!-- Describe your changes in detail --> This pr is to mask the email address being logged in the payment method list response. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a merchant account and mca -> Create a payment with confirm false ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_jviyQiUsX9uHI99VXUlF_secret_lHrA6q5GKvNvd5a0blUQ' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_df002da8beb74682ac3e8677a4b82217' ``` in the below log we can see the email address being logged (this is without the changes in this pr) <img width="1448" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0900eba7-09e0-4db7-95aa-bcd102cb49d6"> after the changes the email is being masked <img width="1466" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67164e06-9953-4b17-83e1-3ccdad17d129">
42e5ef155128f4df717e8fb101da6e6929659a0a
-> Create a merchant account and mca -> Create a payment with confirm false ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_jviyQiUsX9uHI99VXUlF_secret_lHrA6q5GKvNvd5a0blUQ' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_df002da8beb74682ac3e8677a4b82217' ``` in the below log we can see the email address being logged (this is without the changes in this pr) <img width="1448" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0900eba7-09e0-4db7-95aa-bcd102cb49d6"> after the changes the email is being masked <img width="1466" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67164e06-9953-4b17-83e1-3ccdad17d129">
[ "crates/api_models/src/payment_methods.rs", "crates/router/src/core/payment_methods/cards.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4748
Bug: log and ignore the apple pay metadata parsing error while fetching apple pay retry connectors For a merchant account there are be n number of connectors and its not mandatory that apple pay needs to be enabled for all of them. So while fetching apple pay retry connectors log the error if the apple pay metadata parsing fails. This is required as this will create unnecessary errors for the connectors that does not have the apple pay metadata enabled as for them apple pay metadata will be not there.
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index a6befa5269e..f760e907288 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3163,8 +3163,14 @@ where routing_data.business_sub_label = choice.sub_label.clone(); } + #[cfg(feature = "retry")] + let should_do_retry = + retry::config_should_call_gsm(&*state.store, &merchant_account.merchant_id).await; + + #[cfg(feature = "retry")] if payment_data.payment_attempt.payment_method_type == Some(storage_enums::PaymentMethodType::ApplePay) + && should_do_retry { let retryable_connector_data = helpers::get_apple_pay_retryable_connectors( state, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 06c8c7f2c94..5611e536871 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3890,18 +3890,27 @@ pub fn validate_customer_access( pub fn is_apple_pay_simplified_flow( connector_metadata: Option<pii::SecretSerdeValue>, + connector_name: Option<&String>, ) -> CustomResult<bool, errors::ApiErrorResponse> { - let apple_pay_metadata = get_applepay_metadata(connector_metadata)?; - - Ok(match apple_pay_metadata { - api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( - apple_pay_combined_metadata, - ) => match apple_pay_combined_metadata { - api_models::payments::ApplePayCombinedMetadata::Simplified { .. } => true, - api_models::payments::ApplePayCombinedMetadata::Manual { .. } => false, - }, - api_models::payments::ApplepaySessionTokenMetadata::ApplePay(_) => false, - }) + let option_apple_pay_metadata = get_applepay_metadata(connector_metadata) + .map_err(|error| { + logger::info!( + "Apple pay metadata parsing for {:?} in is_apple_pay_simplified_flow {:?}", + connector_name, + error + ) + }) + .ok(); + + // return true only if the apple flow type is simplified + Ok(matches!( + option_apple_pay_metadata, + Some( + api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( + api_models::payments::ApplePayCombinedMetadata::Simplified { .. } + ) + ) + )) } pub fn get_applepay_metadata( @@ -3954,7 +3963,7 @@ where field_name: "profile_id", })?; - let merchant_connector_account = get_merchant_connector_account( + let merchant_connector_account_type = get_merchant_connector_account( &state, merchant_account.merchant_id.as_str(), payment_data.creds_identifier.to_owned(), @@ -3963,15 +3972,19 @@ where &decided_connector_data.connector_name.to_string(), merchant_connector_id, ) - .await? - .get_metadata(); + .await?; - let connector_data_list = if is_apple_pay_simplified_flow(merchant_connector_account)? { + let connector_data_list = if is_apple_pay_simplified_flow( + merchant_connector_account_type.get_metadata(), + merchant_connector_account_type + .get_connector_name() + .as_ref(), + )? { let merchant_connector_account_list = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( merchant_account.merchant_id.as_str(), - true, + false, key_store, ) .await @@ -3980,7 +3993,10 @@ where let mut connector_data_list = vec![decided_connector_data.clone()]; for merchant_connector_account in merchant_connector_account_list { - if is_apple_pay_simplified_flow(merchant_connector_account.metadata)? { + if is_apple_pay_simplified_flow( + merchant_connector_account.metadata, + Some(&merchant_connector_account.connector_name), + )? { let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &merchant_connector_account.connector_name.to_string(),
2024-05-23T11:15:20Z
## Description <!-- Describe your changes in detail --> For a merchant account there are be n number of connectors and its not mandatory that apple pay needs to be enabled for all of them. So while fetching apple pay retry connectors log the error if the apple pay metadata parsing fails. This is required as this will create unnecessary errors for the connectors that does not have the apple pay metadata enabled as for them apple pay metadata will be not there. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a merchant account -> Enable gcm for the `merchant_id` ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "should_call_gsm_{merchant_id}", "value": "true" }' ``` -> Set the maximum retries count ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "max_auto_retries_enabled_{merchant_id}", "value": "1" }' ``` -> Create MCA for stripe and cybersource with apple pay simplified flow metadata for simplified flow ``` "metadata": { "apple_pay_combined": { "simplified": { "session_token_data": { "initiative_context": "sdk-test-app.netlify.app", "merchant_business_country": "US" }, "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": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ] } } } ``` -> Do a apple pay payment create with confirm false ``` { "amount": 650, "currency": "USD", "confirm": false, "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", "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" } } } ``` <img width="1007" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67deb74e-e0dd-4af3-b5d9-7298d65c3e01"> -> Do payment method list for merchant ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_V1VBfr3VW6MVXaFw01sT_secret_6bByPi9DrnPk0uv6vYJj' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_cc7a8a8132a840338323ac8f7f6860d0' ``` <img width="1059" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/38f97f9d-ff51-41dc-9a06-20137f2ead1a"> -> Confirm the above create payment with `payment_id` and payment_data ``` curl --location 'http://localhost:8080/payments/pay_V1VBfr3VW6MVXaFw01sT/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api_key' \ --data '{ "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSTBNRFV5TVRBM016TXlORm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlEa29VdTlwZ01JUHR2R0VEZi9tSXk3LzNjSTg2b3U5eTJaZkV6RkhuRFN0TUFvR0NDcUdTTTQ5QkFNQ0JFWXdSQUlnTWdkSG9rZHNWQndya3RYRzd1VmowMm9QVVNsQllaWGVPeXJyd3RsQk5MUUNJRDdzZnZPaThZcjVWNkVyNjFqU05sKzR3ZDhpR050YUxEdFRMZjNBQ0VhNkFBQUFBQUFBIiwiaGVhZGVyIjp7InB1YmxpY0tleUhhc2giOiJ4MnFmMTFaemRXbnFCZnc0U0NyOWxIYzZRc1JQOEp6Z2xrZnU5RTVkWUpnPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } }' ``` <img width="1045" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/1b5c8cb4-43bf-42ea-a82f-9c6db940950b"> -> Apple pay retry connectors. In here I had configured apple pay simplified flow for stripe and rapyd. And apple pay manual flow for cybersource and adyen mca without apple pay enabled <img width="1158" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/59e3a5ba-31f6-42f9-bb81-d388ced47e0e">
ae77373b4cac63979673fdac37c55986d954358e
-> Create a merchant account -> Enable gcm for the `merchant_id` ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "should_call_gsm_{merchant_id}", "value": "true" }' ``` -> Set the maximum retries count ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "max_auto_retries_enabled_{merchant_id}", "value": "1" }' ``` -> Create MCA for stripe and cybersource with apple pay simplified flow metadata for simplified flow ``` "metadata": { "apple_pay_combined": { "simplified": { "session_token_data": { "initiative_context": "sdk-test-app.netlify.app", "merchant_business_country": "US" }, "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": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ] } } } ``` -> Do a apple pay payment create with confirm false ``` { "amount": 650, "currency": "USD", "confirm": false, "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", "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" } } } ``` <img width="1007" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67deb74e-e0dd-4af3-b5d9-7298d65c3e01"> -> Do payment method list for merchant ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_V1VBfr3VW6MVXaFw01sT_secret_6bByPi9DrnPk0uv6vYJj' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_cc7a8a8132a840338323ac8f7f6860d0' ``` <img width="1059" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/38f97f9d-ff51-41dc-9a06-20137f2ead1a"> -> Confirm the above create payment with `payment_id` and payment_data ``` curl --location 'http://localhost:8080/payments/pay_V1VBfr3VW6MVXaFw01sT/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api_key' \ --data '{ "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSTBNRFV5TVRBM016TXlORm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlEa29VdTlwZ01JUHR2R0VEZi9tSXk3LzNjSTg2b3U5eTJaZkV6RkhuRFN0TUFvR0NDcUdTTTQ5QkFNQ0JFWXdSQUlnTWdkSG9rZHNWQndya3RYRzd1VmowMm9QVVNsQllaWGVPeXJyd3RsQk5MUUNJRDdzZnZPaThZcjVWNkVyNjFqU05sKzR3ZDhpR050YUxEdFRMZjNBQ0VhNkFBQUFBQUFBIiwiaGVhZGVyIjp7InB1YmxpY0tleUhhc2giOiJ4MnFmMTFaemRXbnFCZnc0U0NyOWxIYzZRc1JQOEp6Z2xrZnU5RTVkWUpnPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } }' ``` <img width="1045" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/1b5c8cb4-43bf-42ea-a82f-9c6db940950b"> -> Apple pay retry connectors. In here I had configured apple pay simplified flow for stripe and rapyd. And apple pay manual flow for cybersource and adyen mca without apple pay enabled <img width="1158" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/59e3a5ba-31f6-42f9-bb81-d388ced47e0e">
[ "crates/router/src/core/payments.rs", "crates/router/src/core/payments/helpers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4742
Bug: [BUG] Failing unit tests for routing and constraint graph ### Bug Description Certain unit tests in the `euclid` and `kgraph_utils` crates are failing. **euclid** ``` FAIL [ 0.032s] euclid frontend::dir::test::test_consistent_dir_key_naming ``` **kgraph_utils** ``` FAIL [ 0.037s] kgraph_utils mca::tests::test_debit_card_success_case ``` ### Expected Behavior All unit tests should pass. ### Actual Behavior Some tests fail owing to being outdated or due to a code discrepancy. ### Steps To Reproduce 1. Clone the main branch 2. Run the unit tests for the `euclid` and `kgraph_utils` crates ### Context For The Bug _No response_ ### Environment Local ### 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/euclid/src/frontend/dir.rs b/crates/euclid/src/frontend/dir.rs index bc16057fbb5..f2b9ab99049 100644 --- a/crates/euclid/src/frontend/dir.rs +++ b/crates/euclid/src/frontend/dir.rs @@ -809,6 +809,10 @@ mod test { let mut key_names: FxHashMap<DirKeyKind, String> = FxHashMap::default(); for key in DirKeyKind::iter() { + if matches!(key, DirKeyKind::Connector) { + continue; + } + let json_str = if let DirKeyKind::MetaData = key { r#""metadata""#.to_string() } else { diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index ed96cd9b545..b32c8c23bd9 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -716,7 +716,6 @@ mod tests { api_enums::CardNetwork::Mastercard, ]), accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![ - api_enums::Currency::USD, api_enums::Currency::INR, ])), accepted_countries: None, @@ -734,7 +733,6 @@ mod tests { ]), accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![ api_enums::Currency::GBP, - api_enums::Currency::PHP, ])), accepted_countries: None, minimum_amount: Some(10), @@ -752,14 +750,6 @@ mod tests { status: api_enums::ConnectorStatus::Inactive, }; - let currency_country_flow_filter = kgraph_types::CurrencyCountryFlowFilter { - currency: Some(HashSet::from([api_enums::Currency::INR])), - country: Some(HashSet::from([api_enums::CountryAlpha2::IN])), - not_available_flows: Some(kgraph_types::NotAvailableFlows { - capture_method: Some(api_enums::CaptureMethod::Manual), - }), - }; - let config_map = kgraph_types::CountryCurrencyFilter { connector_configs: HashMap::from([( api_enums::RoutableConnectors::Stripe, @@ -768,13 +758,31 @@ mod tests { kgraph_types::PaymentMethodFilterKey::PaymentMethodType( api_enums::PaymentMethodType::Credit, ), - currency_country_flow_filter.clone(), + kgraph_types::CurrencyCountryFlowFilter { + currency: Some(HashSet::from([ + api_enums::Currency::INR, + api_enums::Currency::USD, + ])), + country: Some(HashSet::from([api_enums::CountryAlpha2::IN])), + not_available_flows: Some(kgraph_types::NotAvailableFlows { + capture_method: Some(api_enums::CaptureMethod::Manual), + }), + }, ), ( kgraph_types::PaymentMethodFilterKey::PaymentMethodType( api_enums::PaymentMethodType::Debit, ), - currency_country_flow_filter, + kgraph_types::CurrencyCountryFlowFilter { + currency: Some(HashSet::from([ + api_enums::Currency::GBP, + api_enums::Currency::PHP, + ])), + country: Some(HashSet::from([api_enums::CountryAlpha2::IN])), + not_available_flows: Some(kgraph_types::NotAvailableFlows { + capture_method: Some(api_enums::CaptureMethod::Manual), + }), + }, ), ])), )]), @@ -838,8 +846,8 @@ mod tests { dirval!(Connector = Stripe), dirval!(PaymentMethod = Card), dirval!(CardType = Debit), - dirval!(CardNetwork = DinersClub), - dirval!(PaymentCurrency = GBP), + dirval!(CardNetwork = Maestro), + dirval!(PaymentCurrency = PHP), dirval!(PaymentAmount = 100), ]), &mut Memoization::new(),
2024-05-23T08:01:10Z
## Description <!-- Describe your changes in detail --> This PR fixes a couple of failing unit tests in the `euclid` and `kgraph_utils` crates. ### 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 unit tests locally. API Tests not required <img width="674" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/babeb68b-2e8c-4b9e-925c-08c6ff55a9a9"> <img width="762" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/a99b2bc7-57e2-45d6-a8af-754f0da52cbb">
ba624d049840f65fc21a5e578f8d4ba8543e1420
Running unit tests locally. API Tests not required <img width="674" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/babeb68b-2e8c-4b9e-925c-08c6ff55a9a9"> <img width="762" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/a99b2bc7-57e2-45d6-a8af-754f0da52cbb">
[ "crates/euclid/src/frontend/dir.rs", "crates/kgraph_utils/src/mca.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4740
Bug: Setup for Data services locally targeting clickhouse/ kafka and the relevant features on dashboard
diff --git a/README.md b/README.md index 5bfcfdfd62b..62e016d3620 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ The single API to access payment ecosystems across 130+ countries</div> <p align="center"> <a href="#%EF%B8%8F-quick-start-guide">Quick Start Guide</a> • - <a href="https://github.com/juspay/hyperswitch/blob/main/docs/try_local_system.md">Local Setup Guide</a> • + <a href="/docs/try_local_system.md">Local Setup Guide</a> • <a href="#-fast-integration-for-stripe-users">Fast Integration for Stripe Users</a> • <a href="https://api-reference.hyperswitch.io/introduction"> API Docs </a> • <a href="#-supported-features">Supported Features</a> • diff --git a/config/dashboard.toml b/config/dashboard.toml new file mode 100644 index 00000000000..9bb2b6bf336 --- /dev/null +++ b/config/dashboard.toml @@ -0,0 +1,38 @@ +[default.theme] +primary_color="#006DF9" +primary_hover_color="#005ED6" +sidebar_color="#242F48" + +[default.endpoints] +api_url="http://localhost:8080" # The backend hyperswitch API server for making payments +sdk_url="http://localhost:9050/HyperLoader.js" # SDK distribution url used for loading the SDK in control center +logo_url="" +favicon_url="" +mixpanel_token="" + +[default.features] +test_live_toggle=false +is_live_mode=false +email=false +quick_start=false +audit_trail=true +system_metrics=false +sample_data=false +frm=false +payout=true +recon=false +test_processors=true +feedback=false +mixpanel=false +generate_report=false +user_journey_analytics=false +authentication_analytics=false +surcharge=false +dispute_evidence_upload=false +paypal_automatic_flow=false +threeds_authenticator=false +global_search=false +dispute_analytics=true +configure_pmts=false +branding=false +totp=false \ No newline at end of file diff --git a/crates/analytics/docs/README.md b/crates/analytics/docs/README.md new file mode 100644 index 00000000000..b822edd810e --- /dev/null +++ b/crates/analytics/docs/README.md @@ -0,0 +1,104 @@ +# Running Kafka & Clickhouse with Analytics and Events Source Configuration + +This document provides instructions on how to run Kafka and Clickhouse using Docker Compose, and how to configure the analytics and events source. + +## Architecture + +------------------------+ + | Hyperswitch | + +------------------------+ + | + | + v + +------------------------+ + | Kafka | + | (Event Stream Broker) | + +------------------------+ + | + | + v + +------------------------+ + | ClickHouse | + | +------------------+ | + | | Kafka Engine | | + | | Table | | + | +------------------+ | + | | | + | v | + | +------------------+ | + | | Materialized | | + | | View (MV) | | + | +------------------+ | + | | | + | v | + | +------------------+ | + | | Storage Table | | + | +------------------+ | + +------------------------+ + + +## Starting the Containers + +Docker Compose can be used to start all the components. + +Run the following command: + +```bash +docker compose --profile olap up -d +``` +This will spawn up the following services +1. kafka +2. clickhouse +3. opensearch + +## Setting up Kafka + +Kafka-UI is a visual tool for inspecting Kafka and it can be accessed at `localhost:8090` to view topics, partitions, consumers & generated events. + +## Setting up Clickhouse + +Once Clickhouse is up and running, you can interact with it via web. + +You can either visit the URL (`http://localhost:8123/play`) where the Clickhouse server is running to get a playground, or you can bash into the Clickhouse container and execute commands manually. + +Run the following commands: + +```bash +# On your local terminal +docker compose exec clickhouse-server bash + +# Inside the clickhouse-server container shell +clickhouse-client --user default + +# Inside the clickhouse-client shell +SHOW TABLES; +``` + +## Configuring Analytics and Events Source + +To use Clickhouse and Kafka, you need to enable the `analytics.source` and update the `events.source` in the configuration file. + +You can do this in either the `config/development.toml` or `config/docker_compose.toml` file. + +Here's an example of how to do this: + +```toml +[analytics] +source = "clickhouse" + +[events] +source = "kafka" +``` + +After making this change, save the file and restart your application for the changes to take effect. + +## Enabling Data Features in Dashboard + +To check the data features in the dashboard, you need to enable them in the `config/dashboard.toml` configuration file. + +Here's an example of how to do this: + +```toml +[default.features] +audit_trail=true +system_metrics=true +``` \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/README.md b/crates/analytics/docs/clickhouse/README.md deleted file mode 100644 index 2fd48a30c29..00000000000 --- a/crates/analytics/docs/clickhouse/README.md +++ /dev/null @@ -1,45 +0,0 @@ -#### Starting the containers - -In our use case we rely on kafka for ingesting events. -hence we can use docker compose to start all the components - -``` -docker compose up -d clickhouse-server kafka-ui -``` - -> kafka-ui is a visual tool for inspecting kafka on localhost:8090 - -#### Setting up Clickhouse - -Once clickhouse is up & running you need to create the required tables for it - -you can either visit the url (http://localhost:8123/play) in which the clickhouse-server is running to get a playground -Alternatively you can bash into the clickhouse container & execute commands manually -``` -# On your local terminal -docker compose exec clickhouse-server bash - -# Inside the clickhouse-server container shell -clickhouse-client --user default - -# Inside the clickhouse-client shell -SHOW TABLES; -CREATE TABLE ...... -``` - -The table creation scripts are provided [here](./scripts) - -#### Running/Debugging your application -Once setup you can run your application either via docker compose or normally via cargo run - -Remember to enable the kafka_events via development.toml/docker_compose.toml files - -Inspect the [kafka-ui](http://localhost:8090) to check the messages being inserted in queue - -If the messages/topic are available then you can run select queries on your clickhouse table to ensure data is being populated... - -If the data is not being populated in clickhouse, you can check the error logs in clickhouse server via -``` -# Inside the clickhouse-server container shell -tail -f /var/log/clickhouse-server/clickhouse-server.err.log -``` \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 64d36caf248..a1e9e1dee92 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,5 +1,3 @@ -version: "3.8" - volumes: pg_data: redisinsight_store: @@ -137,8 +135,8 @@ services: context: ./docker dockerfile: web.Dockerfile environment: - - HYPERSWITCH_PUBLISHABLE_KEY=$HYPERSWITCH_PUBLISHABLE_KEY - - HYPERSWITCH_SECRET_KEY=$HYPERSWITCH_SECRET_KEY + - HYPERSWITCH_PUBLISHABLE_KEY=${HYPERSWITCH_PUBLISHABLE_KEY:PUBLISHABLE_KEY} + - HYPERSWITCH_SECRET_KEY=${HYPERSWITCH_SECRET_KEY:SECRET_KEY} - HYPERSWITCH_SERVER_URL=${HYPERSWITCH_SERVER_URL:-http://hyperswitch-server:8080} - HYPERSWITCH_CLIENT_URL=${HYPERSWITCH_CLIENT_URL:-http://localhost:9050} - SELF_SERVER_URL=${SELF_SERVER_URL:-http://localhost:5252} @@ -156,8 +154,11 @@ services: ports: - "9000:9000" environment: - - apiBaseUrl=http://localhost:8080 - - sdkBaseUrl=http://localhost:9050/HyperLoader.js + - configPath=/tmp/dashboard-config.toml + volumes: + - ./config/dashboard.toml:/tmp/dashboard-config.toml + depends_on: + - hyperswitch-web labels: logs: "promtail" @@ -185,38 +186,23 @@ services: - redis-cluster networks: - router_net - command: "bash -c 'export COUNT=${REDIS_CLUSTER_COUNT:-3} - - \ if [ $$COUNT -lt 3 ] - - \ then - - \ echo \"Minimum 3 nodes are needed for redis cluster\" - - \ exit 1 - - \ fi - - \ HOSTS=\"\" - - \ for ((c=1; c<=$$COUNT;c++)) - - \ do - - \ NODE=$COMPOSE_PROJECT_NAME-redis-cluster-$$c:6379 - - \ echo $$NODE - - \ HOSTS=\"$$HOSTS $$NODE\" - - \ done - - \ echo Creating a cluster with $$HOSTS - - \ redis-cli --cluster create $$HOSTS --cluster-yes - - \ '" - + command: |- + bash -c 'export COUNT=${REDIS_CLUSTER_COUNT:-3} + if [ $$COUNT -lt 3 ] + then + echo \"Minimum 3 nodes are needed for redis cluster\" + exit 1 + fi + HOSTS=\"\" + for ((c=1; c<=$$COUNT;c++)) + do + NODE=$COMPOSE_PROJECT_NAME-redis-cluster-$$c:6379 + echo $$NODE + HOSTS=\"$$HOSTS $$NODE\" + done + echo Creating a cluster with $$HOSTS + redis-cli --cluster create $$HOSTS --cluster-yes + ' ### Monitoring grafana: image: grafana/grafana:latest @@ -304,7 +290,7 @@ services: networks: - router_net profiles: - - full_kv + - monitoring ports: - "8001:8001" volumes: @@ -390,24 +376,20 @@ services: hostname: opensearch environment: - "discovery.type=single-node" - expose: - - "9200" + profiles: + - olap ports: - "9200:9200" networks: - router_net - profiles: - - olap opensearch-dashboards: image: opensearchproject/opensearch-dashboards:1.3.14 ports: - 5601:5601 - expose: - - "5601" + profiles: + - olap environment: OPENSEARCH_HOSTS: '["https://opensearch:9200"]' networks: - router_net - profiles: - - olap
2024-05-23T07:33:28Z
## Description <!-- Describe your changes in detail --> Fixes #4740 - Update `docker-compose.yml` profiles to unfiy them - Add steps in `try_local_system.md` to setup data services - Add additional documentation in `analytics` crate to enable features in `control-center` - update architecture diagram to include data services ### 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). --> - Providing a better user experience for self hosting users ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Don't need to test since doc changes only
13f6efc7e8c01b4a377f627b9cfe2319b518204d
- Don't need to test since doc changes only
[ "README.md", "config/dashboard.toml", "crates/analytics/docs/README.md", "crates/analytics/docs/clickhouse/README.md", "docker-compose.yml" ]
juspay/hyperswitch
juspay__hyperswitch-4736
Bug: feat: add support to verify using recovery code Create a new endpoint that adds, - support to verify 2FA with recovery code - the provided recovery code can be used only once - then verification can be done with the remaining recovery codes only next time ( there are total 8 set of recovery codes that are being generated when configuring 2FA)
diff --git a/config/config.example.toml b/config/config.example.toml index 5d575b5ba09..d5bdfb5a6a7 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -351,7 +351,8 @@ email_role_arn = "" # The amazon resource name ( arn ) of the role which sts_role_session_name = "" # An identifier for the assumed role session, used to uniquely identify a session. [user] -password_validity_in_days = 90 # Number of days after which password should be updated +password_validity_in_days = 90 # Number of days after which password should be updated +two_factor_auth_expiry_in_secs = 300 # Number of seconds after which 2FA should be done again if doing update/change from inside #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 5b6c5fe152d..9551cd2a80d 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -113,6 +113,7 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw [user] password_validity_in_days = 90 +two_factor_auth_expiry_in_secs = 300 [frm] enabled = true diff --git a/config/deployments/production.toml b/config/deployments/production.toml index b5441f0059d..5f940867438 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -120,6 +120,7 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw [user] password_validity_in_days = 90 +two_factor_auth_expiry_in_secs = 300 [frm] enabled = false diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index e168fab121d..d5f63524e6b 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -120,6 +120,7 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw [user] password_validity_in_days = 90 +two_factor_auth_expiry_in_secs = 300 [frm] enabled = true diff --git a/config/development.toml b/config/development.toml index af26d91446f..a9f7f4d7b4d 100644 --- a/config/development.toml +++ b/config/development.toml @@ -269,6 +269,7 @@ sts_role_session_name = "" [user] password_validity_in_days = 90 +two_factor_auth_expiry_in_secs = 300 [bank_config.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" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 0d615b11b5c..6661d164032 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -53,6 +53,7 @@ recon_admin_api_key = "recon_test_admin" [user] password_validity_in_days = 90 +two_factor_auth_expiry_in_secs = 300 [locker] host = "" diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index b7d7adbf8e3..a472b3a76e6 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -17,7 +17,7 @@ use crate::user::{ RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse, UpdateUserAccountDetailsRequest, UserFromEmailRequest, - UserMerchantCreate, VerifyEmailRequest, VerifyTotpRequest, + UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -75,6 +75,7 @@ common_utils::impl_misc_api_event_type!( TokenResponse, UserFromEmailRequest, BeginTotpResponse, + VerifyRecoveryCodeRequest, VerifyTotpRequest, RecoveryCodes ); diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 6b2748ca344..5423fc830a5 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -263,6 +263,11 @@ pub struct VerifyTotpRequest { pub totp: Option<Secret<String>>, } +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct VerifyRecoveryCodeRequest { + pub recovery_code: Secret<String>, +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct RecoveryCodes { pub recovery_codes: Vec<Secret<String>>, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 9564a759ccd..b8a315f944b 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -395,6 +395,7 @@ pub struct Secrets { #[derive(Debug, Clone, Default, Deserialize)] pub struct UserSettings { pub password_validity_in_days: u16, + pub two_factor_auth_expiry_in_secs: i64, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index 7b61a834f60..2f347dc3d3e 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -14,4 +14,4 @@ pub const MAX_PASSWORD_LENGTH: usize = 70; pub const MIN_PASSWORD_LENGTH: usize = 8; pub const TOTP_PREFIX: &str = "TOTP_"; -pub const REDIS_RECOVERY_CODES_PREFIX: &str = "RC_"; +pub const REDIS_RECOVERY_CODE_PREFIX: &str = "RC_"; diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index cda85078718..adcf8794b83 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -72,6 +72,8 @@ pub enum UserErrors { InvalidTotp, #[error("TotpRequired")] TotpRequired, + #[error("InvalidRecoveryCode")] + InvalidRecoveryCode, #[error("TwoFactorAuthRequired")] TwoFactorAuthRequired, #[error("TwoFactorAuthNotSetup")] @@ -188,12 +190,15 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::TotpRequired => { AER::BadRequest(ApiError::new(sub_code, 38, self.get_error_message(), None)) } - Self::TwoFactorAuthRequired => { + Self::InvalidRecoveryCode => { AER::BadRequest(ApiError::new(sub_code, 39, self.get_error_message(), None)) } - Self::TwoFactorAuthNotSetup => { + Self::TwoFactorAuthRequired => { AER::BadRequest(ApiError::new(sub_code, 40, self.get_error_message(), None)) } + Self::TwoFactorAuthNotSetup => { + AER::BadRequest(ApiError::new(sub_code, 41, self.get_error_message(), None)) + } } } } @@ -233,6 +238,7 @@ impl UserErrors { Self::TotpNotSetup => "TOTP not setup", Self::InvalidTotp => "Invalid TOTP", Self::TotpRequired => "TOTP required", + Self::InvalidRecoveryCode => "Invalid Recovery Code", Self::TwoFactorAuthRequired => "Two factor auth required", Self::TwoFactorAuthNotSetup => "Two factor auth not setup", } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 705c12907ff..4fd9fa865cd 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -179,7 +179,7 @@ pub async fn signin( })? .into(); - user_from_db.compare_password(request.password)?; + user_from_db.compare_password(&request.password)?; let signin_strategy = if let Some(preferred_merchant_id) = user_from_db.get_preferred_merchant_id() { @@ -217,7 +217,7 @@ pub async fn signin_token_only_flow( .to_not_found_response(UserErrors::InvalidCredentials)? .into(); - user_from_db.compare_password(request.password)?; + user_from_db.compare_password(&request.password)?; let next_flow = domain::NextFlow::from_origin(domain::Origin::SignIn, user_from_db.clone(), &state).await?; @@ -341,7 +341,7 @@ pub async fn change_password( .change_context(UserErrors::InternalServerError)? .into(); - user.compare_password(request.old_password.to_owned()) + user.compare_password(&request.old_password) .change_context(UserErrors::InvalidOldPassword)?; if request.old_password == request.new_password { @@ -439,7 +439,7 @@ pub async fn rotate_password( let password = domain::UserPassword::new(request.password.to_owned())?; let hash_password = utils::user::password::generate_password_hash(password.get_secret())?; - if user.compare_password(request.password).is_ok() { + if user.compare_password(&request.password).is_ok() { return Err(UserErrors::ChangePasswordError.into()); } @@ -1766,6 +1766,51 @@ pub async fn generate_recovery_codes( })) } +pub async fn verify_recovery_code( + state: AppState, + user_token: auth::UserFromSinglePurposeToken, + req: user_api::VerifyRecoveryCodeRequest, +) -> UserResponse<user_api::TokenResponse> { + let user_from_db: domain::UserFromStorage = state + .store + .find_user_by_id(&user_token.user_id) + .await + .change_context(UserErrors::InternalServerError)? + .into(); + + if user_from_db.get_totp_status() != TotpStatus::Set { + return Err(UserErrors::TwoFactorAuthNotSetup.into()); + } + + let mut recovery_codes = user_from_db + .get_recovery_codes() + .ok_or(UserErrors::InternalServerError)?; + + let matching_index = utils::user::password::get_index_for_correct_recovery_code( + &req.recovery_code, + &recovery_codes, + )? + .ok_or(UserErrors::InvalidRecoveryCode)?; + + tfa_utils::insert_recovery_code_in_redis(&state, user_from_db.get_user_id()).await?; + let _ = recovery_codes.remove(matching_index); + + state + .store + .update_user_by_user_id( + user_from_db.get_user_id(), + storage_user::UserUpdate::TotpUpdate { + totp_status: None, + totp_secret: None, + totp_recovery_codes: Some(recovery_codes), + }, + ) + .await + .change_context(UserErrors::InternalServerError)?; + + Ok(ApplicationResponse::StatusOk) +} + pub async fn terminate_two_factor_auth( state: AppState, user_token: auth::UserFromSinglePurposeToken, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index cf2e986c325..bad5ab5a926 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1212,14 +1212,16 @@ impl User { ) .service(web::resource("/totp/begin").route(web::get().to(totp_begin))) .service(web::resource("/totp/verify").route(web::post().to(totp_verify))) - .service( - web::resource("/recovery_codes/generate") - .route(web::get().to(generate_recovery_codes)), - ) .service( web::resource("/2fa/terminate").route(web::get().to(terminate_two_factor_auth)), ); + route = route.service( + web::scope("/recovery_code") + .service(web::resource("/verify").route(web::post().to(verify_recovery_code))) + .service(web::resource("/generate").route(web::post().to(generate_recovery_codes))), + ); + #[cfg(feature = "email")] { route = route diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 97d92d49911..75821bbd2ba 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -215,9 +215,9 @@ impl From<Flow> for ApiIdentifier { | Flow::UpdateUserAccountDetails | Flow::TotpBegin | Flow::TotpVerify - | Flow::TerminateTwoFactorAuth - | Flow::GenerateRecoveryCodes => Self::User, - + | Flow::RecoveryCodeVerify + | Flow::RecoveryCodesGenerate + | Flow::TerminateTwoFactorAuth => Self::User, Flow::ListRoles | Flow::GetRole | Flow::GetRoleFromToken diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 2019855114a..6b8015ac3e5 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -666,8 +666,26 @@ pub async fn totp_verify( .await } +pub async fn verify_recovery_code( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_api::VerifyRecoveryCodeRequest>, +) -> HttpResponse { + let flow = Flow::RecoveryCodeVerify; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, user, req_body, _| user_core::verify_recovery_code(state, user, req_body), + &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP), + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn generate_recovery_codes(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { - let flow = Flow::GenerateRecoveryCodes; + let flow = Flow::RecoveryCodesGenerate; Box::pin(api::server_wrap( flow, state.clone(), diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 0704e51e781..91323b0c16d 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -774,8 +774,8 @@ impl UserFromStorage { self.0.user_id.as_str() } - pub fn compare_password(&self, candidate: Secret<String>) -> UserResult<()> { - match password::is_correct_password(candidate, self.0.password.clone()) { + pub fn compare_password(&self, candidate: &Secret<String>) -> UserResult<()> { + match password::is_correct_password(candidate, &self.0.password) { Ok(true) => Ok(()), Ok(false) => Err(UserErrors::InvalidCredentials.into()), Err(e) => Err(e), diff --git a/crates/router/src/utils/user/password.rs b/crates/router/src/utils/user/password.rs index beb87c325b6..e01181acb9d 100644 --- a/crates/router/src/utils/user/password.rs +++ b/crates/router/src/utils/user/password.rs @@ -7,7 +7,7 @@ use argon2::{ }; use common_utils::errors::CustomResult; use error_stack::ResultExt; -use masking::{ExposeInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use rand::{seq::SliceRandom, Rng}; use crate::core::errors::UserErrors; @@ -25,13 +25,13 @@ pub fn generate_password_hash( } pub fn is_correct_password( - candidate: Secret<String>, - password: Secret<String>, + candidate: &Secret<String>, + password: &Secret<String>, ) -> CustomResult<bool, UserErrors> { - let password = password.expose(); + let password = password.peek(); let parsed_hash = - PasswordHash::new(&password).change_context(UserErrors::InternalServerError)?; - let result = Argon2::default().verify_password(candidate.expose().as_bytes(), &parsed_hash); + PasswordHash::new(password).change_context(UserErrors::InternalServerError)?; + let result = Argon2::default().verify_password(candidate.peek().as_bytes(), &parsed_hash); match result { Ok(_) => Ok(true), Err(argon2Err::Password) => Ok(false), @@ -40,6 +40,19 @@ pub fn is_correct_password( .change_context(UserErrors::InternalServerError) } +pub fn get_index_for_correct_recovery_code( + candidate: &Secret<String>, + recovery_codes: &[Secret<String>], +) -> CustomResult<Option<usize>, UserErrors> { + for (index, recovery_code) in recovery_codes.iter().enumerate() { + let is_match = is_correct_password(candidate, recovery_code)?; + if is_match { + return Ok(Some(index)); + } + } + Ok(None) +} + pub fn get_temp_password() -> Secret<String> { let uuid_pass = uuid::Uuid::new_v4().to_string(); let mut rng = rand::thread_rng(); diff --git a/crates/router/src/utils/user/two_factor_auth.rs b/crates/router/src/utils/user/two_factor_auth.rs index 479c346b6e5..e9e3f66005c 100644 --- a/crates/router/src/utils/user/two_factor_auth.rs +++ b/crates/router/src/utils/user/two_factor_auth.rs @@ -45,7 +45,7 @@ pub async fn check_totp_in_redis(state: &AppState, user_id: &str) -> UserResult< pub async fn check_recovery_code_in_redis(state: &AppState, user_id: &str) -> UserResult<bool> { let redis_conn = get_redis_connection(state)?; - let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODES_PREFIX, user_id); + let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn .exists::<()>(&key) .await @@ -59,3 +59,16 @@ fn get_redis_connection(state: &AppState) -> UserResult<Arc<RedisConnectionPool> .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get redis connection") } + +pub async fn insert_recovery_code_in_redis(state: &AppState, user_id: &str) -> UserResult<()> { + let redis_conn = get_redis_connection(state)?; + let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); + redis_conn + .set_key_with_expiry( + key.as_str(), + common_utils::date_time::now_unix_timestamp(), + state.conf.user.two_factor_auth_expiry_in_secs, + ) + .await + .change_context(UserErrors::InternalServerError) +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index be071ffefc3..35b55b6fb97 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -406,8 +406,10 @@ pub enum Flow { TotpBegin, /// Verify TOTP TotpVerify, + /// Verify Access Code + RecoveryCodeVerify, /// Generate or Regenerate recovery codes - GenerateRecoveryCodes, + RecoveryCodesGenerate, // Terminate two factor authentication TerminateTwoFactorAuth, /// List initial webhook delivery attempts diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index a104f5760b4..2c3e83ad2ba 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -30,6 +30,7 @@ jwt_secret = "secret" [user] password_validity_in_days = 90 +two_factor_auth_expiry_in_secs = 300 [locker] host = ""
2024-05-22T19:54:33Z
## Description The PR adds support to verify 2FA using recovery code, in case TOTP is lost ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes [#4736](https://github.com/juspay/hyperswitch/issues/4736) ## How did you test it? First Sign in for user for which 2FA is already set. Then to verify 2FA: Use the below curl to test it ``` curl --location 'http://localhost:8080/user/recovery_code/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer SPT' \ --header 'Cookie: Cookie_1=value' \ --data '{ "recovery_code": "j4Az-W7Fk" }' ``` If the recovery code is correct then response will be `200 ok`. Else proper error would be thrown ``` { "error": { "type": "invalid_request", "message": "Invalid Recovery Code", "code": "UR_39" } } ```
42e5ef155128f4df717e8fb101da6e6929659a0a
First Sign in for user for which 2FA is already set. Then to verify 2FA: Use the below curl to test it ``` curl --location 'http://localhost:8080/user/recovery_code/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer SPT' \ --header 'Cookie: Cookie_1=value' \ --data '{ "recovery_code": "j4Az-W7Fk" }' ``` If the recovery code is correct then response will be `200 ok`. Else proper error would be thrown ``` { "error": { "type": "invalid_request", "message": "Invalid Recovery Code", "code": "UR_39" } } ```
[ "config/config.example.toml", "config/deployments/integration_test.toml", "config/deployments/production.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/src/events/user.rs", "crates/api_models/src/user.rs", "crates/router/src/conf...
juspay/hyperswitch
juspay__hyperswitch-4734
Bug: [BUG] Decrypt the card without having locker as a fallback ### Feature Description Decrypt the card without having locker as a fallback ### Possible Implementation Decrypt the card without having locker as a fallback ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 8dbef81b906..a3ed16def0c 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -3,7 +3,8 @@ use std::marker::PhantomData; use api_models::{ admin::ExtendedCardInfoConfig, enums::FrmSuggestion, - payments::{AdditionalCardInfo, AdditionalPaymentData, ExtendedCardInfo}, + payment_methods::PaymentMethodsData, + payments::{AdditionalPaymentData, ExtendedCardInfo}, }; use async_trait::async_trait; use common_utils::ext_traits::{AsyncExt, Encode, StringExt, ValueExt}; @@ -21,7 +22,6 @@ use crate::{ blocklist::utils as blocklist_utils, errors::{self, CustomResult, RouterResult, StorageErrorExt}, mandate::helpers as m_helpers, - payment_methods::cards, payments::{ self, helpers, operations, populate_surcharge_details, CustomerDetails, PaymentAddress, PaymentData, @@ -34,7 +34,7 @@ use crate::{ types::{ self, api::{self, ConnectorCallType, PaymentIdTypeExt}, - domain, + domain::{self, types::decrypt}, storage::{self, enums as storage_enums}, }, utils::{self, OptionExt}, @@ -1040,26 +1040,39 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode additional pm data")?; - let key = key_store.key.get_inner().peek(); + let encode_additional_pm_to_value = if let Some(ref pm) = payment_data.payment_method_info { + let key = key_store.key.get_inner().peek(); - let card_detail_from_locker = payment_data - .payment_method_info - .as_ref() - .async_map(|pm| async move { - cards::get_card_details_without_locker_fallback(pm, key, state).await + let card_detail_from_locker: Option<api::CardDetailFromLocker> = + decrypt::<serde_json::Value, masking::WithType>( + pm.payment_method_data.clone(), + key, + ) + .await + .change_context(errors::StorageError::DecryptionError) + .attach_printable("unable to decrypt card details") + .ok() + .flatten() + .map(|x| x.into_inner().expose()) + .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok()) + .and_then(|pmd| match pmd { + PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), + _ => None, + }); + + card_detail_from_locker.and_then(|card_details| { + let additional_data = card_details.into(); + let additional_data_payment = + AdditionalPaymentData::Card(Box::new(additional_data)); + additional_data_payment + .encode_to_value() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encode additional pm data") + .ok() }) - .await - .transpose()?; - - let additional_data: Option<AdditionalCardInfo> = card_detail_from_locker.map(From::from); - - let encode_additional_pm_to_value = additional_data - .map(|additional_data| AdditionalPaymentData::Card(Box::new(additional_data))) - .as_ref() - .map(Encode::encode_to_value) - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to encode additional pm data")?; + } else { + None + }; let business_sub_label = payment_data.payment_attempt.business_sub_label.clone(); let authentication_type = payment_data.payment_attempt.authentication_type;
2024-05-22T16:43:57Z
## Description The token based MIT payments were throwing a 5xx , as this [PR](https://github.com/juspay/hyperswitch/pull/4711) called locker every time as a fallback while trying to decrypt the card . This PR fixes the failing token based MIT 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? -Create a MA and a MCA - Create a off_session payment , with google pay token - Create another recurring payment via google pay > ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_QEGuyQGnDNOXysqCH4yETBv5kLrF9Nk0cktqhVcnxEutsoJQZkAlmeQ4rITJHTI5' \ --data-raw '{ "amount": 6777, "currency": "USD", "confirm": false, "customer_id": "new-c777", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage":"off_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` > ``` Confirm curl --location 'http://localhost:8080/payments/pay_MmhKI2g6MjI22FZbi1jh/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_QEGuyQGnDNOXysqCH4yETBv5kLrF9Nk0cktqhVcnxEutsoJQZkAlmeQ4rITJHTI5' \ --data '{ "confirm": true, "payment_method": "wallet", "payment_method_type": "google_pay", "payment_token": "token_5rtAjgUaL0bLDjfj185V" }' ``` > Response ``` { "payment_id": "pay_MmhKI2g6MjI22FZbi1jh", "merchant_id": "merchant_1716403278", "status": "succeeded", "amount": 6777, "net_amount": 6777, "amount_capturable": 0, "amount_received": 6777, "connector": "bankofamerica", "client_secret": "pay_MmhKI2g6MjI22FZbi1jh_secret_GbiTtFazN61AKDLwJMMu", "created": "2024-05-22T18:41:47.798Z", "currency": "USD", "customer_id": "new-c777", "customer": { "id": "new-c777", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": null, "payment_token": "token_5rtAjgUaL0bLDjfj185V", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "google_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7164033224736237803955", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pay_MmhKI2g6MjI22FZbi1jh_1", "payment_link": null, "profile_id": "pro_iBJ1GnZMmCPPTzJ0izXc", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_WTIH9V0jHkOxRG9L01ux", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-22T18:56:47.798Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_hrBVSNziVDNOzeGqvMCB", "payment_method_status": "active", "updated": "2024-05-22T18:42:03.520Z", "frm_metadata": null } ``` - For Cards > Do a token based MIT will see the card_details in the response ``` Resposne { "payment_id": "pay_4ZRUltEq1k4Swzm1NX3V", "merchant_id": "merchant_1716400925", "status": "succeeded", "amount": 6777, "net_amount": 6777, "amount_capturable": 0, "amount_received": 6777, "connector": "cybersource", "client_secret": "pay_4ZRUltEq1k4Swzm1NX3V_secret_Xy2mkCxiynpb4QVvJ87P", "created": "2024-05-22T18:05:27.351Z", "currency": "USD", "customer_id": "new-c777", "customer": { "id": "new-c777", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": null }, "authentication_data": null }, "billing": null }, "payment_token": "token_7wYGRb2yHaxmRHew4Nwb", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7164013142446089903955", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pay_4ZRUltEq1k4Swzm1NX3V_1", "payment_link": null, "profile_id": "pro_YaIF6M1jA9UH6xnB0Att", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_JWZiq29SfXxoNTiFGlG8", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-22T18:20:27.351Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_ByLjjOGIQdbHriocx497", "payment_method_status": "active", "updated": "2024-05-22T18:08:35.227Z", "frm_metadata": null } ``` - For Cybersource wallts recurring payments ``` Create curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \ --data-raw '{ "amount": 6777, "currency": "USD", "confirm": false, "customer_id": "new-c777", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage":"off_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` > ``` Confirm curl --location 'http://localhost:8080/payments/pay_6nyM2u8hRoS9YWDzSgqj/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \ --data '{ "confirm": true, "payment_method": "wallet", "payment_method_type": "google_pay", "payment_token": "token_qK3qo9EVuk5TE4sBb1v8" }' ``` > ``` Response { "payment_id": "pay_6nyM2u8hRoS9YWDzSgqj", "merchant_id": "merchant_1716404501", "status": "succeeded", "amount": 6777, "net_amount": 6777, "amount_capturable": 0, "amount_received": 6777, "connector": "cybersource", "client_secret": "pay_6nyM2u8hRoS9YWDzSgqj_secret_DEYEPOXvjoWgvzVvCDKK", "created": "2024-05-22T19:03:02.415Z", "currency": "USD", "customer_id": "new-c777", "customer": { "id": "new-c777", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": null, "payment_token": "token_qK3qo9EVuk5TE4sBb1v8", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "google_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7164045889206818003954", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pay_6nyM2u8hRoS9YWDzSgqj_1", "payment_link": null, "profile_id": "pro_NMDohQHyrqzAkUjBjDmB", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_JfI8xFhxTnL5q2bFhpUW", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-22T19:18:02.415Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka", "payment_method_status": "active", "updated": "2024-05-22T19:03:10.117Z", "frm_metadata": null } ```
d942a31d60595d366977746be7215620da0ababd
-Create a MA and a MCA - Create a off_session payment , with google pay token - Create another recurring payment via google pay > ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_QEGuyQGnDNOXysqCH4yETBv5kLrF9Nk0cktqhVcnxEutsoJQZkAlmeQ4rITJHTI5' \ --data-raw '{ "amount": 6777, "currency": "USD", "confirm": false, "customer_id": "new-c777", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage":"off_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` > ``` Confirm curl --location 'http://localhost:8080/payments/pay_MmhKI2g6MjI22FZbi1jh/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_QEGuyQGnDNOXysqCH4yETBv5kLrF9Nk0cktqhVcnxEutsoJQZkAlmeQ4rITJHTI5' \ --data '{ "confirm": true, "payment_method": "wallet", "payment_method_type": "google_pay", "payment_token": "token_5rtAjgUaL0bLDjfj185V" }' ``` > Response ``` { "payment_id": "pay_MmhKI2g6MjI22FZbi1jh", "merchant_id": "merchant_1716403278", "status": "succeeded", "amount": 6777, "net_amount": 6777, "amount_capturable": 0, "amount_received": 6777, "connector": "bankofamerica", "client_secret": "pay_MmhKI2g6MjI22FZbi1jh_secret_GbiTtFazN61AKDLwJMMu", "created": "2024-05-22T18:41:47.798Z", "currency": "USD", "customer_id": "new-c777", "customer": { "id": "new-c777", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": null, "payment_token": "token_5rtAjgUaL0bLDjfj185V", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "google_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7164033224736237803955", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pay_MmhKI2g6MjI22FZbi1jh_1", "payment_link": null, "profile_id": "pro_iBJ1GnZMmCPPTzJ0izXc", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_WTIH9V0jHkOxRG9L01ux", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-22T18:56:47.798Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_hrBVSNziVDNOzeGqvMCB", "payment_method_status": "active", "updated": "2024-05-22T18:42:03.520Z", "frm_metadata": null } ``` - For Cards > Do a token based MIT will see the card_details in the response ``` Resposne { "payment_id": "pay_4ZRUltEq1k4Swzm1NX3V", "merchant_id": "merchant_1716400925", "status": "succeeded", "amount": 6777, "net_amount": 6777, "amount_capturable": 0, "amount_received": 6777, "connector": "cybersource", "client_secret": "pay_4ZRUltEq1k4Swzm1NX3V_secret_Xy2mkCxiynpb4QVvJ87P", "created": "2024-05-22T18:05:27.351Z", "currency": "USD", "customer_id": "new-c777", "customer": { "id": "new-c777", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "11", "card_exp_year": "2040", "card_holder_name": "AKA", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": null }, "authentication_data": null }, "billing": null }, "payment_token": "token_7wYGRb2yHaxmRHew4Nwb", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7164013142446089903955", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pay_4ZRUltEq1k4Swzm1NX3V_1", "payment_link": null, "profile_id": "pro_YaIF6M1jA9UH6xnB0Att", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_JWZiq29SfXxoNTiFGlG8", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-22T18:20:27.351Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_ByLjjOGIQdbHriocx497", "payment_method_status": "active", "updated": "2024-05-22T18:08:35.227Z", "frm_metadata": null } ``` - For Cybersource wallts recurring payments ``` Create curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \ --data-raw '{ "amount": 6777, "currency": "USD", "confirm": false, "customer_id": "new-c777", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage":"off_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` > ``` Confirm curl --location 'http://localhost:8080/payments/pay_6nyM2u8hRoS9YWDzSgqj/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \ --data '{ "confirm": true, "payment_method": "wallet", "payment_method_type": "google_pay", "payment_token": "token_qK3qo9EVuk5TE4sBb1v8" }' ``` > ``` Response { "payment_id": "pay_6nyM2u8hRoS9YWDzSgqj", "merchant_id": "merchant_1716404501", "status": "succeeded", "amount": 6777, "net_amount": 6777, "amount_capturable": 0, "amount_received": 6777, "connector": "cybersource", "client_secret": "pay_6nyM2u8hRoS9YWDzSgqj_secret_DEYEPOXvjoWgvzVvCDKK", "created": "2024-05-22T19:03:02.415Z", "currency": "USD", "customer_id": "new-c777", "customer": { "id": "new-c777", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": null, "payment_token": "token_qK3qo9EVuk5TE4sBb1v8", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "google_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7164045889206818003954", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pay_6nyM2u8hRoS9YWDzSgqj_1", "payment_link": null, "profile_id": "pro_NMDohQHyrqzAkUjBjDmB", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_JfI8xFhxTnL5q2bFhpUW", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-22T19:18:02.415Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka", "payment_method_status": "active", "updated": "2024-05-22T19:03:10.117Z", "frm_metadata": null } ```
[ "crates/router/src/core/payments/operations/payment_confirm.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4733
Bug: [Refactor] Use recurring enabled flag to decide which payment method supports MIT ### Feature Description Use recurring enabled flag to decide which payment method supports MIT ### Possible Implementation Use recurring enabled flag to decide which payment method supports MIT ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/diesel_models/src/query/merchant_connector_account.rs b/crates/diesel_models/src/query/merchant_connector_account.rs index bd24d12ec22..cc73bd7a532 100644 --- a/crates/diesel_models/src/query/merchant_connector_account.rs +++ b/crates/diesel_models/src/query/merchant_connector_account.rs @@ -124,7 +124,9 @@ impl MerchantConnectorAccount { if get_disabled { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, - dsl::merchant_id.eq(merchant_id.to_owned()), + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::disabled.eq(true)), None, None, Some(dsl::created_at.asc()), diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 657ad625045..28121ecc801 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3525,7 +3525,22 @@ pub async fn list_customer_payment_method( ) .await .attach_printable("unable to decrypt payment method billing address details")?; - + let connector_mandate_details = pm + .connector_mandate_details + .clone() + .map(|val| { + val.parse_value::<storage::PaymentsMandateReference>("PaymentsMandateReference") + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize to Payment Mandate Reference ")?; + let mca_enabled = get_mca_status( + state, + &key_store, + &merchant_account.merchant_id, + connector_mandate_details, + ) + .await?; // Need validation for enabled payment method ,querying MCA let pma = api::CustomerPaymentMethod { payment_token: parent_payment_method_token.to_owned(), @@ -3537,7 +3552,7 @@ pub async fn list_customer_payment_method( card: payment_method_retrieval_context.card_details, metadata: pm.metadata, payment_method_issuer_code: pm.payment_method_issuer_code, - recurring_enabled: false, + recurring_enabled: mca_enabled, installment_payment_enabled: false, payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), created: Some(pm.created_at), @@ -3667,7 +3682,38 @@ pub async fn list_customer_payment_method( Ok(services::ApplicationResponse::Json(response)) } +pub async fn get_mca_status( + state: &routes::AppState, + key_store: &domain::MerchantKeyStore, + merchant_id: &str, + connector_mandate_details: Option<storage::PaymentsMandateReference>, +) -> errors::RouterResult<bool> { + if let Some(connector_mandate_details) = connector_mandate_details { + let mcas = state + .store + .find_merchant_connector_account_by_merchant_id_and_disabled_list( + merchant_id, + true, + key_store, + ) + .await + .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: merchant_id.to_string(), + })?; + let mut mca_ids = HashSet::new(); + for mca in mcas { + mca_ids.insert(mca.merchant_connector_id); + } + + for mca_id in connector_mandate_details.keys() { + if !mca_ids.contains(mca_id) { + return Ok(true); + } + } + } + Ok(false) +} pub async fn decrypt_generic_data<T>( data: Option<Encryption>, key: &[u8],
2024-05-22T14:10:18Z
## Description use recurring enabled flag in the lIst Customer Payment Method to decide which payment method supports MIT. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? - Create a MA and a MCA with 2 connectors , cybersource and stripe - Create a mandate payment with one card , lets say using stripe - create a mandate payment with some pm, let's say wallet with the connector cybersource - list the payment methods for the customer, the card which has mandate enabled will have the recurring field as true else false > So in the below case have not disabled any mca and then you do a list the recurring enabled field will come as true ``` Response { "customer_payment_methods": [ { "payment_token": "token_HeBYwsQiiuwKosGloeAF", "payment_method_id": "pm_N1PKc4pShnNg3zCCKFrY", "customer_id": "CustomerX", "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "11", "expiry_year": "2040", "card_token": null, "card_holder_name": "AKA", "card_fingerprint": null, "nick_name": "HELO", "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "metadata": null, "created": "2024-05-23T07:11:00.434Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-05-23T07:11:00.434Z", "default_payment_method_set": false, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } }, { "payment_token": "token_lMFXXJEri6mOFZOc0q1Y", "payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka", "customer_id": "CustomerX", "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": null, "metadata": null, "created": "2024-05-22T19:01:56.041Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-05-22T19:01:56.041Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "AE", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "Dubai", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+97" }, "email": null } } ], "is_guest_customer": null } ``` > Now if you disable cybersource then the list pm will show the recurring enabled field for wallets as false <img width="1680" alt="Screenshot 2024-05-23 at 12 46 15 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/11902155-dff0-4cf9-a4a0-7413810ea013"> ``` Response { "customer_payment_methods": [ { "payment_token": "token_P93Wev0NlWNzCqr0nHzz", "payment_method_id": "pm_N1PKc4pShnNg3zCCKFrY", "customer_id": "CustomerX", "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "11", "expiry_year": "2040", "card_token": null, "card_holder_name": "AKA", "card_fingerprint": null, "nick_name": "HELO", "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "metadata": null, "created": "2024-05-23T07:11:00.434Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-05-23T07:11:00.434Z", "default_payment_method_set": false, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } }, { "payment_token": "token_MaQ7pdm33YgwUHQtOSFe", "payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka", "customer_id": "CustomerX", "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": null, "metadata": null, "created": "2024-05-22T19:01:56.041Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-05-22T19:01:56.041Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "AE", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "Dubai", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+97" }, "email": null } } ], "is_guest_customer": null } ``` > Make a on_session payment with some other card, lets say `4111`, the recurring enabled will be false as there was no mandate setup with the connector ``` Create curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \ --data-raw ' {"amount": 7000, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "CustomerX", "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 } }, "setup_future_usage": "on_session" }' ``` ``` Confirm curl --location 'http://localhost:8080/payments/pay_Ig6fQkfaXJfMYNWFYRp2/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \ --data '{ "confirm": true, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "12", "card_exp_year": "2043", "card_holder_name": "Cy1", "card_cvc": "123" } }, "routing": { "type": "single", "data": {"connector":"cybersource","merchant_connector_id":"mca_JfI8xFhxTnL5q2bFhpUW"} }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" }} }' ``` ``` Response { "customer_payment_methods": [ { "payment_token": "token_bz048kmTQUOIn9ZVXt6P", "payment_method_id": "pm_SkeqCzMYhN4ztURPxxw9", "customer_id": "CustomerX", "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": null, "issuer_country": null, "last4_digits": "1111", "expiry_month": "12", "expiry_year": "2043", "card_token": null, "card_holder_name": "Cy1", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "411111", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "metadata": null, "created": "2024-05-23T07:19:38.071Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-05-23T07:19:38.071Z", "default_payment_method_set": false, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } }, { "payment_token": "token_XwND8wiXdMykgcfZQprc", "payment_method_id": "pm_N1PKc4pShnNg3zCCKFrY", "customer_id": "CustomerX", "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "11", "expiry_year": "2040", "card_token": null, "card_holder_name": "AKA", "card_fingerprint": null, "nick_name": "HELO", "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "metadata": null, "created": "2024-05-23T07:11:00.434Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-05-23T07:11:00.434Z", "default_payment_method_set": false, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } }, { "payment_token": "token_RDoIFRCyyWgRcaB2JPGa", "payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka", "customer_id": "CustomerX", "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": null, "metadata": null, "created": "2024-05-22T19:01:56.041Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-05-22T19:01:56.041Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "AE", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "Dubai", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+97" }, "email": null } } ], "is_guest_customer": null } ```
8afeda54fc5e3f3d510c48c81c222387e9cacc0e
- Create a MA and a MCA with 2 connectors , cybersource and stripe - Create a mandate payment with one card , lets say using stripe - create a mandate payment with some pm, let's say wallet with the connector cybersource - list the payment methods for the customer, the card which has mandate enabled will have the recurring field as true else false > So in the below case have not disabled any mca and then you do a list the recurring enabled field will come as true ``` Response { "customer_payment_methods": [ { "payment_token": "token_HeBYwsQiiuwKosGloeAF", "payment_method_id": "pm_N1PKc4pShnNg3zCCKFrY", "customer_id": "CustomerX", "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "11", "expiry_year": "2040", "card_token": null, "card_holder_name": "AKA", "card_fingerprint": null, "nick_name": "HELO", "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "metadata": null, "created": "2024-05-23T07:11:00.434Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-05-23T07:11:00.434Z", "default_payment_method_set": false, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } }, { "payment_token": "token_lMFXXJEri6mOFZOc0q1Y", "payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka", "customer_id": "CustomerX", "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": null, "metadata": null, "created": "2024-05-22T19:01:56.041Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-05-22T19:01:56.041Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "AE", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "Dubai", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+97" }, "email": null } } ], "is_guest_customer": null } ``` > Now if you disable cybersource then the list pm will show the recurring enabled field for wallets as false <img width="1680" alt="Screenshot 2024-05-23 at 12 46 15 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/11902155-dff0-4cf9-a4a0-7413810ea013"> ``` Response { "customer_payment_methods": [ { "payment_token": "token_P93Wev0NlWNzCqr0nHzz", "payment_method_id": "pm_N1PKc4pShnNg3zCCKFrY", "customer_id": "CustomerX", "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "11", "expiry_year": "2040", "card_token": null, "card_holder_name": "AKA", "card_fingerprint": null, "nick_name": "HELO", "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "metadata": null, "created": "2024-05-23T07:11:00.434Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-05-23T07:11:00.434Z", "default_payment_method_set": false, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } }, { "payment_token": "token_MaQ7pdm33YgwUHQtOSFe", "payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka", "customer_id": "CustomerX", "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": null, "metadata": null, "created": "2024-05-22T19:01:56.041Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-05-22T19:01:56.041Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "AE", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "Dubai", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+97" }, "email": null } } ], "is_guest_customer": null } ``` > Make a on_session payment with some other card, lets say `4111`, the recurring enabled will be false as there was no mandate setup with the connector ``` Create curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \ --data-raw ' {"amount": 7000, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "CustomerX", "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 } }, "setup_future_usage": "on_session" }' ``` ``` Confirm curl --location 'http://localhost:8080/payments/pay_Ig6fQkfaXJfMYNWFYRp2/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \ --data '{ "confirm": true, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "12", "card_exp_year": "2043", "card_holder_name": "Cy1", "card_cvc": "123" } }, "routing": { "type": "single", "data": {"connector":"cybersource","merchant_connector_id":"mca_JfI8xFhxTnL5q2bFhpUW"} }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" }} }' ``` ``` Response { "customer_payment_methods": [ { "payment_token": "token_bz048kmTQUOIn9ZVXt6P", "payment_method_id": "pm_SkeqCzMYhN4ztURPxxw9", "customer_id": "CustomerX", "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": null, "issuer_country": null, "last4_digits": "1111", "expiry_month": "12", "expiry_year": "2043", "card_token": null, "card_holder_name": "Cy1", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "411111", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "metadata": null, "created": "2024-05-23T07:19:38.071Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-05-23T07:19:38.071Z", "default_payment_method_set": false, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } }, { "payment_token": "token_XwND8wiXdMykgcfZQprc", "payment_method_id": "pm_N1PKc4pShnNg3zCCKFrY", "customer_id": "CustomerX", "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "11", "expiry_year": "2040", "card_token": null, "card_holder_name": "AKA", "card_fingerprint": null, "nick_name": "HELO", "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "metadata": null, "created": "2024-05-23T07:11:00.434Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-05-23T07:11:00.434Z", "default_payment_method_set": false, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null } }, { "payment_token": "token_RDoIFRCyyWgRcaB2JPGa", "payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka", "customer_id": "CustomerX", "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": null, "metadata": null, "created": "2024-05-22T19:01:56.041Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2024-05-22T19:01:56.041Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "AE", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "Dubai", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+97" }, "email": null } } ], "is_guest_customer": null } ```
[ "crates/diesel_models/src/query/merchant_connector_account.rs", "crates/router/src/core/payment_methods/cards.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4730
Bug: refactor: Separate out totp completion from verify Currently,`verify_totp` is the terminating 2fa API and also it was setting the TOTP status as "SET". So , we want to separate the logic of terminating the 2FA to a separate API so that the job of the `verify_totp` API will only be to verify if the totp is valid or not which will also help in reusing it inside dashboard.
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 7864117856e..6b2748ca344 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -224,6 +224,11 @@ pub struct TokenOnlyQueryParam { pub token_only: Option<bool>, } +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct SkipTwoFactorAuthQueryParam { + pub skip_two_factor_auth: Option<bool>, +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TokenResponse { pub token: Secret<String>, diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index 33642205d57..7b61a834f60 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -14,3 +14,4 @@ pub const MAX_PASSWORD_LENGTH: usize = 70; pub const MIN_PASSWORD_LENGTH: usize = 8; pub const TOTP_PREFIX: &str = "TOTP_"; +pub const REDIS_RECOVERY_CODES_PREFIX: &str = "RC_"; diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index 2d1c196f5df..cda85078718 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -72,6 +72,10 @@ pub enum UserErrors { InvalidTotp, #[error("TotpRequired")] TotpRequired, + #[error("TwoFactorAuthRequired")] + TwoFactorAuthRequired, + #[error("TwoFactorAuthNotSetup")] + TwoFactorAuthNotSetup, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -184,6 +188,12 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::TotpRequired => { AER::BadRequest(ApiError::new(sub_code, 38, self.get_error_message(), None)) } + Self::TwoFactorAuthRequired => { + AER::BadRequest(ApiError::new(sub_code, 39, self.get_error_message(), None)) + } + Self::TwoFactorAuthNotSetup => { + AER::BadRequest(ApiError::new(sub_code, 40, self.get_error_message(), None)) + } } } } @@ -223,6 +233,8 @@ impl UserErrors { Self::TotpNotSetup => "TOTP not setup", Self::InvalidTotp => "Invalid TOTP", Self::TotpRequired => "TOTP required", + Self::TwoFactorAuthRequired => "Two factor auth required", + Self::TwoFactorAuthNotSetup => "Two factor auth not setup", } } } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 7a0ef683e7a..705c12907ff 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -24,8 +24,9 @@ use crate::{ routes::{app::ReqState, AppState}, services::{authentication as auth, authorization::roles, ApplicationResponse}, types::{domain, transformers::ForeignInto}, - utils, + utils::{self, user::two_factor_auth as tfa_utils}, }; + pub mod dashboard_metadata; #[cfg(feature = "dummy_connector")] pub mod sample_data; @@ -1631,7 +1632,7 @@ pub async fn begin_totp( })); } - let totp = utils::user::two_factor_auth::generate_default_totp(user_from_db.get_email(), None)?; + let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), None)?; let recovery_codes = domain::RecoveryCodes::generate_new(); let key_store = user_from_db.get_or_create_key_store(&state).await?; @@ -1693,10 +1694,8 @@ pub async fn verify_totp( .await? .ok_or(UserErrors::InternalServerError)?; - let totp = utils::user::two_factor_auth::generate_default_totp( - user_from_db.get_email(), - Some(user_totp_secret), - )?; + let totp = + tfa_utils::generate_default_totp(user_from_db.get_email(), Some(user_totp_secret))?; if totp .generate_current() @@ -1739,7 +1738,7 @@ pub async fn generate_recovery_codes( state: AppState, user_token: auth::UserFromSinglePurposeToken, ) -> UserResponse<user_api::RecoveryCodes> { - if !utils::user::two_factor_auth::check_totp_in_redis(&state, &user_token.user_id).await? { + if !tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await? { return Err(UserErrors::TotpRequired.into()); } @@ -1766,3 +1765,55 @@ pub async fn generate_recovery_codes( recovery_codes: recovery_codes.into_inner(), })) } + +pub async fn terminate_two_factor_auth( + state: AppState, + user_token: auth::UserFromSinglePurposeToken, + skip_two_factor_auth: bool, +) -> UserResponse<user_api::TokenResponse> { + let user_from_db: domain::UserFromStorage = state + .store + .find_user_by_id(&user_token.user_id) + .await + .change_context(UserErrors::InternalServerError)? + .into(); + + if !skip_two_factor_auth { + if !tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await? + && !tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id).await? + { + return Err(UserErrors::TwoFactorAuthRequired.into()); + } + + if user_from_db.get_recovery_codes().is_none() { + return Err(UserErrors::TwoFactorAuthNotSetup.into()); + } + + if user_from_db.get_totp_status() != TotpStatus::Set { + state + .store + .update_user_by_user_id( + user_from_db.get_user_id(), + storage_user::UserUpdate::TotpUpdate { + totp_status: Some(TotpStatus::Set), + totp_secret: None, + totp_recovery_codes: None, + }, + ) + .await + .change_context(UserErrors::InternalServerError)?; + } + } + + let current_flow = domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::TOTP.into())?; + let next_flow = current_flow.next(user_from_db, &state).await?; + let token = next_flow.get_token(&state).await?; + + auth::cookies::set_cookie_response( + user_api::TokenResponse { + token: token.clone(), + token_type: next_flow.get_flow().into(), + }, + token, + ) +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0e152ec32c1..cf2e986c325 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1215,6 +1215,9 @@ impl User { .service( web::resource("/recovery_codes/generate") .route(web::get().to(generate_recovery_codes)), + ) + .service( + web::resource("/2fa/terminate").route(web::get().to(terminate_two_factor_auth)), ); #[cfg(feature = "email")] diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 706726979dc..97d92d49911 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -215,6 +215,7 @@ impl From<Flow> for ApiIdentifier { | Flow::UpdateUserAccountDetails | Flow::TotpBegin | Flow::TotpVerify + | Flow::TerminateTwoFactorAuth | Flow::GenerateRecoveryCodes => Self::User, Flow::ListRoles diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index f542c446e49..2019855114a 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -679,3 +679,23 @@ pub async fn generate_recovery_codes(state: web::Data<AppState>, req: HttpReques )) .await } + +pub async fn terminate_two_factor_auth( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<user_api::SkipTwoFactorAuthQueryParam>, +) -> HttpResponse { + let flow = Flow::TerminateTwoFactorAuth; + let skip_two_factor_auth = query.into_inner().skip_two_factor_auth.unwrap_or(false); + + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + (), + |state, user, _, _| user_core::terminate_two_factor_auth(state, user, skip_two_factor_auth), + &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 051e6ccf38e..0704e51e781 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -930,6 +930,10 @@ impl UserFromStorage { self.0.totp_status } + pub fn get_recovery_codes(&self) -> Option<Vec<Secret<String>>> { + self.0.totp_recovery_codes.clone() + } + pub async fn decrypt_and_get_totp_secret( &self, state: &AppState, diff --git a/crates/router/src/utils/user/two_factor_auth.rs b/crates/router/src/utils/user/two_factor_auth.rs index 62bcf2f7eb1..479c346b6e5 100644 --- a/crates/router/src/utils/user/two_factor_auth.rs +++ b/crates/router/src/utils/user/two_factor_auth.rs @@ -43,6 +43,15 @@ pub async fn check_totp_in_redis(state: &AppState, user_id: &str) -> UserResult< .change_context(UserErrors::InternalServerError) } +pub async fn check_recovery_code_in_redis(state: &AppState, user_id: &str) -> UserResult<bool> { + let redis_conn = get_redis_connection(state)?; + let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODES_PREFIX, user_id); + redis_conn + .exists::<()>(&key) + .await + .change_context(UserErrors::InternalServerError) +} + fn get_redis_connection(state: &AppState) -> UserResult<Arc<RedisConnectionPool>> { state .store diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 0e35aba3174..be071ffefc3 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -408,6 +408,8 @@ pub enum Flow { TotpVerify, /// Generate or Regenerate recovery codes GenerateRecoveryCodes, + // Terminate two factor authentication + TerminateTwoFactorAuth, /// List initial webhook delivery attempts WebhookEventInitialDeliveryAttemptList, /// List delivery attempts for a webhook event
2024-05-22T12:38:12Z
## Description Currently completion of 2fa and setting the status of the 2fa status as "SET" is handled by `verify_totp` API. We want to remove this from `verify_totp`, so this PR creates a new API to terminate the 2fa flow. ### 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 This will close the issue #4730 ## How did you test it? This can only be tested locally as it requires some changes in the redis. 1. terminate 2fa without skip_two_factor_auth query param a. If the keys with `TOTP_{user_id}` or `RC_{user_id}` is not present in redis Request ``` curl --location 'http://localhost:8080/user/2fa/terminate' \ --header 'Authorization: Bearer SPT with purpose as TOTP' ``` Response ``` { "error": { "type": "invalid_request", "message": "Two factor auth required", "code": "UR_39" } } ``` b. Add the keys to the redis with prefix as `TOTP_{user_id}` or `RC_{user_id}` Request ``` curl --location 'http://localhost:8080/user/2fa/terminate' \ --header 'Authorization: Bearer SPT with purpose as TOTP' ``` Response This will also set the totp_status for the user as "set" ``` { "token": "Bearer token", "token_type": "next flow token type" } ``` 2. terminate 2fa with skip_two_factor_auth query param a. skip_two_factor_auth=true Irrespective if the keys are present in redis or not if skip_two_factor_auth is sent as true it will not change the status and will give the token and token_type for the next flow Request ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: Bearer SPT with purpose as TOTP' ``` Response ``` { "token": "Bearer token", "token_type": "next flow token type" } ``` b. skip_two_factor_auth=false Request ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=false' \ --header 'Authorization: Bearer SPT with purpose as TOTP' ``` Response This will also set the totp_status for the user as "set" ``` { "token": "Bearer token", "token_type": "next flow token type" } ```
8afeda54fc5e3f3d510c48c81c222387e9cacc0e
This can only be tested locally as it requires some changes in the redis. 1. terminate 2fa without skip_two_factor_auth query param a. If the keys with `TOTP_{user_id}` or `RC_{user_id}` is not present in redis Request ``` curl --location 'http://localhost:8080/user/2fa/terminate' \ --header 'Authorization: Bearer SPT with purpose as TOTP' ``` Response ``` { "error": { "type": "invalid_request", "message": "Two factor auth required", "code": "UR_39" } } ``` b. Add the keys to the redis with prefix as `TOTP_{user_id}` or `RC_{user_id}` Request ``` curl --location 'http://localhost:8080/user/2fa/terminate' \ --header 'Authorization: Bearer SPT with purpose as TOTP' ``` Response This will also set the totp_status for the user as "set" ``` { "token": "Bearer token", "token_type": "next flow token type" } ``` 2. terminate 2fa with skip_two_factor_auth query param a. skip_two_factor_auth=true Irrespective if the keys are present in redis or not if skip_two_factor_auth is sent as true it will not change the status and will give the token and token_type for the next flow Request ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: Bearer SPT with purpose as TOTP' ``` Response ``` { "token": "Bearer token", "token_type": "next flow token type" } ``` b. skip_two_factor_auth=false Request ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=false' \ --header 'Authorization: Bearer SPT with purpose as TOTP' ``` Response This will also set the totp_status for the user as "set" ``` { "token": "Bearer token", "token_type": "next flow token type" } ```
[ "crates/api_models/src/user.rs", "crates/router/src/consts/user.rs", "crates/router/src/core/errors/user.rs", "crates/router/src/core/user.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/user.rs", "crates/router/src/types/domain/user.rs", "...
juspay/hyperswitch
juspay__hyperswitch-4729
Bug: [FEATURE] [Iatapay] add upi qr support ### Feature Description Add support for Upi QR code through Iatapay ### Possible Implementation 1. Add a upi intent payment id 2. Add a upi_qr payment data type 3. Do necessary contract changes ### 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 5f9618738b2..cd405e3ca98 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1664,7 +1664,10 @@ impl GetPaymentMethodType for CryptoData { impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { - api_enums::PaymentMethodType::UpiCollect + match self { + Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, + Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, + } } } impl GetPaymentMethodType for VoucherData { @@ -2119,11 +2122,21 @@ pub struct CryptoData { #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] -pub struct UpiData { +pub enum UpiData { + UpiCollect(UpiCollectData), + UpiIntent(UpiIntentData), +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct UpiIntentData {} + #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing @@ -2960,6 +2973,11 @@ pub enum NextActionData { /// The url for Qr code given by the connector qr_code_url: Option<Url>, }, + /// Contains url to fetch Qr code data + FetchQrCodeInformation { + #[schema(value_type = String)] + qr_code_fetch_url: Url, + }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] @@ -3045,6 +3063,11 @@ pub struct SdkNextActionData { pub next_action: NextActionCall, } +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct FetchQrCodeInformation { + pub qr_code_fetch_url: Url, +} + #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index dc4ca6b2cb3..3df291d5681 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1430,6 +1430,7 @@ pub enum PaymentMethodType { Trustly, Twint, UpiCollect, + UpiIntent, Vipps, Venmo, Walley, diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index faca2579c0a..cb37180c987 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1854,6 +1854,7 @@ impl From<PaymentMethodType> for PaymentMethod { PaymentMethodType::Trustly => Self::BankRedirect, PaymentMethodType::Twint => Self::Wallet, PaymentMethodType::UpiCollect => Self::Upi, + PaymentMethodType::UpiIntent => Self::Upi, PaymentMethodType::Vipps => Self::Wallet, PaymentMethodType::Venmo => Self::Wallet, PaymentMethodType::Walley => Self::PayLater, diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index c5f864bf770..133fee18c0d 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -268,6 +268,7 @@ pub enum CryptoType { #[strum(serialize_all = "snake_case")] pub enum UpiType { UpiCollect, + UpiIntent, } #[derive( diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs index f6b156bf909..cc4c9be2a2d 100644 --- a/crates/euclid/src/frontend/dir/lowering.rs +++ b/crates/euclid/src/frontend/dir/lowering.rs @@ -75,6 +75,7 @@ impl From<enums::UpiType> for global_enums::PaymentMethodType { fn from(value: enums::UpiType) -> Self { match value { enums::UpiType::UpiCollect => Self::UpiCollect, + enums::UpiType::UpiIntent => Self::UpiIntent, } } } diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs index bcc951b0057..052561b5aab 100644 --- a/crates/euclid/src/frontend/dir/transformers.rs +++ b/crates/euclid/src/frontend/dir/transformers.rs @@ -109,6 +109,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet } global_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)), global_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)), + global_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)), global_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)), global_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)), global_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)), diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 9dc85c103e9..7517918ed95 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -289,10 +289,20 @@ pub struct CryptoData { #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] -pub struct UpiData { +pub enum UpiData { + UpiCollect(UpiCollectData), + UpiIntent(UpiIntentData), +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub struct UpiCollectData { pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct UpiIntentData {} + #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum VoucherData { @@ -690,8 +700,12 @@ impl From<api_models::payments::CryptoData> for CryptoData { impl From<api_models::payments::UpiData> for UpiData { fn from(value: api_models::payments::UpiData) -> Self { - let api_models::payments::UpiData { vpa_id } = value; - Self { vpa_id } + match value { + api_models::payments::UpiData::UpiCollect(upi) => { + Self::UpiCollect(UpiCollectData { vpa_id: upi.vpa_id }) + } + api_models::payments::UpiData::UpiIntent(_) => Self::UpiIntent(UpiIntentData {}), + } } } diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index b32c8c23bd9..76c7381bf22 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -77,7 +77,6 @@ fn get_dir_value_payment_method( api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)), api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)), - api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)), api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)), api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)), api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)), @@ -133,6 +132,8 @@ fn get_dir_value_payment_method( api_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)), api_enums::PaymentMethodType::CardRedirect => Ok(dirval!(CardRedirectType = CardRedirect)), api_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)), + api_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)), + api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)), } } diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 3e43a4324f9..1bff0eac0d7 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -230,6 +230,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)), api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)), api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)), + api_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)), api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)), api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)), api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)), diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index c67ea2d2746..fd0688ed293 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -291,6 +291,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::CryptoData, api_models::payments::RewardData, api_models::payments::UpiData, + api_models::payments::UpiCollectData, + api_models::payments::UpiIntentData, api_models::payments::VoucherData, api_models::payments::BoletoVoucherData, api_models::payments::AlfamartVoucherData, diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 5e8c9ea08c0..0526eacb2e8 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -141,10 +141,10 @@ impl From<StripeWallet> for payments::WalletData { } impl From<StripeUpi> for payments::UpiData { - fn from(upi: StripeUpi) -> Self { - Self { - vpa_id: Some(upi.vpa_id), - } + fn from(upi_data: StripeUpi) -> Self { + Self::UpiCollect(payments::UpiCollectData { + vpa_id: Some(upi_data.vpa_id), + }) } } @@ -315,6 +315,18 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { let amount = item.amount.map(|amount| MinorUnit::new(amount).into()); + let payment_method_data = item.payment_method_data.as_ref().map(|pmd| { + let payment_method_data = match pmd.payment_method_details.as_ref() { + Some(spmd) => Some(payments::PaymentMethodData::from(spmd.to_owned())), + None => get_pmd_based_on_payment_method_type(item.payment_method_types), + }; + + payments::PaymentMethodDataRequest { + payment_method_data, + billing: pmd.billing_details.clone().map(payments::Address::from), + } + }); + let request = Ok(Self { payment_id: item.id.map(payments::PaymentIdType::PaymentIntentId), amount, @@ -334,16 +346,7 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { phone: item.shipping.as_ref().and_then(|s| s.phone.clone()), description: item.description, return_url: item.return_url, - payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| { - pmd.payment_method_details - .as_ref() - .map(|spmd| payments::PaymentMethodDataRequest { - payment_method_data: Some(payments::PaymentMethodData::from( - spmd.to_owned(), - )), - billing: pmd.billing_details.clone().map(payments::Address::from), - }) - }), + payment_method_data, payment_method: item .payment_method_data .as_ref() @@ -816,6 +819,9 @@ pub enum StripeNextAction { display_to_timestamp: Option<i64>, qr_code_url: Option<url::Url>, }, + FetchQrCodeInformation { + qr_code_fetch_url: url::Url, + }, DisplayVoucherInformation { voucher_details: payments::VoucherNextStepData, }, @@ -858,6 +864,9 @@ pub(crate) fn into_stripe_next_action( display_to_timestamp, qr_code_url, }, + payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => { + StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url } + } payments::NextActionData::DisplayVoucherInformation { voucher_details } => { StripeNextAction::DisplayVoucherInformation { voucher_details } } @@ -884,3 +893,15 @@ pub(crate) fn into_stripe_next_action( pub struct StripePaymentRetrieveBody { pub client_secret: Option<String>, } + +//To handle payment types that have empty payment method data +fn get_pmd_based_on_payment_method_type( + payment_method_type: Option<api_enums::PaymentMethodType>, +) -> Option<payments::PaymentMethodData> { + match payment_method_type { + Some(api_enums::PaymentMethodType::UpiIntent) => Some(payments::PaymentMethodData::Upi( + payments::UpiData::UpiIntent(payments::UpiIntentData {}), + )), + _ => None, + } +} diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index bbcafb65e9f..9a1cf58f11b 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -382,6 +382,9 @@ pub enum StripeNextAction { display_to_timestamp: Option<i64>, qr_code_url: Option<url::Url>, }, + FetchQrCodeInformation { + qr_code_fetch_url: url::Url, + }, DisplayVoucherInformation { voucher_details: payments::VoucherNextStepData, }, @@ -424,6 +427,9 @@ pub(crate) fn into_stripe_next_action( display_to_timestamp, qr_code_url, }, + payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => { + StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url } + } payments::NextActionData::DisplayVoucherInformation { voucher_details } => { StripeNextAction::DisplayVoucherInformation { voucher_details } } diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index e2effb2e325..1a63dc50c9e 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -214,7 +214,8 @@ impl ConnectorValidation for Adyen { | PaymentMethodType::SamsungPay | PaymentMethodType::Evoucher | PaymentMethodType::Cashapp - | PaymentMethodType::UpiCollect => { + | PaymentMethodType::UpiCollect + | PaymentMethodType::UpiIntent => { capture_method_not_supported!(connector, capture_method, payment_method_type) } }, diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index 5daa33ab944..b36792e90ca 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -1,7 +1,8 @@ use std::collections::HashMap; use api_models::enums::PaymentMethod; -use common_utils::errors::CustomResult; +use common_utils::{errors::CustomResult, ext_traits::Encode}; +use error_stack::ResultExt; use masking::{Secret, SwitchStrategy}; use serde::{Deserialize, Serialize}; @@ -84,6 +85,13 @@ pub struct PayerInfo { token_id: Secret<String>, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum PreferredCheckoutMethod { + Vpa, + Qr, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct IatapayPaymentsRequest { @@ -95,7 +103,9 @@ pub struct IatapayPaymentsRequest { locale: String, redirect_urls: RedirectUrls, notification_url: String, + #[serde(skip_serializing_if = "Option::is_none")] payer_info: Option<PayerInfo>, + preferred_checkout_method: Option<PreferredCheckoutMethod>, } impl @@ -136,24 +146,31 @@ impl | PaymentMethod::GiftCard => item.router_data.get_billing_country()?.to_string(), }; let return_url = item.router_data.get_return_url()?; - let payer_info = match item.router_data.request.payment_method_data.clone() { - domain::PaymentMethodData::Upi(upi_data) => upi_data.vpa_id.map(|id| PayerInfo { - token_id: id.switch_strategy(), - }), - domain::PaymentMethodData::Card(_) - | domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => None, - }; + let (payer_info, preferred_checkout_method) = + match item.router_data.request.payment_method_data.clone() { + domain::PaymentMethodData::Upi(upi_type) => match upi_type { + domain::UpiData::UpiCollect(upi_data) => ( + upi_data.vpa_id.map(|id| PayerInfo { + token_id: id.switch_strategy(), + }), + Some(PreferredCheckoutMethod::Vpa), + ), + domain::UpiData::UpiIntent(_) => (None, Some(PreferredCheckoutMethod::Qr)), + }, + domain::PaymentMethodData::Card(_) + | domain::PaymentMethodData::CardRedirect(_) + | domain::PaymentMethodData::Wallet(_) + | domain::PaymentMethodData::PayLater(_) + | domain::PaymentMethodData::BankRedirect(_) + | domain::PaymentMethodData::BankDebit(_) + | domain::PaymentMethodData::BankTransfer(_) + | domain::PaymentMethodData::Crypto(_) + | domain::PaymentMethodData::MandatePayment + | domain::PaymentMethodData::Reward + | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::CardToken(_) => (None, None), + }; let payload = Self { merchant_id: IatapayAuthType::try_from(&item.router_data.connector_auth_type)? .merchant_id, @@ -165,6 +182,7 @@ impl redirect_urls: get_redirect_url(return_url), payer_info, notification_url: item.router_data.request.get_webhook_url()?, + preferred_checkout_method, }; Ok(payload) } @@ -291,8 +309,46 @@ fn get_iatpay_response( }; let connector_response_reference_id = response.merchant_payment_id.or(response.iata_payment_id); - let payment_response_data = response.checkout_methods.map_or( - types::PaymentsResponseData::TransactionResponse { + let payment_response_data = match response.checkout_methods { + Some(checkout_methods) => { + let (connector_metadata, redirection_data) = + match checkout_methods.redirect.redirect_url.ends_with("qr") { + true => { + let qr_code_info = api_models::payments::FetchQrCodeInformation { + qr_code_fetch_url: url::Url::parse( + &checkout_methods.redirect.redirect_url, + ) + .change_context(errors::ConnectorError::ResponseHandlingFailed)?, + }; + ( + Some(qr_code_info.encode_to_value()) + .transpose() + .change_context(errors::ConnectorError::ResponseHandlingFailed)?, + None, + ) + } + false => ( + None, + Some(services::RedirectForm::Form { + endpoint: checkout_methods.redirect.redirect_url, + method: services::Method::Get, + form_fields, + }), + ), + }; + + types::PaymentsResponseData::TransactionResponse { + resource_id: id, + redirection_data, + mandate_reference: None, + connector_metadata, + network_txn_id: None, + connector_response_reference_id: connector_response_reference_id.clone(), + incremental_authorization_allowed: None, + charge_id: None, + } + } + None => types::PaymentsResponseData::TransactionResponse { resource_id: id.clone(), redirection_data: None, mandate_reference: None, @@ -302,21 +358,8 @@ fn get_iatpay_response( incremental_authorization_allowed: None, charge_id: None, }, - |checkout_methods| types::PaymentsResponseData::TransactionResponse { - resource_id: id, - redirection_data: Some(services::RedirectForm::Form { - endpoint: checkout_methods.redirect.redirect_url, - method: services::Method::Get, - form_fields, - }), - mandate_reference: None, - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: connector_response_reference_id.clone(), - incremental_authorization_allowed: None, - charge_id: None, - }, - ); + }; + Ok((status, error, payment_response_data)) } diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 5c174c69e3b..48b6616a64e 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -398,6 +398,7 @@ impl | common_enums::PaymentMethodType::Trustly | common_enums::PaymentMethodType::Twint | common_enums::PaymentMethodType::UpiCollect + | common_enums::PaymentMethodType::UpiIntent | common_enums::PaymentMethodType::Venmo | common_enums::PaymentMethodType::Vipps | common_enums::PaymentMethodType::Walley diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 55b0d7f4675..83bca39626f 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -675,6 +675,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { | enums::PaymentMethodType::Paypal | enums::PaymentMethodType::Pix | enums::PaymentMethodType::UpiCollect + | enums::PaymentMethodType::UpiIntent | enums::PaymentMethodType::Cashapp | enums::PaymentMethodType::Oxxo => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index a39f0deb3ca..db99ff590cd 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1009,6 +1009,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { api_models::payments::NextActionData::DisplayBankTransferInformation { .. } => None, api_models::payments::NextActionData::ThirdPartySdkSessionToken { .. } => None, api_models::payments::NextActionData::QrCodeInformation{..} => None, + api_models::payments::NextActionData::FetchQrCodeInformation{..} => None, api_models::payments::NextActionData::DisplayVoucherInformation{ .. } => None, api_models::payments::NextActionData::WaitScreenInformation{..} => None, api_models::payments::NextActionData::ThreeDsInvoke{..} => None, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 973ca4b2266..6e3f6a9bf6e 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2338,7 +2338,7 @@ pub fn validate_payment_method_type_against_payment_method( ), api_enums::PaymentMethod::Upi => matches!( payment_method_type, - api_enums::PaymentMethodType::UpiCollect + api_enums::PaymentMethodType::UpiCollect | api_enums::PaymentMethodType::UpiIntent ), api_enums::PaymentMethod::Voucher => matches!( payment_method_type, @@ -4252,9 +4252,9 @@ pub fn get_key_params_for_surcharge_details( )), api_models::payments::PaymentMethodData::MandatePayment => None, api_models::payments::PaymentMethodData::Reward => None, - api_models::payments::PaymentMethodData::Upi(_) => Some(( + api_models::payments::PaymentMethodData::Upi(upi_data) => Some(( common_enums::PaymentMethod::Upi, - common_enums::PaymentMethodType::UpiCollect, + upi_data.get_payment_method_type(), None, )), api_models::payments::PaymentMethodData::Voucher(voucher) => Some(( diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7f6b0cc1f61..8f6af2f89bc 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -541,6 +541,9 @@ where let papal_sdk_next_action = paypal_sdk_next_steps_check(payment_attempt.clone())?; + let next_action_containing_fetch_qr_code_url = + fetch_qr_code_url_next_steps_check(payment_attempt.clone())?; + let next_action_containing_wait_screen = wait_screen_next_steps_check(payment_attempt.clone())?; @@ -550,6 +553,7 @@ where || next_action_containing_qr_code_url.is_some() || next_action_containing_wait_screen.is_some() || papal_sdk_next_action.is_some() + || next_action_containing_fetch_qr_code_url.is_some() || payment_data.authentication.is_some() { next_action_response = bank_transfer_next_steps @@ -566,6 +570,11 @@ where .or(next_action_containing_qr_code_url.map(|qr_code_data| { api_models::payments::NextActionData::foreign_from(qr_code_data) })) + .or(next_action_containing_fetch_qr_code_url.map(|fetch_qr_code_data| { + api_models::payments::NextActionData::FetchQrCodeInformation { + qr_code_fetch_url: fetch_qr_code_data.qr_code_fetch_url + } + })) .or(papal_sdk_next_action.map(|paypal_next_action_data| { api_models::payments::NextActionData::InvokeSdkClient{ next_action_data: paypal_next_action_data @@ -899,6 +908,18 @@ pub fn paypal_sdk_next_steps_check( Ok(paypal_next_steps) } +pub fn fetch_qr_code_url_next_steps_check( + payment_attempt: storage::PaymentAttempt, +) -> RouterResult<Option<api_models::payments::FetchQrCodeInformation>> { + let qr_code_steps: Option<Result<api_models::payments::FetchQrCodeInformation, _>> = + payment_attempt + .connector_metadata + .map(|metadata| metadata.parse_value("FetchQrCodeInformation")); + + let qr_code_fetch_url = qr_code_steps.transpose().ok().flatten(); + Ok(qr_code_fetch_url) +} + pub fn wait_screen_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::WaitScreenInstructions>> { @@ -1108,8 +1129,8 @@ impl ForeignFrom<api_models::payments::QrCodeInformation> for api_models::paymen display_to_timestamp, } => Self::QrCodeInformation { qr_code_url: Some(qr_code_url), - display_to_timestamp, image_data_url: None, + display_to_timestamp, }, } } diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs index 7b1f3365490..51d3210a70f 100644 --- a/crates/router/src/types/domain/payments.rs +++ b/crates/router/src/types/domain/payments.rs @@ -5,6 +5,6 @@ pub use hyperswitch_domain_models::payment_method_data::{ GooglePayPaymentMethodInfo, GooglePayRedirectData, GooglePayThirdPartySdkData, GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData, KakaoPayRedirection, MbWayRedirection, PayLaterData, PaymentMethodData, SamsungPayWalletData, - SepaAndBacsBillingDetails, SwishQrData, TouchNGoRedirection, VoucherData, WalletData, - WeChatPayQr, + SepaAndBacsBillingDetails, SwishQrData, TouchNGoRedirection, UpiCollectData, UpiData, + UpiIntentData, VoucherData, WalletData, WeChatPayQr, }; diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index da8e8c621b7..59ec42abfd2 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -461,7 +461,9 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { | api_enums::PaymentMethodType::Trustly | api_enums::PaymentMethodType::Bizum | api_enums::PaymentMethodType::Interac => Self::BankRedirect, - api_enums::PaymentMethodType::UpiCollect => Self::Upi, + api_enums::PaymentMethodType::UpiCollect | api_enums::PaymentMethodType::UpiIntent => { + Self::Upi + } api_enums::PaymentMethodType::CryptoCurrency => Self::Crypto, api_enums::PaymentMethodType::Ach | api_enums::PaymentMethodType::Sepa diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index b87b516de28..30bd356cd45 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -11757,6 +11757,25 @@ } } }, + { + "type": "object", + "description": "Contains url to fetch Qr code data", + "required": [ + "qr_code_fetch_url", + "type" + ], + "properties": { + "qr_code_fetch_url": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "fetch_qr_code_information" + ] + } + } + }, { "type": "object", "description": "Contains the download url and the reference number for transaction", @@ -13529,6 +13548,7 @@ "trustly", "twint", "upi_collect", + "upi_intent", "vipps", "venmo", "walley", @@ -18692,7 +18712,7 @@ }, "additionalProperties": false }, - "UpiData": { + "UpiCollectData": { "type": "object", "properties": { "vpa_id": { @@ -18702,6 +18722,35 @@ } } }, + "UpiData": { + "oneOf": [ + { + "type": "object", + "required": [ + "upi_collect" + ], + "properties": { + "upi_collect": { + "$ref": "#/components/schemas/UpiCollectData" + } + } + }, + { + "type": "object", + "required": [ + "upi_intent" + ], + "properties": { + "upi_intent": { + "$ref": "#/components/schemas/UpiIntentData" + } + } + } + ] + }, + "UpiIntentData": { + "type": "object" + }, "ValueType": { "oneOf": [ {
2024-05-22T10:09:28Z
## Description <!-- Describe your changes in detail --> This PR introduces a new payment_method_type: `upi_intent` and a new payment_method_data: `upi_qr: {}` along with iatapay qr code implementation. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> _Note:Test through stripe compatibility layer_ 1. Create a upi qr payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ZLiIlOCsh5GUTiRJCCSc6lOIXpo0tTGuROyxvZokpKSIl5Lh5mCYwBB9IZV3Jno2' \ --data-raw '{ "amount": 5000, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 5000, "customer_id": "IatapayCustomer", "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": "upi", "payment_method_type": "upi_intent", "payment_method_data": { "upi": { "upi_intent": { } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "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" } }' ``` Response ``` { "payment_id": "pay_ZBLXkfFi0wcdBPrQkKPL", "merchant_id": "merchant_1716310637", "status": "requires_customer_action", "amount": 5000, "net_amount": 5000, "amount_capturable": 5000, "amount_received": null, "connector": "iatapay", "client_secret": "pay_ZBLXkfFi0wcdBPrQkKPL_secret_YYAnlcRyF7ZX3r82WtjL", "created": "2024-05-22T10:04:05.468Z", "currency": "INR", "customer_id": "IatapayCustomer", "customer": { "id": "IatapayCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "upi", "payment_method_data": { "upi": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "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": "8056594427", "country_code": "+91" }, "email": null }, "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": "JS", "next_action": { "type": "fetch_qr_code_information", "qr_code_fetch_url": "https://sandbox.iata-pay.iata.org/api/v1/payments/PJHE6F45O1D7M/checkout/api/qr" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "upi_intent", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "IatapayCustomer", "created_at": 1716372245, "expires": 1716375845, "secret": "epk_41f95816c9844c2e9c8672ec5bc91d65" }, "manual_retry_allowed": null, "connector_transaction_id": "P1D74RYCPET6J", "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_ZBLXkfFi0wcdBPrQkKPL_1", "payment_link": null, "profile_id": "pro_aqLkyMdeFcYrp3v3yPd8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nLDpyk2OF9mrlivQTJnS", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-22T10:19:05.468Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-22T10:04:08.642Z", "frm_metadata": null } ``` 2. Create a upi payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:""' \ --data-raw '{ "amount": 5000, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 5000, "customer_id": "IatapayCustomer", "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": "upi", "payment_method_type": "upi_collect", "payment_method_data": { "upi": { "upi_collect": { "vpa_id": "successtest@ita" } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "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" } }' ``` Response ``` { "payment_id": "pay_VfMfCw7jxtbHNc5xvF4Z", "merchant_id": "merchant_1716310637", "status": "requires_customer_action", "amount": 5000, "net_amount": 5000, "amount_capturable": 5000, "amount_received": null, "connector": "iatapay", "client_secret": "pay_VfMfCw7jxtbHNc5xvF4Z_secret_lMsdWF0m50OBBvxe1fl7", "created": "2024-05-22T09:54:19.813Z", "currency": "INR", "customer_id": "IatapayCustomer", "customer": { "id": "IatapayCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "upi", "payment_method_data": { "upi": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "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": "8056594427", "country_code": "+91" }, "email": null }, "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": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_VfMfCw7jxtbHNc5xvF4Z/merchant_1716310637/pay_VfMfCw7jxtbHNc5xvF4Z_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": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "IatapayCustomer", "created_at": 1716371659, "expires": 1716375259, "secret": "epk_7bb67ee9c3304c8a9458ba6ef2488225" }, "manual_retry_allowed": null, "connector_transaction_id": "P46Y265SXCTXZ", "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_VfMfCw7jxtbHNc5xvF4Z_1", "payment_link": null, "profile_id": "pro_aqLkyMdeFcYrp3v3yPd8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nLDpyk2OF9mrlivQTJnS", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-22T10:09:19.813Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-22T09:54:21.635Z", "frm_metadata": null } ``` Stimulate Terminal status (for Failed - `FAILED`) ``` curl --location --request PUT 'https://sandbox.iata-pay.iata.org/api/v2/payments/P50G9SL4HD0A7/simulate' \ --header 'Content-Type: application/json' \ --header 'Authorization: access_token' \ --data '{ "status": "SETTLED" }' ```
b3d4d13db81143cf663142d8bd8fdf95b0882b3f
_Note:Test through stripe compatibility layer_ 1. Create a upi qr payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ZLiIlOCsh5GUTiRJCCSc6lOIXpo0tTGuROyxvZokpKSIl5Lh5mCYwBB9IZV3Jno2' \ --data-raw '{ "amount": 5000, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 5000, "customer_id": "IatapayCustomer", "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": "upi", "payment_method_type": "upi_intent", "payment_method_data": { "upi": { "upi_intent": { } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "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" } }' ``` Response ``` { "payment_id": "pay_ZBLXkfFi0wcdBPrQkKPL", "merchant_id": "merchant_1716310637", "status": "requires_customer_action", "amount": 5000, "net_amount": 5000, "amount_capturable": 5000, "amount_received": null, "connector": "iatapay", "client_secret": "pay_ZBLXkfFi0wcdBPrQkKPL_secret_YYAnlcRyF7ZX3r82WtjL", "created": "2024-05-22T10:04:05.468Z", "currency": "INR", "customer_id": "IatapayCustomer", "customer": { "id": "IatapayCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "upi", "payment_method_data": { "upi": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "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": "8056594427", "country_code": "+91" }, "email": null }, "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": "JS", "next_action": { "type": "fetch_qr_code_information", "qr_code_fetch_url": "https://sandbox.iata-pay.iata.org/api/v1/payments/PJHE6F45O1D7M/checkout/api/qr" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "upi_intent", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "IatapayCustomer", "created_at": 1716372245, "expires": 1716375845, "secret": "epk_41f95816c9844c2e9c8672ec5bc91d65" }, "manual_retry_allowed": null, "connector_transaction_id": "P1D74RYCPET6J", "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_ZBLXkfFi0wcdBPrQkKPL_1", "payment_link": null, "profile_id": "pro_aqLkyMdeFcYrp3v3yPd8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nLDpyk2OF9mrlivQTJnS", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-22T10:19:05.468Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-22T10:04:08.642Z", "frm_metadata": null } ``` 2. Create a upi payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:""' \ --data-raw '{ "amount": 5000, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 5000, "customer_id": "IatapayCustomer", "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": "upi", "payment_method_type": "upi_collect", "payment_method_data": { "upi": { "upi_collect": { "vpa_id": "successtest@ita" } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "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" } }' ``` Response ``` { "payment_id": "pay_VfMfCw7jxtbHNc5xvF4Z", "merchant_id": "merchant_1716310637", "status": "requires_customer_action", "amount": 5000, "net_amount": 5000, "amount_capturable": 5000, "amount_received": null, "connector": "iatapay", "client_secret": "pay_VfMfCw7jxtbHNc5xvF4Z_secret_lMsdWF0m50OBBvxe1fl7", "created": "2024-05-22T09:54:19.813Z", "currency": "INR", "customer_id": "IatapayCustomer", "customer": { "id": "IatapayCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "upi", "payment_method_data": { "upi": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "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": "8056594427", "country_code": "+91" }, "email": null }, "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": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_VfMfCw7jxtbHNc5xvF4Z/merchant_1716310637/pay_VfMfCw7jxtbHNc5xvF4Z_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": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "IatapayCustomer", "created_at": 1716371659, "expires": 1716375259, "secret": "epk_7bb67ee9c3304c8a9458ba6ef2488225" }, "manual_retry_allowed": null, "connector_transaction_id": "P46Y265SXCTXZ", "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_VfMfCw7jxtbHNc5xvF4Z_1", "payment_link": null, "profile_id": "pro_aqLkyMdeFcYrp3v3yPd8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nLDpyk2OF9mrlivQTJnS", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-22T10:09:19.813Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-22T09:54:21.635Z", "frm_metadata": null } ``` Stimulate Terminal status (for Failed - `FAILED`) ``` curl --location --request PUT 'https://sandbox.iata-pay.iata.org/api/v2/payments/P50G9SL4HD0A7/simulate' \ --header 'Content-Type: application/json' \ --header 'Authorization: access_token' \ --data '{ "status": "SETTLED" }' ```
[ "crates/api_models/src/payments.rs", "crates/common_enums/src/enums.rs", "crates/common_enums/src/transformers.rs", "crates/euclid/src/frontend/dir/enums.rs", "crates/euclid/src/frontend/dir/lowering.rs", "crates/euclid/src/frontend/dir/transformers.rs", "crates/hyperswitch_domain_models/src/payment_met...
juspay/hyperswitch
juspay__hyperswitch-4722
Bug: Enable auto-retries for apple pay Currently for apple pay pre-routing is done before the session call and a connector is decided based on the routing logic. Because of this we are not able retry the failed apple pay payments. As the certificates use in the simplified flows are same across the connectors the failed apple pay payment can be retired with the other connectors with apple pay simplified flow configured. In order to achieve this we need to pass a list of apple pay simplified flow configured connectors and in pre routing.
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 175400c54bf..9b2082cf31f 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3170,6 +3170,28 @@ where { routing_data.business_sub_label = choice.sub_label.clone(); } + + if payment_data.payment_attempt.payment_method_type + == Some(storage_enums::PaymentMethodType::ApplePay) + { + let retryable_connector_data = helpers::get_apple_pay_retryable_connectors( + state, + merchant_account, + payment_data, + key_store, + connector_data.clone(), + #[cfg(feature = "connector_choice_mca_id")] + choice.merchant_connector_id.clone().as_ref(), + #[cfg(not(feature = "connector_choice_mca_id"))] + None, + ) + .await?; + + if let Some(connector_data_list) = retryable_connector_data { + return Ok(ConnectorCallType::Retryable(connector_data_list)); + } + } + return Ok(ConnectorCallType::PreDetermined(connector_data)); } } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 2eb0c921bbf..76ff96c7021 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -122,36 +122,6 @@ fn is_dynamic_fields_required( .unwrap_or(false) } -fn get_applepay_metadata( - connector_metadata: Option<common_utils::pii::SecretSerdeValue>, -) -> RouterResult<payment_types::ApplepaySessionTokenMetadata> { - connector_metadata - .clone() - .parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>( - "ApplepayCombinedSessionTokenData", - ) - .map(|combined_metadata| { - api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( - combined_metadata.apple_pay_combined, - ) - }) - .or_else(|_| { - connector_metadata - .parse_value::<api_models::payments::ApplepaySessionTokenData>( - "ApplepaySessionTokenData", - ) - .map(|old_metadata| { - api_models::payments::ApplepaySessionTokenMetadata::ApplePay( - old_metadata.apple_pay, - ) - }) - }) - .change_context(errors::ApiErrorResponse::InvalidDataFormat { - field_name: "connector_metadata".to_string(), - expected_format: "applepay_metadata_format".to_string(), - }) -} - fn build_apple_pay_session_request( state: &routes::AppState, request: payment_types::ApplepaySessionRequest, @@ -196,7 +166,8 @@ async fn create_applepay_session_token( ) } else { // Get the apple pay metadata - let apple_pay_metadata = get_applepay_metadata(router_data.connector_meta_data.clone())?; + let apple_pay_metadata = + helpers::get_applepay_metadata(router_data.connector_meta_data.clone())?; // Get payment request data , apple pay session request and merchant keys let ( @@ -213,6 +184,8 @@ async fn create_applepay_session_token( payment_request_data, session_token_data, } => { + logger::info!("Apple pay simplified flow"); + let merchant_identifier = state .conf .applepay_merchant_configs @@ -254,6 +227,8 @@ async fn create_applepay_session_token( payment_request_data, session_token_data, } => { + logger::info!("Apple pay manual flow"); + let apple_pay_session_request = get_session_request_for_manual_apple_pay(session_token_data.clone()); @@ -269,6 +244,8 @@ async fn create_applepay_session_token( } }, payment_types::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => { + logger::info!("Apple pay manual flow"); + let apple_pay_session_request = get_session_request_for_manual_apple_pay( apple_pay_metadata.session_token_data.clone(), ); diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index eb3dca11060..06c8c7f2c94 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3888,6 +3888,122 @@ pub fn validate_customer_access( Ok(()) } +pub fn is_apple_pay_simplified_flow( + connector_metadata: Option<pii::SecretSerdeValue>, +) -> CustomResult<bool, errors::ApiErrorResponse> { + let apple_pay_metadata = get_applepay_metadata(connector_metadata)?; + + Ok(match apple_pay_metadata { + api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( + apple_pay_combined_metadata, + ) => match apple_pay_combined_metadata { + api_models::payments::ApplePayCombinedMetadata::Simplified { .. } => true, + api_models::payments::ApplePayCombinedMetadata::Manual { .. } => false, + }, + api_models::payments::ApplepaySessionTokenMetadata::ApplePay(_) => false, + }) +} + +pub fn get_applepay_metadata( + connector_metadata: Option<pii::SecretSerdeValue>, +) -> RouterResult<api_models::payments::ApplepaySessionTokenMetadata> { + connector_metadata + .clone() + .parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>( + "ApplepayCombinedSessionTokenData", + ) + .map(|combined_metadata| { + api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( + combined_metadata.apple_pay_combined, + ) + }) + .or_else(|_| { + connector_metadata + .parse_value::<api_models::payments::ApplepaySessionTokenData>( + "ApplepaySessionTokenData", + ) + .map(|old_metadata| { + api_models::payments::ApplepaySessionTokenMetadata::ApplePay( + old_metadata.apple_pay, + ) + }) + }) + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "connector_metadata".to_string(), + expected_format: "applepay_metadata_format".to_string(), + }) +} + +pub async fn get_apple_pay_retryable_connectors<F>( + state: AppState, + merchant_account: &domain::MerchantAccount, + payment_data: &mut PaymentData<F>, + key_store: &domain::MerchantKeyStore, + decided_connector_data: api::ConnectorData, + merchant_connector_id: Option<&String>, +) -> CustomResult<Option<Vec<api::ConnectorData>>, errors::ApiErrorResponse> +where + F: Send + Clone, +{ + let profile_id = &payment_data + .payment_intent + .profile_id + .clone() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::MissingRequiredField { + field_name: "profile_id", + })?; + + let merchant_connector_account = get_merchant_connector_account( + &state, + merchant_account.merchant_id.as_str(), + payment_data.creds_identifier.to_owned(), + key_store, + profile_id, // need to fix this + &decided_connector_data.connector_name.to_string(), + merchant_connector_id, + ) + .await? + .get_metadata(); + + let connector_data_list = if is_apple_pay_simplified_flow(merchant_connector_account)? { + let merchant_connector_account_list = state + .store + .find_merchant_connector_account_by_merchant_id_and_disabled_list( + merchant_account.merchant_id.as_str(), + true, + key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; + + let mut connector_data_list = vec![decided_connector_data.clone()]; + + for merchant_connector_account in merchant_connector_account_list { + if is_apple_pay_simplified_flow(merchant_connector_account.metadata)? { + let connector_data = api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &merchant_connector_account.connector_name.to_string(), + api::GetToken::Connector, + Some(merchant_connector_account.merchant_connector_id), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received")?; + + if !connector_data_list.iter().any(|connector_details| { + connector_details.merchant_connector_id == connector_data.merchant_connector_id + }) { + connector_data_list.push(connector_data) + } + } + } + Some(connector_data_list) + } else { + None + }; + Ok(connector_data_list) +} + #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct ApplePayData { version: masking::Secret<String>, @@ -4040,6 +4156,8 @@ impl ApplePayData { &self, symmetric_key: &[u8], ) -> CustomResult<String, errors::ApplePayDecryptionError> { + logger::info!("Decrypt apple pay token"); + let data = BASE64_ENGINE .decode(self.data.peek().as_bytes()) .change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?;
2024-05-21T15:54:52Z
## Description <!-- Describe your changes in detail --> Currently for apple pay pre-routing is done before the session call and a connector is decided based on the routing logic. Because of this we are not able retry the failed apple pay payments. As the certificates use in the simplified flows are same across the connectors the failed apple pay payment can be retired with the other connectors with apple pay simplified flow configured. In order to achieve this we need to pass a list of apple pay simplified flow configured connectors and in pre routing. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a merchant account -> Enable gcm for the `merchant_id` ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "should_call_gsm_{merchant_id}", "value": "true" }' ``` -> Set the maximum retries count ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "max_auto_retries_enabled_{merchant_id}", "value": "1" }' ``` -> Create MCA for stripe and cybersource with apple pay simplified flow metadata for simplified flow ``` "metadata": { "apple_pay_combined": { "simplified": { "session_token_data": { "initiative_context": "sdk-test-app.netlify.app", "merchant_business_country": "US" }, "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": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ] } } } ``` -> Do a apple pay payment create with confirm false ``` { "amount": 650, "currency": "USD", "confirm": false, "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", "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" } } } ``` <img width="1007" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67deb74e-e0dd-4af3-b5d9-7298d65c3e01"> -> Do payment method list for merchant ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_V1VBfr3VW6MVXaFw01sT_secret_6bByPi9DrnPk0uv6vYJj' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_cc7a8a8132a840338323ac8f7f6860d0' ``` <img width="1059" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/38f97f9d-ff51-41dc-9a06-20137f2ead1a"> -> Confirm the above create payment with `payment_id` and payment_data ``` curl --location 'http://localhost:8080/payments/pay_V1VBfr3VW6MVXaFw01sT/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api_key' \ --data '{ "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSTBNRFV5TVRBM016TXlORm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlEa29VdTlwZ01JUHR2R0VEZi9tSXk3LzNjSTg2b3U5eTJaZkV6RkhuRFN0TUFvR0NDcUdTTTQ5QkFNQ0JFWXdSQUlnTWdkSG9rZHNWQndya3RYRzd1VmowMm9QVVNsQllaWGVPeXJyd3RsQk5MUUNJRDdzZnZPaThZcjVWNkVyNjFqU05sKzR3ZDhpR050YUxEdFRMZjNBQ0VhNkFBQUFBQUFBIiwiaGVhZGVyIjp7InB1YmxpY0tleUhhc2giOiJ4MnFmMTFaemRXbnFCZnc0U0NyOWxIYzZRc1JQOEp6Z2xrZnU5RTVkWUpnPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } }' ``` <img width="1045" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/1b5c8cb4-43bf-42ea-a82f-9c6db940950b"> -> Apple pay retry connectors <img width="1174" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/f3612f01-ee02-4687-b42c-af70eaf3e521"> -> Payment retrieve have two payment attempts ``` curl --location 'http://localhost:8080/payments/pay_V1VBfr3VW6MVXaFw01sT?expand_attempts=true' \ --header 'Accept: application/json' \ --header 'api-key: api_key' ``` <img width="720" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/705f2a0e-c057-47e1-8edf-e63139975a42">
8afeda54fc5e3f3d510c48c81c222387e9cacc0e
-> Create a merchant account -> Enable gcm for the `merchant_id` ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "should_call_gsm_{merchant_id}", "value": "true" }' ``` -> Set the maximum retries count ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "max_auto_retries_enabled_{merchant_id}", "value": "1" }' ``` -> Create MCA for stripe and cybersource with apple pay simplified flow metadata for simplified flow ``` "metadata": { "apple_pay_combined": { "simplified": { "session_token_data": { "initiative_context": "sdk-test-app.netlify.app", "merchant_business_country": "US" }, "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": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ] } } } ``` -> Do a apple pay payment create with confirm false ``` { "amount": 650, "currency": "USD", "confirm": false, "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", "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" } } } ``` <img width="1007" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67deb74e-e0dd-4af3-b5d9-7298d65c3e01"> -> Do payment method list for merchant ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_V1VBfr3VW6MVXaFw01sT_secret_6bByPi9DrnPk0uv6vYJj' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_cc7a8a8132a840338323ac8f7f6860d0' ``` <img width="1059" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/38f97f9d-ff51-41dc-9a06-20137f2ead1a"> -> Confirm the above create payment with `payment_id` and payment_data ``` curl --location 'http://localhost:8080/payments/pay_V1VBfr3VW6MVXaFw01sT/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api_key' \ --data '{ "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSTBNRFV5TVRBM016TXlORm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlEa29VdTlwZ01JUHR2R0VEZi9tSXk3LzNjSTg2b3U5eTJaZkV6RkhuRFN0TUFvR0NDcUdTTTQ5QkFNQ0JFWXdSQUlnTWdkSG9rZHNWQndya3RYRzd1VmowMm9QVVNsQllaWGVPeXJyd3RsQk5MUUNJRDdzZnZPaThZcjVWNkVyNjFqU05sKzR3ZDhpR050YUxEdFRMZjNBQ0VhNkFBQUFBQUFBIiwiaGVhZGVyIjp7InB1YmxpY0tleUhhc2giOiJ4MnFmMTFaemRXbnFCZnc0U0NyOWxIYzZRc1JQOEp6Z2xrZnU5RTVkWUpnPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } }' ``` <img width="1045" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/1b5c8cb4-43bf-42ea-a82f-9c6db940950b"> -> Apple pay retry connectors <img width="1174" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/f3612f01-ee02-4687-b42c-af70eaf3e521"> -> Payment retrieve have two payment attempts ``` curl --location 'http://localhost:8080/payments/pay_V1VBfr3VW6MVXaFw01sT?expand_attempts=true' \ --header 'Accept: application/json' \ --header 'api-key: api_key' ``` <img width="720" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/705f2a0e-c057-47e1-8edf-e63139975a42">
[ "crates/router/src/core/payments.rs", "crates/router/src/core/payments/flows/session_flow.rs", "crates/router/src/core/payments/helpers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4719
Bug: [ENHANCEMENT] Make `redis_interface` crate agnostic of `router_env` dependencies
diff --git a/Cargo.lock b/Cargo.lock index d5dc4e2ee9f..e6278079b20 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5365,11 +5365,11 @@ dependencies = [ "error-stack", "fred", "futures 0.3.30", - "router_env", "serde", "thiserror", "tokio 1.37.0", "tokio-stream", + "tracing", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 82687a32ba6..fc2095275d3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,9 @@ package.edition = "2021" package.rust-version = "1.70" package.license = "Apache-2.0" +[workspace.dependencies] +tracing = { version = "0.1.40" } + [profile.release] strip = true lto = true diff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.toml index 1fb74be79d9..d55ff86bcea 100644 --- a/crates/redis_interface/Cargo.toml +++ b/crates/redis_interface/Cargo.toml @@ -15,10 +15,10 @@ serde = { version = "1.0.197", features = ["derive"] } thiserror = "1.0.58" tokio = "1.37.0" tokio-stream = {version = "0.1.15", features = ["sync"]} +tracing = { workspace = true } # First party crates common_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext"] } -router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } [dev-dependencies] tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] } diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index 46e3a35fd33..504820822c0 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -23,7 +23,7 @@ use fred::{ }, }; use futures::StreamExt; -use router_env::{instrument, logger, tracing}; +use tracing::instrument; use crate::{ errors, @@ -379,7 +379,7 @@ impl super::RedisConnectionPool { Some(futures::stream::iter(v)) } Err(err) => { - logger::error!(?err); + tracing::error!(?err); None } } diff --git a/crates/redis_interface/src/lib.rs b/crates/redis_interface/src/lib.rs index 0ab1ea394c9..df74d728331 100644 --- a/crates/redis_interface/src/lib.rs +++ b/crates/redis_interface/src/lib.rs @@ -26,7 +26,6 @@ use common_utils::errors::CustomResult; use error_stack::ResultExt; pub use fred::interfaces::PubsubInterface; use fred::{interfaces::ClientLike, prelude::EventInterface}; -use router_env::logger; pub use self::types::*; @@ -189,10 +188,10 @@ impl RedisConnectionPool { let mut error_rx = futures::stream::select_all(error_rxs); loop { if let Some(Ok(error)) = error_rx.next().await { - logger::error!(?error, "Redis protocol or connection error"); + tracing::error!(?error, "Redis protocol or connection error"); if self.pool.state() == fred::types::ClientState::Disconnected { if tx.send(()).is_err() { - logger::error!("The redis shutdown signal sender failed to signal"); + tracing::error!("The redis shutdown signal sender failed to signal"); } self.is_redis_available .store(false, atomic::Ordering::SeqCst); @@ -205,7 +204,7 @@ 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"); + tracing::warn!(redis_server =?server.host, "Redis server is unresponsive"); Ok(()) }) }); diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml index 3b95d5f22fd..b9b1184fedf 100644 --- a/crates/router_env/Cargo.toml +++ b/crates/router_env/Cargo.toml @@ -22,7 +22,7 @@ serde_path_to_error = "0.1.16" strum = { version = "0.26.2", features = ["derive"] } time = { version = "0.3.35", default-features = false, features = ["formatting"] } tokio = { version = "1.37.0" } -tracing = { version = "0.1.40" } +tracing = { workspace = true } tracing-actix-web = { version = "0.7.10", features = ["opentelemetry_0_19", "uuid_v7"], optional = true } tracing-appender = { version = "0.2.3" } tracing-attributes = "0.1.27"
2024-05-21T12:10:21Z
…ndency for redis_interface ## Description This PR removes `router_env` as a dependency of `redis_interface` crate. To accomplish this we declare `tracing` as a workspace dependency and use that individually in `redis_interface` and `router_env`. <!-- 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 This is done to make `redis_interface` more self-sufficient and improve its usage as a autonomous dependency. <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? This is dependency relocation, no domain logic or framework code was changed <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
2e79ee0615292182111586fda7655dd9a796ef4f
This is dependency relocation, no domain logic or framework code was changed
[ "Cargo.lock", "Cargo.toml", "crates/redis_interface/Cargo.toml", "crates/redis_interface/src/commands.rs", "crates/redis_interface/src/lib.rs", "crates/router_env/Cargo.toml" ]
juspay/hyperswitch
juspay__hyperswitch-4718
Bug: [BUG] handle empty string updated_by for soft kill kv ### Bug Description some entries for payment attempt is inserted with '' value in db, in which case we are not sure where the data is present ### Expected Behavior handle these cases in the safest way by having a lookup in redis and deciding the storage scheme ### Actual Behavior configured scheme gets picked ### Steps To Reproduce tested in integ, not reproducible in local machine ### 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/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs index 9c429058b70..c39e67eb841 100644 --- a/crates/storage_impl/src/redis/kv_store.rs +++ b/crates/storage_impl/src/redis/kv_store.rs @@ -249,7 +249,9 @@ impl<'a> std::fmt::Display for Op<'a> { match self { Op::Insert => f.write_str("insert"), Op::Find => f.write_str("find"), - Op::Update(p_key, _, _) => f.write_str(&format!("update_{}", p_key)), + Op::Update(p_key, _, updated_by) => { + f.write_str(&format!("update_{} for updated_by_{:?}", p_key, updated_by)) + } } } } @@ -273,7 +275,8 @@ where let updated_scheme = match operation { Op::Insert => MerchantStorageScheme::PostgresOnly, Op::Find => MerchantStorageScheme::RedisKv, - Op::Update(partition_key, field, Some("redis_kv")) => { + Op::Update(_, _, Some("postgres_only")) => MerchantStorageScheme::PostgresOnly, + Op::Update(partition_key, field, Some(_updated_by)) => { match kv_wrapper::<D, _, _>(store, KvOperation::<D>::HGet(field), partition_key) .await { @@ -286,11 +289,6 @@ where } Op::Update(_, _, None) => MerchantStorageScheme::PostgresOnly, - Op::Update(_, _, Some("postgres_only")) => MerchantStorageScheme::PostgresOnly, - _ => { - logger::debug!("soft_kill_mode - using default storage scheme"); - storage_scheme - } }; let type_name = std::any::type_name::<D>();
2024-05-21T11:59:24Z
## Description <!-- Describe your changes in detail --> there are some entries created with updated_by as '' for payment_attempt, which is causing decide storage scheme to select the configured scheme which is an issue during soft kill with configured scheme as redis_kv as we want db entities to be processed in db ### 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). --> there are some entries created with updated_by as '' for payment_attempt, which is causing decide storage scheme to select the configured scheme which is an issue during soft kill with configured scheme as redis_kv as we want db entities to be processed in db `select created_at , updated_by from payment_attempt where updated_by = '' order by created_at desc limit 100` ## 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)? -->
2e79ee0615292182111586fda7655dd9a796ef4f
[ "crates/storage_impl/src/redis/kv_store.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4724
Bug: [FEATURE] Add support for external 3ds authentication in cybersource. ### Feature Description Currenctly hyperswitch supports 3ds authenticated payments through cybersource. But we cannot complete 3ds authentication through a separate authentication provider(eg: netcetera). and then do payment authorization through cybersource. ### Possible Implementation This feature is already supported by NMI and Checkout. Similar solution can be used here. ### 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/enums.rs b/crates/api_models/src/enums.rs index 59a85841212..4d5b709bba3 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -244,10 +244,9 @@ impl Connector { | Self::Riskified | Self::Threedsecureio | Self::Netcetera - | Self::Cybersource | Self::Noon | Self::Stripe => false, - Self::Checkout | Self::Nmi => true, + Self::Checkout | Self::Nmi| Self::Cybersource => true, } } } diff --git a/crates/diesel_models/src/authentication.rs b/crates/diesel_models/src/authentication.rs index 9b7c4c96ee0..71a16dcb863 100644 --- a/crates/diesel_models/src/authentication.rs +++ b/crates/diesel_models/src/authentication.rs @@ -42,6 +42,7 @@ pub struct Authentication { pub profile_id: String, pub payment_id: Option<String>, pub merchant_connector_id: String, + pub ds_trans_id: Option<String>, pub directory_server_id: Option<String>, } @@ -87,6 +88,7 @@ pub struct AuthenticationNew { pub profile_id: String, pub payment_id: Option<String>, pub merchant_connector_id: String, + pub ds_trans_id: Option<String>, pub directory_server_id: Option<String>, } @@ -115,6 +117,7 @@ pub enum AuthenticationUpdate { acs_trans_id: Option<String>, acs_signed_content: Option<String>, authentication_status: common_enums::AuthenticationStatus, + ds_trans_id: Option<String>, }, PostAuthenticationUpdate { trans_status: common_enums::TransactionStatus, @@ -162,6 +165,7 @@ pub struct AuthenticationUpdateInternal { pub acs_reference_number: Option<String>, pub acs_trans_id: Option<String>, pub acs_signed_content: Option<String>, + pub ds_trans_id: Option<String>, pub directory_server_id: Option<String>, } @@ -193,6 +197,7 @@ impl Default for AuthenticationUpdateInternal { acs_reference_number: Default::default(), acs_trans_id: Default::default(), acs_signed_content: Default::default(), + ds_trans_id: Default::default(), directory_server_id: Default::default(), } } @@ -226,6 +231,7 @@ impl AuthenticationUpdateInternal { acs_reference_number, acs_trans_id, acs_signed_content, + ds_trans_id, directory_server_id, } = self; Authentication { @@ -258,6 +264,7 @@ impl AuthenticationUpdateInternal { acs_reference_number: acs_reference_number.or(source.acs_reference_number), acs_trans_id: acs_trans_id.or(source.acs_trans_id), acs_signed_content: acs_signed_content.or(source.acs_signed_content), + ds_trans_id: ds_trans_id.or(source.ds_trans_id), directory_server_id: directory_server_id.or(source.directory_server_id), ..source } @@ -336,6 +343,7 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal { acs_trans_id, acs_signed_content, authentication_status, + ds_trans_id, } => Self { cavv: authentication_value, trans_status: Some(trans_status), @@ -346,6 +354,7 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal { acs_trans_id, acs_signed_content, authentication_status: Some(authentication_status), + ds_trans_id, ..Default::default() }, AuthenticationUpdate::PostAuthenticationUpdate { diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index de5b536dcda..6074fdc10b7 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -115,6 +115,8 @@ diesel::table! { payment_id -> Nullable<Varchar>, #[max_length = 128] merchant_connector_id -> Varchar, + #[max_length = 64] + ds_trans_id -> Nullable<Varchar>, #[max_length = 128] directory_server_id -> Nullable<Varchar>, } diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index 56a4ba739c0..c8e68586dad 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -1,7 +1,7 @@ pub mod authentication; pub mod fraud_check; use api_models::payments::RequestSurchargeDetails; -use common_utils::{consts, errors, ext_traits::OptionExt, pii}; +use common_utils::{consts, errors, ext_traits::OptionExt, pii, types as common_types}; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use masking::Secret; @@ -447,7 +447,8 @@ pub struct AuthenticationData { pub eci: Option<String>, pub cavv: String, pub threeds_server_transaction_id: String, - pub message_version: String, + pub message_version: common_types::SemanticVersion, + pub ds_trans_id: Option<String>, } #[derive(Debug, Clone)] diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs index 3d89163b3da..57d579e1a0a 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types.rs @@ -219,6 +219,7 @@ pub enum AuthenticationResponseData { authn_flow_type: AuthNFlowType, authentication_value: Option<String>, trans_status: common_enums::TransactionStatus, + ds_trans_id: Option<String>, }, PostAuthNResponse { trans_status: common_enums::TransactionStatus, diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index c92d75f1de8..10918b7bc6e 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -383,7 +383,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme eci: authentication_data.and_then(|auth| auth.eci.clone()), cryptogram: authentication_data.map(|auth| auth.cavv.clone()), xid: authentication_data.map(|auth| auth.threeds_server_transaction_id.clone()), - version: authentication_data.map(|auth| auth.message_version.clone()), + version: authentication_data.map(|auth| auth.message_version.to_string()), }, enums::AuthenticationType::NoThreeDs => CheckoutThreeDS { enabled: false, diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 43e5660d2b9..3cccb8dcf5c 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -848,6 +848,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P if req.is_three_ds() && req.request.is_card() && req.request.connector_mandate_id().is_none() + && req.request.authentication_data.is_none() { Ok(format!( "{}risk/v1/authentication-setups", @@ -875,6 +876,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P if req.is_three_ds() && req.request.is_card() && req.request.connector_mandate_id().is_none() + && req.request.authentication_data.is_none() { let connector_req = cybersource::CybersourceAuthSetupRequest::try_from(&connector_router_data)?; @@ -915,6 +917,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P if data.is_three_ds() && data.request.is_card() && data.request.connector_mandate_id().is_none() + && data.request.authentication_data.is_none() { let response: cybersource::CybersourceAuthSetupResponse = res .response diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index f1774a0de39..4527ea3950a 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -6,7 +6,7 @@ use api_models::{ }; use base64::Engine; use common_enums::FutureUsage; -use common_utils::{ext_traits::ValueExt, pii}; +use common_utils::{ext_traits::ValueExt, pii, types::SemanticVersion}; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; @@ -261,7 +261,16 @@ pub struct CybersourceConsumerAuthInformation { xid: Option<String>, directory_server_transaction_id: Option<Secret<String>>, specification_version: Option<String>, + /// This field specifies the 3ds version + pa_specification_version: Option<SemanticVersion>, + /// Verification response enrollment status. + /// + /// This field is supported only on Asia, Middle East, and Africa Gateway. + /// + /// For external authentication, this field will always be "Y" + veres_enrolled: Option<String>, } + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MerchantDefinedInformation { @@ -655,6 +664,19 @@ impl } else { (None, None, None) }; + // this logic is for external authenticated card + let commerce_indicator_for_external_authentication = item + .router_data + .request + .authentication_data + .as_ref() + .and_then(|authn_data| { + authn_data + .eci + .clone() + .map(|eci| get_commerce_indicator_for_external_authentication(network, eci)) + }); + Ok(Self { capture: Some(matches!( item.router_data.request.capture_method, @@ -665,11 +687,62 @@ impl action_token_types, authorization_options, capture_options: None, - commerce_indicator, + commerce_indicator: commerce_indicator_for_external_authentication + .unwrap_or(commerce_indicator), }) } } +fn get_commerce_indicator_for_external_authentication( + card_network: Option<String>, + eci: String, +) -> String { + let card_network_lower_case = card_network + .as_ref() + .map(|card_network| card_network.to_lowercase()); + match eci.as_str() { + "00" | "01" | "02" => { + if matches!( + card_network_lower_case.as_deref(), + Some("mastercard") | Some("maestro") + ) { + "spa" + } else { + "internet" + } + } + "05" => match card_network_lower_case.as_deref() { + Some("amex") => "aesk", + Some("discover") => "dipb", + Some("mastercard") => "spa", + Some("visa") => "vbv", + Some("diners") => "pb", + Some("upi") => "up3ds", + _ => "internet", + }, + "06" => match card_network_lower_case.as_deref() { + Some("amex") => "aesk_attempted", + Some("discover") => "dipb_attempted", + Some("mastercard") => "spa", + Some("visa") => "vbv_attempted", + Some("diners") => "pb_attempted", + Some("upi") => "up3ds_attempted", + _ => "internet", + }, + "07" => match card_network_lower_case.as_deref() { + Some("amex") => "internet", + Some("discover") => "internet", + Some("mastercard") => "spa", + Some("visa") => "vbv_failure", + Some("diners") => "internet", + Some("upi") => "up3ds_failure", + _ => "internet", + }, + _ => "vbv_failure", + } + .to_string() +} + impl From<( &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, @@ -852,12 +925,39 @@ impl Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) }); + let consumer_authentication_information = item + .router_data + .request + .authentication_data + .as_ref() + .map(|authn_data| { + let (ucaf_authentication_data, cavv) = + if ccard.card_network == Some(common_enums::CardNetwork::Mastercard) { + (Some(Secret::new(authn_data.cavv.clone())), None) + } else { + (None, Some(authn_data.cavv.clone())) + }; + CybersourceConsumerAuthInformation { + ucaf_collection_indicator: None, + cavv, + ucaf_authentication_data, + xid: Some(authn_data.threeds_server_transaction_id.clone()), + directory_server_transaction_id: authn_data + .ds_trans_id + .clone() + .map(Secret::new), + specification_version: None, + pa_specification_version: Some(authn_data.message_version.clone()), + veres_enrolled: Some("Y".to_string()), + } + }); + Ok(Self { processing_information, payment_information, order_information, client_reference_information, - consumer_authentication_information: None, + consumer_authentication_information, merchant_defined_information, }) } @@ -922,6 +1022,8 @@ impl .three_ds_data .directory_server_transaction_id, specification_version: three_ds_info.three_ds_data.specification_version, + pa_specification_version: None, + veres_enrolled: None, }); let merchant_defined_information = @@ -1000,6 +1102,8 @@ impl xid: None, directory_server_transaction_id: None, specification_version: None, + pa_specification_version: None, + veres_enrolled: None, }), merchant_defined_information, }) @@ -1131,6 +1235,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> xid: None, directory_server_transaction_id: None, specification_version: None, + pa_specification_version: None, + veres_enrolled: None, }, ), }) diff --git a/crates/router/src/connector/netcetera/transformers.rs b/crates/router/src/connector/netcetera/transformers.rs index fffacc3ea4d..25ed7c5271e 100644 --- a/crates/router/src/connector/netcetera/transformers.rs +++ b/crates/router/src/connector/netcetera/transformers.rs @@ -167,6 +167,7 @@ impl authn_flow_type, authentication_value: response.authentication_value, trans_status: response.trans_status, + ds_trans_id: response.authentication_response.ds_trans_id, }, ) } @@ -646,6 +647,8 @@ pub struct AuthenticationResponse { pub acs_reference_number: Option<String>, #[serde(rename = "acsTransID")] pub acs_trans_id: Option<String>, + #[serde(rename = "dsTransID")] + pub ds_trans_id: Option<String>, pub acs_signed_content: Option<String>, } diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index 2a8498bfbad..44836002024 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -625,7 +625,7 @@ impl TryFrom<(&domain::payments::Card, &types::PaymentsAuthorizeData)> for Payme cavv: Some(auth_data.cavv.clone()), eci: auth_data.eci.clone(), cardholder_auth: None, - three_ds_version: Some(auth_data.message_version.clone()), + three_ds_version: Some(auth_data.message_version.to_string()), directory_server_id: Some(auth_data.threeds_server_transaction_id.clone().into()), }; diff --git a/crates/router/src/connector/threedsecureio/transformers.rs b/crates/router/src/connector/threedsecureio/transformers.rs index fe26e509c12..242d0dee946 100644 --- a/crates/router/src/connector/threedsecureio/transformers.rs +++ b/crates/router/src/connector/threedsecureio/transformers.rs @@ -187,6 +187,7 @@ impl types::authentication::AuthNFlowType::Frictionless }, authentication_value: response.authentication_value, + ds_trans_id: Some(response.ds_trans_id), }, ) } diff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rs index 0152fb4321d..f67f66bfffb 100644 --- a/crates/router/src/core/authentication/utils.rs +++ b/crates/router/src/core/authentication/utils.rs @@ -84,6 +84,7 @@ pub async fn update_trackers<F: Clone, Req>( authn_flow_type, authentication_value, trans_status, + ds_trans_id, } => { let authentication_status = common_enums::AuthenticationStatus::foreign_from(trans_status.clone()); @@ -97,6 +98,7 @@ pub async fn update_trackers<F: Clone, Req>( acs_signed_content: authn_flow_type.get_acs_signed_content(), authentication_type: authn_flow_type.get_decoupled_authentication_type(), authentication_status, + ds_trans_id, } } AuthenticationResponseData::PostAuthNResponse { @@ -183,6 +185,7 @@ pub async fn create_new_authentication( profile_id, payment_id, merchant_connector_id, + ds_trans_id: None, directory_server_id: None, }; state diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs index d39527b4229..92c9eec5ff8 100644 --- a/crates/router/src/core/payments/types.rs +++ b/crates/router/src/core/payments/types.rs @@ -369,7 +369,8 @@ impl ForeignTryFrom<&storage::Authentication> for AuthenticationData { eci: authentication.eci.clone(), cavv, threeds_server_transaction_id, - message_version: message_version.to_string(), + message_version, + ds_trans_id: authentication.ds_trans_id.clone(), }) } else { Err(errors::ApiErrorResponse::PaymentAuthenticationFailed { data: None }.into()) diff --git a/crates/router/src/db/authentication.rs b/crates/router/src/db/authentication.rs index 4eff3dfdbfd..cd3bb663ec9 100644 --- a/crates/router/src/db/authentication.rs +++ b/crates/router/src/db/authentication.rs @@ -147,6 +147,7 @@ impl AuthenticationInterface for MockDb { profile_id: authentication.profile_id, payment_id: authentication.payment_id, merchant_connector_id: authentication.merchant_connector_id, + ds_trans_id: authentication.ds_trans_id, directory_server_id: authentication.directory_server_id, }; authentications.push(authentication.clone()); diff --git a/migrations/2024-05-21-065403_add_ds_trans_id_to_authentication_table/down.sql b/migrations/2024-05-21-065403_add_ds_trans_id_to_authentication_table/down.sql new file mode 100644 index 00000000000..146b91185c2 --- /dev/null +++ b/migrations/2024-05-21-065403_add_ds_trans_id_to_authentication_table/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE authentication DROP COLUMN If EXISTS ds_trans_id; \ No newline at end of file diff --git a/migrations/2024-05-21-065403_add_ds_trans_id_to_authentication_table/up.sql b/migrations/2024-05-21-065403_add_ds_trans_id_to_authentication_table/up.sql new file mode 100644 index 00000000000..b02613777c8 --- /dev/null +++ b/migrations/2024-05-21-065403_add_ds_trans_id_to_authentication_table/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE authentication ADD COLUMN IF NOT EXISTS ds_trans_id VARCHAR(64); \ No newline at end of file
2024-05-21T11:09:06Z
## Description <!-- Describe your changes in detail --> add support for external authentication for cybersource. After this change is merged, we'll be able to authenticate a payment through an external 3ds authentication(threedsecureio or netcetera) and authorise the same payment through cybersource. Other changes: Added `ds_trans_id` field to `authentication` table since it is required for authorization through cybersource. ### 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)? --> Ran cybersource postman collection to make sure existing 3ds flow is not affected. <img width="785" alt="Screenshot 2024-05-23 at 1 00 07 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/c210e8ce-1864-444d-8f81-2ef3a7133160"> curls: 1. Create a cybersource connector and netcetera authentication connector. ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_7360288d-b77e-4624-8a48-74c11c31d3a0/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "cybersource", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "", "key1": "", "api_secret": "" }, "test_mode": false, "disabled": false, "business_country": "US", "business_label": "default", "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 } ] }, { "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": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "acquirer_bin": "438309", "acquirer_merchant_id": "00002000000" } }' ``` ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_7360288d-b77e-4624-8a48-74c11c31d3a0/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "authentication_processor", "business_country": "US", "business_label": "default", "connector_name": "netcetera", "connector_account_details": { "auth_type": "CertificateAuth", "certificate": "", "private_key": "" }, "test_mode": true, "disabled": false, "metadata": { "mcc": "5411", "merchant_country_code": "840", "merchant_name": "Dummy Merchant", "endpoint_prefix": "flowbird", "three_ds_requestor_name": "juspay-prev", "three_ds_requestor_id": "juspay-prev", "pull_mechanism_for_external_3ds_enabled": false } }' ``` 2. Create a payment with "request_external_three_ds_authentication": true, and "authentication_type": "three_ds", ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Mv6wkxquIeO6WDvY49Mpd4hullQ4CW05hBRT7tlIX4EOS5NaG5fmDzuY5NqacvXT' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": false, "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": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" }, "phone": { "number": "123456789", "country_code": "12" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" }, "phone": { "number": "123456789", "country_code": "12" } }, "request_external_three_ds_authentication": true, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 3. Confirm the payment ``` curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_d777ba4dfb764db2a6f851870a00a7e5' \ --data '{ "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": "115.99.183.2" }, "client_secret": "pay_XPc0gwoIZLYpMBKI8Yng_secret_vRjk6g87hvftbO9z18BO", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4929251897047956", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } }' ``` 4. Authenticate the payment. ``` curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng/3ds/authentication' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_d777ba4dfb764db2a6f851870a00a7e5' \ --data '{ "client_secret": "pay_XPc0gwoIZLYpMBKI8Yng_secret_vRjk6g87hvftbO9z18BO", "device_channel": "BRW", "threeds_method_comp_ind": "N" }' ``` 5. Authorize the payment. ``` curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng/postman_merchant_GHAction_7360288d-b77e-4624-8a48-74c11c31d3a0/authorize/checkout' \ --header 'Content-Type: application/json' \ --data '{ }' ``` 6. Retrive the payment. ``` curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_Mv6wkxquIeO6WDvY49Mpd4hullQ4CW05hBRT7tlIX4EOS5NaG5fmDzuY5NqacvXT' ``` Payment should `succeed` and below object should be returned in the payment response body. ``` "external_authentication_details": { "authentication_flow": "frictionless", "electronic_commerce_indicator": null, "status": "success", "ds_transaction_id": "3961a5b1-593f-4f94-851e-2793cd7f9e77", "version": "2.2.0", "error_code": null, "error_message": null } ```
dd333298f8b4e8ff3c15fc79fbc528a61fa1b63f
Ran cybersource postman collection to make sure existing 3ds flow is not affected. <img width="785" alt="Screenshot 2024-05-23 at 1 00 07 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/c210e8ce-1864-444d-8f81-2ef3a7133160"> curls: 1. Create a cybersource connector and netcetera authentication connector. ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_7360288d-b77e-4624-8a48-74c11c31d3a0/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "cybersource", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "", "key1": "", "api_secret": "" }, "test_mode": false, "disabled": false, "business_country": "US", "business_label": "default", "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 } ] }, { "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": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "acquirer_bin": "438309", "acquirer_merchant_id": "00002000000" } }' ``` ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_7360288d-b77e-4624-8a48-74c11c31d3a0/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "authentication_processor", "business_country": "US", "business_label": "default", "connector_name": "netcetera", "connector_account_details": { "auth_type": "CertificateAuth", "certificate": "", "private_key": "" }, "test_mode": true, "disabled": false, "metadata": { "mcc": "5411", "merchant_country_code": "840", "merchant_name": "Dummy Merchant", "endpoint_prefix": "flowbird", "three_ds_requestor_name": "juspay-prev", "three_ds_requestor_id": "juspay-prev", "pull_mechanism_for_external_3ds_enabled": false } }' ``` 2. Create a payment with "request_external_three_ds_authentication": true, and "authentication_type": "three_ds", ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Mv6wkxquIeO6WDvY49Mpd4hullQ4CW05hBRT7tlIX4EOS5NaG5fmDzuY5NqacvXT' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": false, "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": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" }, "phone": { "number": "123456789", "country_code": "12" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" }, "phone": { "number": "123456789", "country_code": "12" } }, "request_external_three_ds_authentication": true, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 3. Confirm the payment ``` curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_d777ba4dfb764db2a6f851870a00a7e5' \ --data '{ "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": "115.99.183.2" }, "client_secret": "pay_XPc0gwoIZLYpMBKI8Yng_secret_vRjk6g87hvftbO9z18BO", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4929251897047956", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } }' ``` 4. Authenticate the payment. ``` curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng/3ds/authentication' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_d777ba4dfb764db2a6f851870a00a7e5' \ --data '{ "client_secret": "pay_XPc0gwoIZLYpMBKI8Yng_secret_vRjk6g87hvftbO9z18BO", "device_channel": "BRW", "threeds_method_comp_ind": "N" }' ``` 5. Authorize the payment. ``` curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng/postman_merchant_GHAction_7360288d-b77e-4624-8a48-74c11c31d3a0/authorize/checkout' \ --header 'Content-Type: application/json' \ --data '{ }' ``` 6. Retrive the payment. ``` curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_Mv6wkxquIeO6WDvY49Mpd4hullQ4CW05hBRT7tlIX4EOS5NaG5fmDzuY5NqacvXT' ``` Payment should `succeed` and below object should be returned in the payment response body. ``` "external_authentication_details": { "authentication_flow": "frictionless", "electronic_commerce_indicator": null, "status": "success", "ds_transaction_id": "3961a5b1-593f-4f94-851e-2793cd7f9e77", "version": "2.2.0", "error_code": null, "error_message": null } ```
[ "crates/api_models/src/enums.rs", "crates/diesel_models/src/authentication.rs", "crates/diesel_models/src/schema.rs", "crates/hyperswitch_domain_models/src/router_request_types.rs", "crates/hyperswitch_domain_models/src/router_response_types.rs", "crates/router/src/connector/checkout/transformers.rs", "...
juspay/hyperswitch
juspay__hyperswitch-4712
Bug: [Refcator] Refactor Payment Response to show the Payment Method Data ### Feature Description Refactor Payment Response to show the Payment Method Data after a recurring payment using payment token ### Possible Implementation Refactor Payment Response to show the Payment Method Data after a recurring payment using payment token ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 7d1858bd0d7..6cbdb86a750 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -1,6 +1,10 @@ use std::marker::PhantomData; -use api_models::{admin::ExtendedCardInfoConfig, enums::FrmSuggestion, payments::ExtendedCardInfo}; +use api_models::{ + admin::ExtendedCardInfoConfig, + enums::FrmSuggestion, + payments::{AdditionalCardInfo, AdditionalPaymentData, ExtendedCardInfo}, +}; use async_trait::async_trait; use common_utils::ext_traits::{AsyncExt, Encode, StringExt, ValueExt}; use error_stack::{report, ResultExt}; @@ -17,6 +21,7 @@ use crate::{ blocklist::utils as blocklist_utils, errors::{self, CustomResult, RouterResult, StorageErrorExt}, mandate::helpers as m_helpers, + payment_methods::cards, payments::{ self, helpers, operations, populate_surcharge_details, CustomerDetails, PaymentAddress, PaymentData, @@ -1035,6 +1040,26 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode additional pm data")?; + let key = key_store.key.get_inner().peek(); + + let card_detail_from_locker = payment_data + .payment_method_info + .as_ref() + .async_map(|pm| async move { + cards::get_card_details_without_locker_fallback(pm, key, state).await + }) + .await + .transpose()?; + + let additional_data: Option<AdditionalCardInfo> = card_detail_from_locker.map(From::from); + + let encode_additional_pm_to_value = additional_data + .map(|additional_data| AdditionalPaymentData::Card(Box::new(additional_data))) + .as_ref() + .map(Encode::encode_to_value) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encode additional pm data")?; let business_sub_label = payment_data.payment_attempt.business_sub_label.clone(); let authentication_type = payment_data.payment_attempt.authentication_type; @@ -1079,12 +1104,20 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .or(payment_data.payment_attempt.client_version.clone()); let m_payment_data_payment_attempt = payment_data.payment_attempt.clone(); - let m_payment_method_id = payment_data.payment_attempt.payment_method_id.clone(); + let m_payment_method_id = + payment_data + .payment_attempt + .payment_method_id + .clone() + .or(payment_data + .payment_method_info + .as_ref() + .map(|payment_method| payment_method.payment_method_id.clone())); let m_browser_info = browser_info.clone(); let m_connector = connector.clone(); let m_capture_method = capture_method; let m_payment_token = payment_token.clone(); - let m_additional_pm_data = additional_pm_data.clone(); + let m_additional_pm_data = additional_pm_data.clone().or(encode_additional_pm_to_value); let m_business_sub_label = business_sub_label.clone(); let m_straight_through_algorithm = straight_through_algorithm.clone(); let m_error_code = error_code.clone();
2024-05-21T08:22:32Z
## Description add support to enable pm_data and pm_id in payments response ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? - Create a MA and a MCA - Create a Off session payment with Customer Acceptance > ``` Create curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \ --data-raw '{ "amount": 6777, "currency": "USD", "confirm": false, "customer_id": "new-c777", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage":"off_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` > ``` Confirm curl --location 'http://localhost:8080/payments/pay_2iVBNXi0blHcB0tyjeMW/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \ --data '{ "confirm": true, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "12", "card_exp_year": "2043", "card_holder_name": "Cy1", "card_cvc": "123" } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } } }' ``` - Create a off session payment with payment token > ``` Create curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \ --data-raw '{ "amount": 6777, "currency": "USD", "confirm": false, "customer_id": "new-c777", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage":"off_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` > ``` Confirm curl --location 'http://localhost:8080/payments/pay_2iVBNXi0blHcB0tyjeMW/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \ --data '{ "confirm": true, "payment_method": "card", "payment_method_type": "credit", "payment_token": "{{payment_token}}" }' ``` - Retrieve the Payment, the card details will be shown in the response > ``` Response { "payment_id": "pay_2iVBNXi0blHcB0tyjeMW", "merchant_id": "merchant_1716278979", "status": "succeeded", "amount": 6777, "net_amount": 6777, "amount_capturable": 0, "amount_received": 6777, "connector": "cybersource", "client_secret": "pay_2iVBNXi0blHcB0tyjeMW_secret_Chc0A7EDkeiAoqfbuFKU", "created": "2024-05-21T08:10:04.739Z", "currency": "USD", "customer_id": "new-c777", "customer": { "id": "new-c777", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "2043", "card_holder_name": "Cy1", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": null }, "authentication_data": null }, "billing": null }, "payment_token": "token_JHzGpIqfTEJ0zm0QNE8T", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7162790289656608304951", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pay_2iVBNXi0blHcB0tyjeMW_1", "payment_link": null, "profile_id": "pro_3sd18D4q96QhAGUAI7K7", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_tSrvrQbl3NvDlS9GkQdd", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-21T08:25:04.739Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_UnNkHBpGbeX6pSecvsCt", "payment_method_status": "active", "updated": "2024-05-21T08:10:29.812Z", "frm_metadata": null } ```
44681ab058f081a5621ba147d5491111cfbc55bc
- Create a MA and a MCA - Create a Off session payment with Customer Acceptance > ``` Create curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \ --data-raw '{ "amount": 6777, "currency": "USD", "confirm": false, "customer_id": "new-c777", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage":"off_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` > ``` Confirm curl --location 'http://localhost:8080/payments/pay_2iVBNXi0blHcB0tyjeMW/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \ --data '{ "confirm": true, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "12", "card_exp_year": "2043", "card_holder_name": "Cy1", "card_cvc": "123" } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } } }' ``` - Create a off session payment with payment token > ``` Create curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \ --data-raw '{ "amount": 6777, "currency": "USD", "confirm": false, "customer_id": "new-c777", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage":"off_session", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "connector_metadata": { "noon": { "order_category": "pay" } } }' ``` > ``` Confirm curl --location 'http://localhost:8080/payments/pay_2iVBNXi0blHcB0tyjeMW/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \ --data '{ "confirm": true, "payment_method": "card", "payment_method_type": "credit", "payment_token": "{{payment_token}}" }' ``` - Retrieve the Payment, the card details will be shown in the response > ``` Response { "payment_id": "pay_2iVBNXi0blHcB0tyjeMW", "merchant_id": "merchant_1716278979", "status": "succeeded", "amount": 6777, "net_amount": 6777, "amount_capturable": 0, "amount_received": 6777, "connector": "cybersource", "client_secret": "pay_2iVBNXi0blHcB0tyjeMW_secret_Chc0A7EDkeiAoqfbuFKU", "created": "2024-05-21T08:10:04.739Z", "currency": "USD", "customer_id": "new-c777", "customer": { "id": "new-c777", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "2043", "card_holder_name": "Cy1", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": null }, "authentication_data": null }, "billing": null }, "payment_token": "token_JHzGpIqfTEJ0zm0QNE8T", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7162790289656608304951", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pay_2iVBNXi0blHcB0tyjeMW_1", "payment_link": null, "profile_id": "pro_3sd18D4q96QhAGUAI7K7", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_tSrvrQbl3NvDlS9GkQdd", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-21T08:25:04.739Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_UnNkHBpGbeX6pSecvsCt", "payment_method_status": "active", "updated": "2024-05-21T08:10:29.812Z", "frm_metadata": null } ```
[ "crates/router/src/core/payments/operations/payment_confirm.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4706
Bug: [bug]: fix timestamp sent to kafka events rdkafka library expects time in millis but we send seconds. This can be reflected in the kafka-ui at localhost:8090 as well. We can fix this by either truncating the unix_timestamp_nanos or padding the seconds.
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index 58657c59fd8..6f2aa9fcd10 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -259,7 +259,7 @@ impl KafkaProducer { .timestamp( event .creation_timestamp() - .unwrap_or_else(|| OffsetDateTime::now_utc().unix_timestamp()), + .unwrap_or_else(|| OffsetDateTime::now_utc().unix_timestamp() * 1_000), ), ) .map_err(|(error, record)| report!(error).attach_printable(format!("{record:?}"))) @@ -476,7 +476,7 @@ impl MessagingInterface for KafkaProducer { .key(&data.identifier()) .payload(&json_data) .timestamp( - (timestamp.assume_utc().unix_timestamp_nanos() / 1_000) + (timestamp.assume_utc().unix_timestamp_nanos() / 1_000_000) .to_i64() .unwrap_or_else(|| { // kafka producer accepts milliseconds diff --git a/crates/router/src/services/kafka/dispute.rs b/crates/router/src/services/kafka/dispute.rs index c01089855c6..1950fb253a7 100644 --- a/crates/router/src/services/kafka/dispute.rs +++ b/crates/router/src/services/kafka/dispute.rs @@ -70,10 +70,6 @@ impl<'a> super::KafkaMessage for KafkaDispute<'a> { ) } - fn creation_timestamp(&self) -> Option<i64> { - Some(self.modified_at.unix_timestamp()) - } - fn event_type(&self) -> crate::events::EventType { crate::events::EventType::Dispute } diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs index dfa7da0d0a4..86ea378bfa3 100644 --- a/crates/router/src/services/kafka/payment_attempt.rs +++ b/crates/router/src/services/kafka/payment_attempt.rs @@ -108,10 +108,6 @@ impl<'a> super::KafkaMessage for KafkaPaymentAttempt<'a> { ) } - fn creation_timestamp(&self) -> Option<i64> { - Some(self.modified_at.unix_timestamp()) - } - fn event_type(&self) -> crate::events::EventType { crate::events::EventType::PaymentAttempt } diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs index ad61e102955..bcdf23e7941 100644 --- a/crates/router/src/services/kafka/payment_intent.rs +++ b/crates/router/src/services/kafka/payment_intent.rs @@ -66,10 +66,6 @@ impl<'a> super::KafkaMessage for KafkaPaymentIntent<'a> { format!("{}_{}", self.merchant_id, self.payment_id) } - fn creation_timestamp(&self) -> Option<i64> { - Some(self.modified_at.unix_timestamp()) - } - fn event_type(&self) -> crate::events::EventType { crate::events::EventType::PaymentIntent } diff --git a/crates/router/src/services/kafka/payout.rs b/crates/router/src/services/kafka/payout.rs index 6b25c724eb8..a07b90ee288 100644 --- a/crates/router/src/services/kafka/payout.rs +++ b/crates/router/src/services/kafka/payout.rs @@ -80,10 +80,6 @@ impl<'a> super::KafkaMessage for KafkaPayout<'a> { format!("{}_{}", self.merchant_id, self.payout_attempt_id) } - fn creation_timestamp(&self) -> Option<i64> { - Some(self.last_modified_at.unix_timestamp()) - } - fn event_type(&self) -> crate::events::EventType { crate::events::EventType::Payout }
2024-05-20T14:16:14Z
## Description <!-- Describe your changes in detail --> fixes #4706 Convert secs to millis when sending creation timestamp 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). --> - This will fix problems encountered down the pipeline with data retention ## 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 timestamp listed in kafka-ui - can't be tested without infra access and no visible changes on UI
ae601e8e1be9215488daaae7cb39ad5a030e98d9
- the timestamp listed in kafka-ui - can't be tested without infra access and no visible changes on UI
[ "crates/router/src/services/kafka.rs", "crates/router/src/services/kafka/dispute.rs", "crates/router/src/services/kafka/payment_attempt.rs", "crates/router/src/services/kafka/payment_intent.rs", "crates/router/src/services/kafka/payout.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4707
Bug: refactor: Separate out recovery codes from TOTP Even though recovery codes is dependent entity on TOTP. But the new findings suggest that TOTP is a part of entity called 2FA and TOTP is depended on the 2FA entity not the TOTP entity. This will be more clear when we add multiple 2FAs like SMS OTP. So, we want to separate out recovery codes from the TOTP. This means `begin_totp` should not return the recovery codes anymore.
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index e9eb5157095..b7d7adbf8e3 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -14,10 +14,10 @@ use crate::user::{ ConnectAccountRequest, CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse, ReInviteUserRequest, - ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse, - SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse, - TokenResponse, UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate, - VerifyEmailRequest, VerifyTotpRequest, + RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, + SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, + TokenOrPayloadResponse, TokenResponse, UpdateUserAccountDetailsRequest, UserFromEmailRequest, + UserMerchantCreate, VerifyEmailRequest, VerifyTotpRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -75,7 +75,8 @@ common_utils::impl_misc_api_event_type!( TokenResponse, UserFromEmailRequest, BeginTotpResponse, - VerifyTotpRequest + VerifyTotpRequest, + RecoveryCodes ); #[cfg(feature = "dummy_connector")] diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 7dbf867d1a0..7864117856e 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -257,3 +257,8 @@ pub struct TotpSecret { pub struct VerifyTotpRequest { pub totp: Option<Secret<String>>, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct RecoveryCodes { + pub recovery_codes: Vec<Secret<String>>, +} diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index 8d6aa6265d8..33642205d57 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -12,3 +12,5 @@ pub const TOTP_VALIDITY_DURATION_IN_SECONDS: u64 = 30; pub const TOTP_TOLERANCE: u8 = 1; pub const MAX_PASSWORD_LENGTH: usize = 70; pub const MIN_PASSWORD_LENGTH: usize = 8; + +pub const TOTP_PREFIX: &str = "TOTP_"; diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index 580e34ba7e8..2d1c196f5df 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -66,10 +66,12 @@ pub enum UserErrors { RoleNameParsingError, #[error("RoleNameAlreadyExists")] RoleNameAlreadyExists, - #[error("TOTPNotSetup")] + #[error("TotpNotSetup")] TotpNotSetup, - #[error("InvalidTOTP")] + #[error("InvalidTotp")] InvalidTotp, + #[error("TotpRequired")] + TotpRequired, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -179,6 +181,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::InvalidTotp => { AER::BadRequest(ApiError::new(sub_code, 37, self.get_error_message(), None)) } + Self::TotpRequired => { + AER::BadRequest(ApiError::new(sub_code, 38, self.get_error_message(), None)) + } } } } @@ -217,6 +222,7 @@ impl UserErrors { Self::RoleNameAlreadyExists => "Role name already exists", Self::TotpNotSetup => "TOTP not setup", Self::InvalidTotp => "Invalid TOTP", + Self::TotpRequired => "TOTP required", } } } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 5d1eaeaeb8d..7a0ef683e7a 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1631,7 +1631,7 @@ pub async fn begin_totp( })); } - let totp = utils::user::generate_default_totp(user_from_db.get_email(), None)?; + let totp = utils::user::two_factor_auth::generate_default_totp(user_from_db.get_email(), None)?; let recovery_codes = domain::RecoveryCodes::generate_new(); let key_store = user_from_db.get_or_create_key_store(&state).await?; @@ -1693,8 +1693,10 @@ pub async fn verify_totp( .await? .ok_or(UserErrors::InternalServerError)?; - let totp = - utils::user::generate_default_totp(user_from_db.get_email(), Some(user_totp_secret))?; + let totp = utils::user::two_factor_auth::generate_default_totp( + user_from_db.get_email(), + Some(user_totp_secret), + )?; if totp .generate_current() @@ -1732,3 +1734,35 @@ pub async fn verify_totp( token, ) } + +pub async fn generate_recovery_codes( + state: AppState, + user_token: auth::UserFromSinglePurposeToken, +) -> UserResponse<user_api::RecoveryCodes> { + if !utils::user::two_factor_auth::check_totp_in_redis(&state, &user_token.user_id).await? { + return Err(UserErrors::TotpRequired.into()); + } + + let recovery_codes = domain::RecoveryCodes::generate_new(); + + state + .store + .update_user_by_user_id( + &user_token.user_id, + storage_user::UserUpdate::TotpUpdate { + totp_status: None, + totp_secret: None, + totp_recovery_codes: Some( + recovery_codes + .get_hashed() + .change_context(UserErrors::InternalServerError)?, + ), + }, + ) + .await + .change_context(UserErrors::InternalServerError)?; + + Ok(ApplicationResponse::Json(user_api::RecoveryCodes { + recovery_codes: recovery_codes.into_inner(), + })) +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f4eded24be6..7c8f7e32be1 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1207,7 +1207,11 @@ impl User { .route(web::post().to(set_dashboard_metadata)), ) .service(web::resource("/totp/begin").route(web::get().to(totp_begin))) - .service(web::resource("/totp/verify").route(web::post().to(totp_verify))); + .service(web::resource("/totp/verify").route(web::post().to(totp_verify))) + .service( + web::resource("/recovery_codes/generate") + .route(web::get().to(generate_recovery_codes)), + ); #[cfg(feature = "email")] { diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 30b582079e3..542a18d45be 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -213,7 +213,8 @@ impl From<Flow> for ApiIdentifier { | Flow::VerifyEmailRequest | Flow::UpdateUserAccountDetails | Flow::TotpBegin - | Flow::TotpVerify => Self::User, + | Flow::TotpVerify + | Flow::GenerateRecoveryCodes => Self::User, Flow::ListRoles | Flow::GetRole diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index f28064901e5..f542c446e49 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -665,3 +665,17 @@ pub async fn totp_verify( )) .await } + +pub async fn generate_recovery_codes(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { + let flow = Flow::GenerateRecoveryCodes; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + (), + |state, user, _, _| user_core::generate_recovery_codes(state, user), + &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 4980958c9ac..9c67dbfcab5 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -1,14 +1,11 @@ use std::collections::HashMap; use api_models::user as user_api; -use common_utils::{errors::CustomResult, pii}; +use common_utils::errors::CustomResult; use diesel_models::{enums::UserStatus, user_role::UserRole}; use error_stack::ResultExt; -use masking::ExposeInterface; -use totp_rs::{Algorithm, TOTP}; use crate::{ - consts, core::errors::{StorageError, UserErrors, UserResult}, routes::AppState, services::{ @@ -22,6 +19,7 @@ pub mod dashboard_metadata; pub mod password; #[cfg(feature = "dummy_connector")] pub mod sample_data; +pub mod two_factor_auth; impl UserFromToken { pub async fn get_merchant_account_from_db( @@ -193,25 +191,3 @@ pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> maskin user_api::SignInResponse::MerchantSelect(data) => data.token.clone(), } } - -pub fn generate_default_totp( - email: pii::Email, - secret: Option<masking::Secret<String>>, -) -> UserResult<TOTP> { - let secret = secret - .map(|sec| totp_rs::Secret::Encoded(sec.expose())) - .unwrap_or_else(totp_rs::Secret::generate_secret) - .to_bytes() - .change_context(UserErrors::InternalServerError)?; - - TOTP::new( - Algorithm::SHA1, - consts::user::TOTP_DIGITS, - consts::user::TOTP_TOLERANCE, - consts::user::TOTP_VALIDITY_DURATION_IN_SECONDS, - secret, - Some(consts::user::TOTP_ISSUER_NAME.to_string()), - email.expose().expose(), - ) - .change_context(UserErrors::InternalServerError) -} diff --git a/crates/router/src/utils/user/two_factor_auth.rs b/crates/router/src/utils/user/two_factor_auth.rs new file mode 100644 index 00000000000..62bcf2f7eb1 --- /dev/null +++ b/crates/router/src/utils/user/two_factor_auth.rs @@ -0,0 +1,52 @@ +use std::sync::Arc; + +use common_utils::pii; +use error_stack::ResultExt; +use masking::ExposeInterface; +use redis_interface::RedisConnectionPool; +use totp_rs::{Algorithm, TOTP}; + +use crate::{ + consts, + core::errors::{UserErrors, UserResult}, + routes::AppState, +}; + +pub fn generate_default_totp( + email: pii::Email, + secret: Option<masking::Secret<String>>, +) -> UserResult<TOTP> { + let secret = secret + .map(|sec| totp_rs::Secret::Encoded(sec.expose())) + .unwrap_or_else(totp_rs::Secret::generate_secret) + .to_bytes() + .change_context(UserErrors::InternalServerError)?; + + TOTP::new( + Algorithm::SHA1, + consts::user::TOTP_DIGITS, + consts::user::TOTP_TOLERANCE, + consts::user::TOTP_VALIDITY_DURATION_IN_SECONDS, + secret, + Some(consts::user::TOTP_ISSUER_NAME.to_string()), + email.expose().expose(), + ) + .change_context(UserErrors::InternalServerError) +} + +pub async fn check_totp_in_redis(state: &AppState, user_id: &str) -> UserResult<bool> { + let redis_conn = get_redis_connection(state)?; + let key = format!("{}{}", consts::user::TOTP_PREFIX, user_id); + redis_conn + .exists::<()>(&key) + .await + .change_context(UserErrors::InternalServerError) +} + +fn get_redis_connection(state: &AppState) -> UserResult<Arc<RedisConnectionPool>> { + state + .store + .get_redis_conn() + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get redis connection") +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index ffa492bc60d..186ee4a6704 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -404,6 +404,8 @@ pub enum Flow { TotpBegin, /// Verify TOTP TotpVerify, + /// Generate or Regenerate recovery codes + GenerateRecoveryCodes, /// List initial webhook delivery attempts WebhookEventInitialDeliveryAttemptList, /// List delivery attempts for a webhook event
2024-05-20T13:58:53Z
## Description <!-- Describe your changes in detail --> Currently recovery code are being generated in `begin_totp` API. We want to make a separate out recovery codes and TOTP, so this PR creates a new API which generates the recovery codes. This API will also be used to regenerate recovery codes later. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This is a sub part of #4707 ## 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 only be tested locally as it requires some changes in the redis.** ``` curl --location 'http://localhost:8080/user/recovery_codes/generate' \ --header 'Authorization: Bearer SPT with purpose as TOTP' \ ``` ``` { "recovery_codes": [ "w5fM-NLm0", "TumH-oyXE", "wDIr-zEmu", "HZjm-e16M", "Q4qB-MupL", "5BtN-vRuY", "4vG6-URGf", "Dbq8-n5V1" ] } ```
36409bdc9185d4241971a30c55e1e331568abd2f
**This can only be tested locally as it requires some changes in the redis.** ``` curl --location 'http://localhost:8080/user/recovery_codes/generate' \ --header 'Authorization: Bearer SPT with purpose as TOTP' \ ``` ``` { "recovery_codes": [ "w5fM-NLm0", "TumH-oyXE", "wDIr-zEmu", "HZjm-e16M", "Q4qB-MupL", "5BtN-vRuY", "4vG6-URGf", "Dbq8-n5V1" ] } ```
[ "crates/api_models/src/events/user.rs", "crates/api_models/src/user.rs", "crates/router/src/consts/user.rs", "crates/router/src/core/errors/user.rs", "crates/router/src/core/user.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/user.rs", "cr...
juspay/hyperswitch
juspay__hyperswitch-4702
Bug: [FEATURE] [AUTHORIZEDOTNET] Implement zero mandates ### Feature Description Zero dollar mandates need to be implemented for connector Authorizedotnet. ### Possible Implementation Zero dollar mandates need to be implemented for connector Authorizedotnet. ### 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/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index 0eb4297a414..a9e000b82b9 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -121,20 +121,84 @@ impl types::PaymentsResponseData, > for Authorizedotnet { - // Issue: #173 - fn build_request( + fn get_headers( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, + req: &types::SetupMandateRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + // This connector does not require an auth header, the authentication details are sent in the request body + self.build_headers(req, connectors) + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_url( + &self, + _req: &types::SetupMandateRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(self.base_url(connectors).to_string()) + } + fn get_request_body( + &self, + req: &types::SetupMandateRouterData, _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented( - "Setup Mandate flow for Authorizedotnet".to_string(), - ) - .into()) + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = authorizedotnet::CreateCustomerProfileRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &types::SetupMandateRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<common_utils::request::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::SetupMandateType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::SetupMandateType::get_headers(self, req, connectors)?) + .set_body(types::SetupMandateType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::SetupMandateRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: types::Response, + ) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> { + use bytes::Buf; + + // Handle the case where response bytes contains U+FEFF (BOM) character sent by connector + let encoding = encoding_rs::UTF_8; + let intermediate_response = encoding.decode_with_bom_removal(res.response.chunk()); + let intermediate_response = + bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes()); + let response: authorizedotnet::AuthorizedotnetSetupMandateResponse = 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(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + get_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index ddcfdfacad2..8069b925d44 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -1,6 +1,7 @@ use common_utils::{ errors::CustomResult, ext_traits::{Encode, ValueExt}, + pii, }; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret, StrongSecret}; @@ -8,7 +9,8 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::{ - self, CardData, PaymentsSyncRequestData, RefundsRequestData, RouterData, WalletData, + self, missing_field_err, CardData, PaymentsSyncRequestData, RefundsRequestData, RouterData, + WalletData, }, core::errors, services, @@ -126,112 +128,18 @@ pub enum WalletMethod { Applepay, } -fn get_pm_and_subsequent_auth_detail( - item: &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>, -) -> Result< - ( - PaymentDetails, - Option<ProcessingOptions>, - Option<SubsequentAuthInformation>, - ), - error_stack::Report<errors::ConnectorError>, -> { - match item - .router_data - .request - .mandate_id - .to_owned() - .and_then(|mandate_ids| mandate_ids.mandate_reference_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: Secret::new(network_trans_id), - reason: Reason::Resubmission, - }); - match item.router_data.request.payment_method_data { - domain::PaymentMethodData::Card(ref ccard) => { - let payment_details = PaymentDetails::CreditCard(CreditCardDetails { - card_number: (*ccard.card_number).clone(), - expiration_date: ccard.get_expiry_date_as_yyyymm("-"), - card_code: None, - }); - Ok((payment_details, processing_options, subseuent_auth_info)) - } - domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("authorizedotnet"), - ))? - } - } - } - Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) | None => { - match item.router_data.request.payment_method_data { - domain::PaymentMethodData::Card(ref ccard) => { - Ok(( - PaymentDetails::CreditCard(CreditCardDetails { - card_number: (*ccard.card_number).clone(), - // expiration_date: format!("{expiry_year}-{expiry_month}").into(), - expiration_date: ccard.get_expiry_date_as_yyyymm("-"), - card_code: Some(ccard.card_cvc.clone()), - }), - Some(ProcessingOptions { - is_subsequent_auth: true, - }), - None, - )) - } - domain::PaymentMethodData::Wallet(ref wallet_data) => Ok(( - get_wallet_data( - wallet_data, - &item.router_data.request.complete_authorize_url, - )?, - None, - None, - )), - domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("authorizedotnet"), - ))? - } - } - } - } -} - #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct TransactionRequest { transaction_type: TransactionType, amount: f64, currency_code: String, - payment: PaymentDetails, + #[serde(skip_serializing_if = "Option::is_none")] + profile: Option<CustomerProfileDetails>, + #[serde(skip_serializing_if = "Option::is_none")] + payment: Option<PaymentDetails>, order: Order, + #[serde(skip_serializing_if = "Option::is_none")] bill_to: Option<BillTo>, processing_options: Option<ProcessingOptions>, #[serde(skip_serializing_if = "Option::is_none")] @@ -239,6 +147,19 @@ struct TransactionRequest { authorization_indicator_type: Option<AuthorizationIndicator>, } +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +struct CustomerProfileDetails { + customer_profile_id: Secret<String>, + payment_profile: PaymentProfileDetails, +} + +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +struct PaymentProfileDetails { + payment_profile_id: Secret<String>, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProcessingOptions { @@ -312,6 +233,192 @@ pub struct AuthorizedotnetPaymentCancelOrCaptureRequest { transaction_request: TransactionVoidOrCaptureRequest, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +// The connector enforces field ordering, it expects fields to be in the same order as in their API documentation +pub struct CreateCustomerProfileRequest { + create_customer_profile_request: AuthorizedotnetZeroMandateRequest, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthorizedotnetZeroMandateRequest { + merchant_authentication: AuthorizedotnetAuthType, + profile: Profile, + validation_mode: ValidationMode, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct Profile { + merchant_customer_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + description: Option<String>, + email: Option<pii::Email>, + payment_profiles: PaymentProfiles, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct PaymentProfiles { + customer_type: CustomerType, + payment: PaymentDetails, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum CustomerType { + Individual, + Business, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ValidationMode { + // testMode performs a Luhn mod-10 check on the card number, without further validation at connector. + TestMode, + // liveMode submits a zero-dollar or one-cent transaction (depending on card type and processor support) to confirm that the card number belongs to an active credit or debit account. + LiveMode, +} + +impl TryFrom<&types::SetupMandateRouterData> for CreateCustomerProfileRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { + match item.request.payment_method_data.clone() { + domain::PaymentMethodData::Card(ccard) => { + let merchant_authentication = + AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?; + let validation_mode = match item.test_mode { + Some(true) | None => ValidationMode::TestMode, + Some(false) => ValidationMode::LiveMode, + }; + Ok(Self { + create_customer_profile_request: AuthorizedotnetZeroMandateRequest { + merchant_authentication, + profile: Profile { + merchant_customer_id: item + .customer_id + .clone() + .ok_or_else(missing_field_err("customer_id"))?, + description: item.description.clone(), + email: item.request.email.clone(), + payment_profiles: PaymentProfiles { + customer_type: CustomerType::Individual, + payment: PaymentDetails::CreditCard(CreditCardDetails { + card_number: (*ccard.card_number).clone(), + expiration_date: ccard.get_expiry_date_as_yyyymm("-"), + card_code: Some(ccard.card_cvc.clone()), + }), + }, + }, + validation_mode, + }, + }) + } + domain::PaymentMethodData::CardRedirect(_) + | domain::PaymentMethodData::Wallet(_) + | domain::PaymentMethodData::PayLater(_) + | domain::PaymentMethodData::BankRedirect(_) + | domain::PaymentMethodData::BankDebit(_) + | domain::PaymentMethodData::BankTransfer(_) + | domain::PaymentMethodData::Crypto(_) + | domain::PaymentMethodData::MandatePayment + | domain::PaymentMethodData::Reward + | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("authorizedotnet"), + ))? + } + } + } +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthorizedotnetSetupMandateResponse { + customer_profile_id: Option<String>, + customer_payment_profile_id_list: Vec<String>, + validation_direct_response_list: Option<Vec<Secret<String>>>, + pub messages: ResponseMessages, +} + +// zero dollar response +impl<F, T> + TryFrom< + types::ResponseRouterData< + F, + AuthorizedotnetSetupMandateResponse, + T, + types::PaymentsResponseData, + >, + > for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + AuthorizedotnetSetupMandateResponse, + T, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response.messages.result_code { + ResultCode::Ok => Ok(Self { + status: enums::AttemptStatus::Charged, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data: None, + mandate_reference: item.response.customer_profile_id.map(|mandate_id| { + types::MandateReference { + connector_mandate_id: Some(mandate_id), + payment_method_id: item + .response + .customer_payment_profile_id_list + .first() + .cloned(), + } + }), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + }), + ..item.data + }), + ResultCode::Error => { + let error_code = match item.response.messages.message.first() { + Some(first_error_message) => first_error_message.code.clone(), + None => crate::consts::NO_ERROR_CODE.to_string(), + }; + let error_reason = item + .response + .messages + .message + .iter() + .map(|error: &ResponseMessage| error.text.clone()) + .collect::<Vec<String>>() + .join(" "); + let response = Err(types::ErrorResponse { + code: error_code, + message: item.response.messages.result_code.to_string(), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: None, + }); + Ok(Self { + response, + status: enums::AttemptStatus::Failure, + ..item.data + }) + } + } + } +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] // The connector enforces field ordering, it expects fields to be in the same order as in their API documentation @@ -353,31 +460,153 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>> fn try_from( item: &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { - let (payment_details, processing_options, subsequent_auth_information) = - get_pm_and_subsequent_auth_detail(item)?; + let (payment_details, processing_options, subsequent_auth_information, profile) = match item + .router_data + .request + .mandate_id + .to_owned() + .and_then(|mandate_ids| mandate_ids.mandate_reference_id) + { + Some(api_models::payments::MandateReferenceId::NetworkMandateId(network_trans_id)) => { + let processing_options = Some(ProcessingOptions { + is_subsequent_auth: true, + }); + let subsequent_auth_info = Some(SubsequentAuthInformation { + original_network_trans_id: Secret::new(network_trans_id), + reason: Reason::Resubmission, + }); + match item.router_data.request.payment_method_data { + domain::PaymentMethodData::Card(ref ccard) => { + let payment_details = PaymentDetails::CreditCard(CreditCardDetails { + card_number: (*ccard.card_number).clone(), + expiration_date: ccard.get_expiry_date_as_yyyymm("-"), + card_code: None, + }); + ( + Some(payment_details), + processing_options, + subsequent_auth_info, + None, + ) + } + domain::PaymentMethodData::CardRedirect(_) + | domain::PaymentMethodData::Wallet(_) + | domain::PaymentMethodData::PayLater(_) + | domain::PaymentMethodData::BankRedirect(_) + | domain::PaymentMethodData::BankDebit(_) + | domain::PaymentMethodData::BankTransfer(_) + | domain::PaymentMethodData::Crypto(_) + | domain::PaymentMethodData::MandatePayment + | domain::PaymentMethodData::Reward + | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message( + "authorizedotnet", + ), + ))? + } + } + } + Some(api_models::payments::MandateReferenceId::ConnectorMandateId( + connector_mandate_id, + )) => ( + None, + Some(ProcessingOptions { + is_subsequent_auth: true, + }), + None, + Some(CustomerProfileDetails { + customer_profile_id: Secret::from( + connector_mandate_id + .connector_mandate_id + .ok_or(errors::ConnectorError::MissingConnectorMandateID)?, + ), + payment_profile: PaymentProfileDetails { + payment_profile_id: Secret::from( + connector_mandate_id + .payment_method_id + .ok_or(errors::ConnectorError::MissingConnectorMandateID)?, + ), + }, + }), + ), + None => { + match item.router_data.request.payment_method_data { + domain::PaymentMethodData::Card(ref ccard) => { + ( + Some(PaymentDetails::CreditCard(CreditCardDetails { + card_number: (*ccard.card_number).clone(), + // expiration_date: format!("{expiry_year}-{expiry_month}").into(), + expiration_date: ccard.get_expiry_date_as_yyyymm("-"), + card_code: Some(ccard.card_cvc.clone()), + })), + Some(ProcessingOptions { + is_subsequent_auth: true, + }), + None, + None, + ) + } + domain::PaymentMethodData::Wallet(ref wallet_data) => ( + Some(get_wallet_data( + wallet_data, + &item.router_data.request.complete_authorize_url, + )?), + None, + None, + None, + ), + domain::PaymentMethodData::CardRedirect(_) + | domain::PaymentMethodData::PayLater(_) + | domain::PaymentMethodData::BankRedirect(_) + | domain::PaymentMethodData::BankDebit(_) + | domain::PaymentMethodData::BankTransfer(_) + | domain::PaymentMethodData::Crypto(_) + | domain::PaymentMethodData::MandatePayment + | domain::PaymentMethodData::Reward + | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message( + "authorizedotnet", + ), + ))? + } + } + } + }; let authorization_indicator_type = match item.router_data.request.capture_method { Some(capture_method) => Some(AuthorizationIndicator { authorization_indicator: capture_method.try_into()?, }), None => None, }; - let bill_to = item - .router_data - .get_optional_billing() - .and_then(|billing_address| billing_address.address.as_ref()) - .map(|address| BillTo { - first_name: address.first_name.clone(), - last_name: address.last_name.clone(), - address: address.line1.clone(), - city: address.city.clone(), - state: address.state.clone(), - zip: address.zip.clone(), - country: address.country, - }); + let bill_to = match profile { + Some(_) => None, + None => item + .router_data + .get_optional_billing() + .and_then(|billing_address| billing_address.address.as_ref()) + .map(|address| BillTo { + first_name: address.first_name.clone(), + last_name: address.last_name.clone(), + address: address.line1.clone(), + city: address.city.clone(), + state: address.state.clone(), + zip: address.zip.clone(), + country: address.country, + }), + }; let transaction_request = TransactionRequest { transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, amount: item.amount, currency_code: item.router_data.request.currency.to_string(), + profile, payment: payment_details, order: Order { description: item.router_data.connector_request_reference_id.clone(), @@ -506,7 +735,7 @@ pub struct ResponseMessage { pub text: String, } -#[derive(Debug, Default, Clone, Deserialize, PartialEq, Serialize)] +#[derive(Debug, Default, Clone, Deserialize, PartialEq, Serialize, strum::Display)] enum ResultCode { #[default] Ok,
2024-05-20T10:00:16Z
## Description <!-- Describe your changes in detail --> Zero dollar mandates are implemented for connector Authorizedotnet. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/4702 ## 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)? --> _Note: `test_mode` should be set to `true` while testing._ - Create Zero Amount Mandate: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": true, "customer_id": "tester123", "email": "johndoe@gmail.com", "setup_future_usage": "off_session", "payment_type": "setup_mandate", "off_session": true, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "card_cvc": "123" } }, "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00Z", "end_date": "2023-05-21T00:00:00Z", "metadata": { "frequency": "13" } } } } }' ``` Response: ``` { "payment_id": "pay_BUTzOloWgy5ZjPUjOhDR", "merchant_id": "merchant_1709720492", "status": "succeeded", "amount": 0, "net_amount": 0, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_BUTzOloWgy5ZjPUjOhDR_secret_aQaDNrV3HKhGHZnLcWet", "created": "2024-05-21T13:43:09.180Z", "currency": "USD", "customer_id": "tester123", "customer": { "id": "tester123", "name": null, "email": "johndoe@gmail.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": "man_SJ0R3Dx1krNV2OYYXqK8", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00.000Z", "end_date": "2023-05-21T00:00:00.000Z", "metadata": { "frequency": "13" } } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "johndoe@gmail.com", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "tester123", "created_at": 1716298989, "expires": 1716302589, "secret": "epk_1cdb048e685f43f9ad8b1f1c20b5142b" }, "manual_retry_allowed": false, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_4aXJeUeyy9BzdhcV9Xue", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-21T13:58:09.180Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_eAcvFw4WhUlfAGyeya52", "payment_method_status": null, "updated": "2024-05-21T13:43:09.865Z", "frm_metadata": null } ``` - Create Payment Using Mandate: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 400, "currency": "USD", "confirm": true, "customer_id": "tester123", "mandate_id": "man_SJ0R3Dx1krNV2OYYXqK8", "off_session": true }' ``` Response: ``` { "payment_id": "pay_BYA7GLOyizx2lXr7HY8l", "merchant_id": "merchant_1709720492", "status": "succeeded", "amount": 400, "net_amount": 400, "amount_capturable": 0, "amount_received": 400, "connector": "authorizedotnet", "client_secret": "pay_BYA7GLOyizx2lXr7HY8l_secret_eyykmbXcMfPnc4m9Vbid", "created": "2024-05-21T13:47:00.958Z", "currency": "USD", "customer_id": "tester123", "customer": { "id": "tester123", "name": null, "email": "johndoe@gmail.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": "man_SJ0R3Dx1krNV2OYYXqK8", "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "3906c467-f517-40a1-bb0f-a10c4e6f9878", "shipping": null, "billing": null, "order_details": null, "email": "johndoe@gmail.com", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "tester123", "created_at": 1716299220, "expires": 1716302820, "secret": "epk_866be4c4a3de481b808853b80a5c5198" }, "manual_retry_allowed": false, "connector_transaction_id": "80018772612", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80018772612", "payment_link": null, "profile_id": "pro_4aXJeUeyy9BzdhcV9Xue", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-21T14:02:00.957Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_eAcvFw4WhUlfAGyeya52", "payment_method_status": "active", "updated": "2024-05-21T13:47:03.437Z", "frm_metadata": null } ```
0f53f74d26e829602519998c41a460dc9a4809af
_Note: `test_mode` should be set to `true` while testing._ - Create Zero Amount Mandate: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": true, "customer_id": "tester123", "email": "johndoe@gmail.com", "setup_future_usage": "off_session", "payment_type": "setup_mandate", "off_session": true, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "card_cvc": "123" } }, "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00Z", "end_date": "2023-05-21T00:00:00Z", "metadata": { "frequency": "13" } } } } }' ``` Response: ``` { "payment_id": "pay_BUTzOloWgy5ZjPUjOhDR", "merchant_id": "merchant_1709720492", "status": "succeeded", "amount": 0, "net_amount": 0, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_BUTzOloWgy5ZjPUjOhDR_secret_aQaDNrV3HKhGHZnLcWet", "created": "2024-05-21T13:43:09.180Z", "currency": "USD", "customer_id": "tester123", "customer": { "id": "tester123", "name": null, "email": "johndoe@gmail.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": "man_SJ0R3Dx1krNV2OYYXqK8", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00.000Z", "end_date": "2023-05-21T00:00:00.000Z", "metadata": { "frequency": "13" } } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "johndoe@gmail.com", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "tester123", "created_at": 1716298989, "expires": 1716302589, "secret": "epk_1cdb048e685f43f9ad8b1f1c20b5142b" }, "manual_retry_allowed": false, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_4aXJeUeyy9BzdhcV9Xue", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-21T13:58:09.180Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_eAcvFw4WhUlfAGyeya52", "payment_method_status": null, "updated": "2024-05-21T13:43:09.865Z", "frm_metadata": null } ``` - Create Payment Using Mandate: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 400, "currency": "USD", "confirm": true, "customer_id": "tester123", "mandate_id": "man_SJ0R3Dx1krNV2OYYXqK8", "off_session": true }' ``` Response: ``` { "payment_id": "pay_BYA7GLOyizx2lXr7HY8l", "merchant_id": "merchant_1709720492", "status": "succeeded", "amount": 400, "net_amount": 400, "amount_capturable": 0, "amount_received": 400, "connector": "authorizedotnet", "client_secret": "pay_BYA7GLOyizx2lXr7HY8l_secret_eyykmbXcMfPnc4m9Vbid", "created": "2024-05-21T13:47:00.958Z", "currency": "USD", "customer_id": "tester123", "customer": { "id": "tester123", "name": null, "email": "johndoe@gmail.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": "man_SJ0R3Dx1krNV2OYYXqK8", "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "07", "card_exp_year": "26", "card_holder_name": "Joseph Does", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "3906c467-f517-40a1-bb0f-a10c4e6f9878", "shipping": null, "billing": null, "order_details": null, "email": "johndoe@gmail.com", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "tester123", "created_at": 1716299220, "expires": 1716302820, "secret": "epk_866be4c4a3de481b808853b80a5c5198" }, "manual_retry_allowed": false, "connector_transaction_id": "80018772612", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80018772612", "payment_link": null, "profile_id": "pro_4aXJeUeyy9BzdhcV9Xue", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-21T14:02:00.957Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_eAcvFw4WhUlfAGyeya52", "payment_method_status": "active", "updated": "2024-05-21T13:47:03.437Z", "frm_metadata": null } ```
[ "crates/router/src/connector/authorizedotnet.rs", "crates/router/src/connector/authorizedotnet/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4700
Bug: [FEATURE] Constraint Graph visualization (via GraphViz) functionality ### Feature Description It would be good for developers to be able to visualize constraint graphs for intuition and debugging purposes. This can be done by allowing the constraint graph to describe its structure in the form of a DOT program, which can then be visualized using GraphViz. ### Possible Implementation The idea is to use a Rust crate that allows us to take any constraint graph and convert its edges and nodes into a GraphViz Digraph in the DOT DSL which can then be used to generate a diagram using any DOT-compatible CLI/UI tool. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index abc265ad692..3f9bd9a6303 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2617,6 +2617,21 @@ dependencies = [ "const-random", ] +[[package]] +name = "dot-generator" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aaac7ada45f71873ebce336491d1c1bc4a7c8042c7cea978168ad59e805b871" +dependencies = [ + "dot-structures", +] + +[[package]] +name = "dot-structures" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "675e35c02a51bb4d4618cb4885b3839ce6d1787c97b664474d9208d074742e20" + [[package]] name = "dotenvy" version = "0.15.7" @@ -3252,6 +3267,22 @@ dependencies = [ "walkdir", ] +[[package]] +name = "graphviz-rust" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27dafd1ac303e0dfb347a3861d9ac440859bab26ec2f534bbceb262ea492a1e0" +dependencies = [ + "dot-generator", + "dot-structures", + "into-attr", + "into-attr-derive", + "pest", + "pest_derive", + "rand", + "tempfile", +] + [[package]] name = "h2" version = "0.3.25" @@ -3623,6 +3654,7 @@ name = "hyperswitch_constraint_graph" version = "0.1.0" dependencies = [ "erased-serde 0.3.31", + "graphviz-rust", "rustc-hash", "serde", "serde_json", @@ -3773,6 +3805,28 @@ dependencies = [ "cfg-if 1.0.0", ] +[[package]] +name = "into-attr" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18b48c537e49a709e678caec3753a7dba6854661a1eaa27675024283b3f8b376" +dependencies = [ + "dot-structures", +] + +[[package]] +name = "into-attr-derive" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecac7c1ae6cd2c6a3a64d1061a8bdc7f52ff62c26a831a2301e54c1b5d70d5b1" +dependencies = [ + "dot-generator", + "dot-structures", + "into-attr", + "quote", + "syn 1.0.109", +] + [[package]] name = "iovec" version = "0.1.4" diff --git a/crates/euclid/Cargo.toml b/crates/euclid/Cargo.toml index 3341746ab74..b408c013572 100644 --- a/crates/euclid/Cargo.toml +++ b/crates/euclid/Cargo.toml @@ -21,7 +21,7 @@ utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order # First party dependencies common_enums = { version = "0.1.0", path = "../common_enums" } -hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } +hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph", features = ["viz"] } euclid_macros = { version = "0.1.0", path = "../euclid_macros" } [features] diff --git a/crates/euclid/src/dssa/graph.rs b/crates/euclid/src/dssa/graph.rs index 0ffafe4d48b..1c476ee81b2 100644 --- a/crates/euclid/src/dssa/graph.rs +++ b/crates/euclid/src/dssa/graph.rs @@ -22,6 +22,12 @@ pub mod euclid_graph_prelude { impl cgraph::KeyNode for dir::DirKey {} +impl cgraph::NodeViz for dir::DirKey { + fn viz(&self) -> String { + self.kind.to_string() + } +} + impl cgraph::ValueNode for dir::DirValue { type Key = dir::DirKey; @@ -30,6 +36,41 @@ impl cgraph::ValueNode for dir::DirValue { } } +impl cgraph::NodeViz for dir::DirValue { + fn viz(&self) -> String { + match self { + Self::PaymentMethod(pm) => pm.to_string(), + Self::CardBin(bin) => bin.value.clone(), + Self::CardType(ct) => ct.to_string(), + Self::CardNetwork(cn) => cn.to_string(), + Self::PayLaterType(plt) => plt.to_string(), + Self::WalletType(wt) => wt.to_string(), + Self::UpiType(ut) => ut.to_string(), + Self::BankTransferType(btt) => btt.to_string(), + Self::BankRedirectType(brt) => brt.to_string(), + Self::BankDebitType(bdt) => bdt.to_string(), + Self::CryptoType(ct) => ct.to_string(), + Self::RewardType(rt) => rt.to_string(), + Self::PaymentAmount(amt) => amt.number.to_string(), + Self::PaymentCurrency(curr) => curr.to_string(), + Self::AuthenticationType(at) => at.to_string(), + Self::CaptureMethod(cm) => cm.to_string(), + Self::BusinessCountry(bc) => bc.to_string(), + Self::BillingCountry(bc) => bc.to_string(), + Self::Connector(conn) => conn.connector.to_string(), + Self::MetaData(mv) => format!("[{} = {}]", mv.key, mv.value), + Self::MandateAcceptanceType(mat) => mat.to_string(), + Self::MandateType(mt) => mt.to_string(), + Self::PaymentType(pt) => pt.to_string(), + Self::VoucherType(vt) => vt.to_string(), + Self::GiftCardType(gct) => gct.to_string(), + Self::BusinessLabel(bl) => bl.value.to_string(), + Self::SetupFutureUsage(sfu) => sfu.to_string(), + Self::CardRedirectType(crt) => crt.to_string(), + } + } +} + #[derive(Debug, Clone, serde::Serialize)] #[serde(tag = "type", content = "details", rename_all = "snake_case")] pub enum AnalysisError<V: cgraph::ValueNode> { diff --git a/crates/euclid/src/frontend/dir.rs b/crates/euclid/src/frontend/dir.rs index 455330fcf76..bc16057fbb5 100644 --- a/crates/euclid/src/frontend/dir.rs +++ b/crates/euclid/src/frontend/dir.rs @@ -289,7 +289,6 @@ pub enum DirKeyKind { #[serde(rename = "billing_country")] BillingCountry, #[serde(skip_deserializing, rename = "connector")] - #[strum(disabled)] Connector, #[strum( serialize = "business_label", diff --git a/crates/hyperswitch_constraint_graph/Cargo.toml b/crates/hyperswitch_constraint_graph/Cargo.toml index 425855a05b0..4fe97b2b1ac 100644 --- a/crates/hyperswitch_constraint_graph/Cargo.toml +++ b/crates/hyperswitch_constraint_graph/Cargo.toml @@ -7,8 +7,12 @@ rust-version.workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[features] +viz = ["dep:graphviz-rust"] + [dependencies] erased-serde = "0.3.28" +graphviz-rust = { version = "0.6.2", optional = true } rustc-hash = "1.1.0" serde = { version = "1.0.163", features = ["derive", "rc"] } serde_json = "1.0.96" diff --git a/crates/hyperswitch_constraint_graph/src/graph.rs b/crates/hyperswitch_constraint_graph/src/graph.rs index d0a98e19520..6aed505728e 100644 --- a/crates/hyperswitch_constraint_graph/src/graph.rs +++ b/crates/hyperswitch_constraint_graph/src/graph.rs @@ -585,3 +585,92 @@ where Ok(node_builder.build()) } } + +#[cfg(feature = "viz")] +mod viz { + use graphviz_rust::{ + dot_generator::*, + dot_structures::*, + printer::{DotPrinter, PrinterContext}, + }; + + use crate::{dense_map::EntityId, types, ConstraintGraph, NodeViz, ValueNode}; + + fn get_node_id(node_id: types::NodeId) -> String { + format!("N{}", node_id.get_id()) + } + + impl<'a, V> ConstraintGraph<'a, V> + where + V: ValueNode + NodeViz, + <V as ValueNode>::Key: NodeViz, + { + fn get_node_label(node: &types::Node<V>) -> String { + let label = match &node.node_type { + types::NodeType::Value(types::NodeValue::Key(key)) => format!("any {}", key.viz()), + types::NodeType::Value(types::NodeValue::Value(val)) => { + format!("{} = {}", val.get_key().viz(), val.viz()) + } + types::NodeType::AllAggregator => "&&".to_string(), + types::NodeType::AnyAggregator => "| |".to_string(), + types::NodeType::InAggregator(agg) => { + let key = if let Some(val) = agg.iter().next() { + val.get_key().viz() + } else { + return "empty in".to_string(); + }; + + let nodes = agg.iter().map(NodeViz::viz).collect::<Vec<_>>(); + format!("{key} in [{}]", nodes.join(", ")) + } + }; + + format!("\"{label}\"") + } + + fn build_node(cg_node_id: types::NodeId, cg_node: &types::Node<V>) -> Node { + let viz_node_id = get_node_id(cg_node_id); + let viz_node_label = Self::get_node_label(cg_node); + + node!(viz_node_id; attr!("label", viz_node_label)) + } + + fn build_edge(cg_edge: &types::Edge) -> Edge { + let pred_vertex = get_node_id(cg_edge.pred); + let succ_vertex = get_node_id(cg_edge.succ); + let arrowhead = match cg_edge.strength { + types::Strength::Weak => "onormal", + types::Strength::Normal => "normal", + types::Strength::Strong => "normalnormal", + }; + let color = match cg_edge.relation { + types::Relation::Positive => "blue", + types::Relation::Negative => "red", + }; + + edge!( + node_id!(pred_vertex) => node_id!(succ_vertex); + attr!("arrowhead", arrowhead), + attr!("color", color) + ) + } + + pub fn get_viz_digraph(&self) -> Graph { + graph!( + strict di id!("constraint_graph"), + self.nodes + .iter() + .map(|(node_id, node)| Self::build_node(node_id, node)) + .map(Stmt::Node) + .chain(self.edges.values().map(Self::build_edge).map(Stmt::Edge)) + .collect::<Vec<_>>() + ) + } + + pub fn get_viz_digraph_string(&self) -> String { + let mut ctx = PrinterContext::default(); + let digraph = self.get_viz_digraph(); + digraph.print(&mut ctx) + } + } +} diff --git a/crates/hyperswitch_constraint_graph/src/lib.rs b/crates/hyperswitch_constraint_graph/src/lib.rs index ade9a64272f..6877169732c 100644 --- a/crates/hyperswitch_constraint_graph/src/lib.rs +++ b/crates/hyperswitch_constraint_graph/src/lib.rs @@ -7,6 +7,8 @@ pub mod types; pub use builder::ConstraintGraphBuilder; pub use error::{AnalysisTrace, GraphError}; pub use graph::ConstraintGraph; +#[cfg(feature = "viz")] +pub use types::NodeViz; pub use types::{ CheckingContext, CycleCheck, DomainId, DomainIdentifier, Edge, EdgeId, KeyNode, Memoization, Node, NodeId, NodeValue, Relation, Strength, ValueNode, diff --git a/crates/hyperswitch_constraint_graph/src/types.rs b/crates/hyperswitch_constraint_graph/src/types.rs index d1d14bd7e5c..51818f2fee5 100644 --- a/crates/hyperswitch_constraint_graph/src/types.rs +++ b/crates/hyperswitch_constraint_graph/src/types.rs @@ -17,6 +17,11 @@ pub trait ValueNode: fmt::Debug + Clone + hash::Hash + serde::Serialize + Partia fn get_key(&self) -> Self::Key; } +#[cfg(feature = "viz")] +pub trait NodeViz { + fn viz(&self) -> String; +} + #[derive(Debug, Clone, Copy, serde::Serialize, PartialEq, Eq, Hash)] #[serde(transparent)] pub struct NodeId(usize); diff --git a/crates/kgraph_utils/Cargo.toml b/crates/kgraph_utils/Cargo.toml index 86de6002c32..2f570fcac57 100644 --- a/crates/kgraph_utils/Cargo.toml +++ b/crates/kgraph_utils/Cargo.toml @@ -13,7 +13,7 @@ connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connect [dependencies] api_models = { version = "0.1.0", path = "../api_models", package = "api_models" } common_enums = { version = "0.1.0", path = "../common_enums" } -hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } +hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph", features = ["viz"] } euclid = { version = "0.1.0", path = "../euclid" } masking = { version = "0.1.0", path = "../masking/" }
2024-05-20T09:56:07Z
## Description <!-- Describe your changes in detail --> This PR adds functionality to the constraint graph that allows the graph to describe its structure by generating a DOT program, which can then be visualized by the user through GraphViz. ### 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). --> Being able to visualize a constraint graph would aid with intuition and debugging. ## 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)? --> compiler guided. No API tests required since this is purely a developer-focused feature and does not touch any business logic code.
be9343affeb178e646d4046785a105a9c6040037
compiler guided. No API tests required since this is purely a developer-focused feature and does not touch any business logic code.
[ "Cargo.lock", "crates/euclid/Cargo.toml", "crates/euclid/src/dssa/graph.rs", "crates/euclid/src/frontend/dir.rs", "crates/hyperswitch_constraint_graph/Cargo.toml", "crates/hyperswitch_constraint_graph/src/graph.rs", "crates/hyperswitch_constraint_graph/src/lib.rs", "crates/hyperswitch_constraint_graph...
juspay/hyperswitch
juspay__hyperswitch-4698
Bug: [FEATURE]: Add Session token flow for Paypal Sdk ### Feature Description Add Session token flow for Paypal Sdk ### Possible Implementation - Accept data in `metadata` field of the MCA - create call - Return that data in the sessions call - Change payment_experience for paypal via paypal to sdk ### 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 f0ce3839fce..5f9618738b2 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -2939,13 +2939,17 @@ pub enum NextActionType { #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow - RedirectToUrl { redirect_to_url: String }, + RedirectToUrl { + redirect_to_url: String, + }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response - ThirdPartySdkSessionToken { session_token: Option<SessionToken> }, + ThirdPartySdkSessionToken { + session_token: Option<SessionToken>, + }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] @@ -2967,7 +2971,12 @@ pub enum NextActionData { display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows - ThreeDsInvoke { three_ds_data: ThreeDsData }, + ThreeDsInvoke { + three_ds_data: ThreeDsData, + }, + InvokeSdkClient { + next_action_data: SdkNextActionData, + }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] @@ -3030,6 +3039,12 @@ pub enum QrCodeInformation { }, } +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] +#[serde(rename_all = "snake_case")] +pub struct SdkNextActionData { + pub next_action: NextActionCall, +} + #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer @@ -4030,6 +4045,17 @@ pub struct GpaySessionTokenData { pub data: GpayMetaData, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaypalSdkMetaData { + pub client_id: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaypalSdkSessionTokenData { + #[serde(rename = "paypal_sdk")] + pub data: PaypalSdkMetaData, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { @@ -4207,8 +4233,12 @@ pub struct KlarnaSessionTokenResponse { #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { + /// Name of the connector + pub connector: String, /// The session token for PayPal pub session_token: String, + /// The next action for the sdk (ex: calling confirm or sync call) + pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] @@ -4238,13 +4268,15 @@ pub struct SdkNextAction { pub next_action: NextActionCall, } -#[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] +#[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is confirm Confirm, /// The next action call is sync Sync, + /// The next action call is Complete Authorize + CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] diff --git a/crates/connector_configs/src/common_config.rs b/crates/connector_configs/src/common_config.rs index b11a74a3ca6..fff210b6e4d 100644 --- a/crates/connector_configs/src/common_config.rs +++ b/crates/connector_configs/src/common_config.rs @@ -54,6 +54,12 @@ pub enum GooglePayData { Zen(ZenGooglePay), } +#[serde_with::skip_serializing_none] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaypalSdkData { + pub client_id: Option<String>, +} + #[serde_with::skip_serializing_none] #[derive(Debug, Deserialize, serde::Serialize, Clone)] #[serde(untagged)] @@ -79,6 +85,7 @@ pub struct ApiModelMetaData { pub terminal_id: Option<String>, pub merchant_id: Option<String>, pub google_pay: Option<GoogleApiModelData>, + pub paypal_sdk: Option<PaypalSdkData>, pub apple_pay: Option<ApplePayData>, pub apple_pay_combined: Option<ApplePayData>, pub endpoint_prefix: Option<String>, @@ -180,6 +187,7 @@ pub struct DashboardMetaData { pub terminal_id: Option<String>, pub merchant_id: Option<String>, pub google_pay: Option<GooglePayData>, + pub paypal_sdk: Option<PaypalSdkData>, pub apple_pay: Option<ApplePayData>, pub apple_pay_combined: Option<ApplePayData>, pub endpoint_prefix: Option<String>, diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index e1d55e39385..7118c87b092 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -10,7 +10,7 @@ use serde::Deserialize; #[cfg(any(feature = "sandbox", feature = "development", feature = "production"))] use toml; -use crate::common_config::{CardProvider, GooglePayData, Provider, ZenApplePay}; +use crate::common_config::{CardProvider, GooglePayData, PaypalSdkData, Provider, ZenApplePay}; #[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct Classic { @@ -79,6 +79,7 @@ pub struct ConfigMetadata { pub account_name: Option<String>, pub terminal_id: Option<String>, pub google_pay: Option<GooglePayData>, + pub paypal_sdk: Option<PaypalSdkData>, pub apple_pay: Option<ApplePayTomlConfig>, pub merchant_id: Option<String>, pub endpoint_prefix: Option<String>, diff --git a/crates/connector_configs/src/response_modifier.rs b/crates/connector_configs/src/response_modifier.rs index 8f7da58c4dc..ebf97d83162 100644 --- a/crates/connector_configs/src/response_modifier.rs +++ b/crates/connector_configs/src/response_modifier.rs @@ -309,6 +309,7 @@ impl From<ApiModelMetaData> for DashboardMetaData { terminal_id: api_model.terminal_id, merchant_id: api_model.merchant_id, google_pay: get_google_pay_metadata_response(api_model.google_pay), + paypal_sdk: api_model.paypal_sdk, apple_pay: api_model.apple_pay, apple_pay_combined: api_model.apple_pay_combined, endpoint_prefix: api_model.endpoint_prefix, diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs index 01332c9d29e..ae4b0206767 100644 --- a/crates/connector_configs/src/transformer.rs +++ b/crates/connector_configs/src/transformer.rs @@ -46,7 +46,9 @@ impl DashboardRequestPayload { (Connector::Zen, GooglePay) | (Connector::Zen, ApplePay) => { Some(api_models::enums::PaymentExperience::RedirectToUrl) } - (Connector::Braintree, Paypal) | (Connector::Klarna, Klarna) => { + (Connector::Paypal, Paypal) + | (Connector::Braintree, Paypal) + | (Connector::Klarna, Klarna) => { Some(api_models::enums::PaymentExperience::InvokeSdkClient) } (Connector::Globepay, AliPay) @@ -194,6 +196,7 @@ impl DashboardRequestPayload { three_ds_requestor_name: None, three_ds_requestor_id: None, pull_mechanism_for_external_3ds_enabled: None, + paypal_sdk: None, }; let meta_data = match request.metadata { Some(data) => data, @@ -205,6 +208,7 @@ impl DashboardRequestPayload { let merchant_id = meta_data.merchant_id.clone(); let terminal_id = meta_data.terminal_id.clone(); let endpoint_prefix = meta_data.endpoint_prefix.clone(); + let paypal_sdk = meta_data.paypal_sdk; let apple_pay = meta_data.apple_pay; let apple_pay_combined = meta_data.apple_pay_combined; let merchant_config_currency = meta_data.merchant_config_currency; @@ -228,6 +232,7 @@ impl DashboardRequestPayload { merchant_config_currency, apple_pay_combined, endpoint_prefix, + paypal_sdk, mcc, merchant_country_code, merchant_name, diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index d9e7ec58f75..fcccf9c7e28 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -1645,6 +1645,8 @@ api_key="Client Secret" key1="Client ID" [paypal.connector_webhook_details] merchant_secret="Source verification key" +[paypal.metadata.paypal_sdk] +client_id="Client ID" [paypal_payout] [[paypal.wallet]] diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 202bce64c1f..96fba850e7e 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -1265,6 +1265,8 @@ api_key="Client Secret" key1="Client ID" [paypal.connector_webhook_details] merchant_secret="Source verification key" +[paypal.metadata.paypal_sdk] +client_id="Client ID" [payu] [[payu.credit]] diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 450e14d1080..932352f20e4 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -1645,6 +1645,8 @@ api_key="Client Secret" key1="Client ID" [paypal.connector_webhook_details] merchant_secret="Source verification key" +[paypal.metadata.paypal_sdk] +client_id="Client ID" [paypal_payout] [[paypal.wallet]] diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 8830c689937..c67ea2d2746 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -367,6 +367,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::ApplepaySessionTokenResponse, api_models::payments::SdkNextAction, api_models::payments::NextActionCall, + api_models::payments::SdkNextActionData, api_models::payments::SamsungPayWalletData, api_models::payments::WeChatPay, api_models::payments::GpayTokenizationData, diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index d615acff1ca..5e8c9ea08c0 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -823,6 +823,9 @@ pub enum StripeNextAction { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, + InvokeSdkClient { + next_action_data: payments::SdkNextActionData, + }, } pub(crate) fn into_stripe_next_action( @@ -871,6 +874,9 @@ pub(crate) fn into_stripe_next_action( url: None, }, }, + payments::NextActionData::InvokeSdkClient { next_action_data } => { + StripeNextAction::InvokeSdkClient { next_action_data } + } }) } diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 03335d42722..bbcafb65e9f 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -389,6 +389,9 @@ pub enum StripeNextAction { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, + InvokeSdkClient { + next_action_data: payments::SdkNextActionData, + }, } pub(crate) fn into_stripe_next_action( @@ -437,6 +440,9 @@ pub(crate) fn into_stripe_next_action( url: None, }, }, + payments::NextActionData::InvokeSdkClient { next_action_data } => { + StripeNextAction::InvokeSdkClient { next_action_data } + } }) } diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 1fe86a209e3..0405f318071 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -7914,6 +7914,170 @@ impl Default for super::settings::RequiredFields { ]), }, ), + ( + // Added shipping fields for the SDK flow to accept it from wallet directly, + // this won't show up in SDK in payment's sheet but will be used in the background + enums::PaymentMethodType::Paypal, + ConnectorFields { + fields: HashMap::from([ + ( + enums::Connector::Braintree, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::from([ + ( + "shipping.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.first_name".to_string(), + display_name: "shipping_first_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.last_name".to_string(), + display_name: "shipping_last_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.city".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::UserShippingAddressCity, + value: None, + } + ), + ( + "shipping.address.state".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.state".to_string(), + display_name: "state".to_string(), + field_type: enums::FieldType::UserShippingAddressState, + value: None, + } + ), + ( + "shipping.address.zip".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::UserShippingAddressPincode, + value: None, + } + ), + ( + "shipping.address.country".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserShippingAddressCountry{ + options: vec![ + "ALL".to_string(), + ] + }, + value: None, + } + ), + ( + "shipping.address.line1".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::UserShippingAddressLine1, + value: None, + } + ), + ]), + } + ), + ( + enums::Connector::Paypal, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new( + ), + common: HashMap::from( + [ + ( + "shipping.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.first_name".to_string(), + display_name: "shipping_first_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.last_name".to_string(), + display_name: "shipping_last_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.city".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::UserShippingAddressCity, + value: None, + } + ), + ( + "shipping.address.state".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.state".to_string(), + display_name: "state".to_string(), + field_type: enums::FieldType::UserShippingAddressState, + value: None, + } + ), + ( + "shipping.address.zip".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::UserShippingAddressPincode, + value: None, + } + ), + ( + "shipping.address.country".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserShippingAddressCountry{ + options: vec![ + "ALL".to_string(), + ] + }, + value: None, + } + ), + ( + "shipping.address.line1".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::UserShippingAddressLine1, + value: None, + } + ), + ] + ), + } + ), + ]), + }, + ), ])), ), ( diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index a939f0a83f7..136782cab6e 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -308,6 +308,10 @@ impl<F, T> session_token: api::SessionToken::Paypal(Box::new( payments::PaypalSessionTokenResponse { session_token: item.response.client_token.value.expose(), + connector: "braintree".to_string(), + sdk_next_action: payments::SdkNextAction { + next_action: payments::NextActionCall::Confirm, + }, }, )), }), diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index 9ff6b84a064..9e7b208ef70 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -34,7 +34,7 @@ use crate::{ self, api::{self, CompleteAuthorize, ConnectorCommon, ConnectorCommonExt, VerifyWebhookSource}, storage::enums as storage_enums, - transformers::ForeignFrom, + transformers::{ForeignFrom, ForeignTryFrom}, ConnectorAuthType, ErrorResponse, Response, }, utils::BytesExt, @@ -629,7 +629,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P res.response .parse_struct("paypal PaypalAuthResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - + let payment_method_data = data.request.payment_method_data.clone(); match response { PaypalAuthResponse::PaypalOrdersResponse(response) => { event_builder.map(|i| i.set_response_body(&response)); @@ -644,11 +644,14 @@ 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(), - http_code: res.status_code, - }) + types::RouterData::foreign_try_from(( + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + payment_method_data, + )) } PaypalAuthResponse::PaypalThreeDsResponse(response) => { event_builder.map(|i| i.set_response_body(&response)); @@ -1033,11 +1036,14 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .change_context(errors::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, - }) + types::RouterData::foreign_try_from(( + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + data.request.payment_experience, + )) } fn get_error_response( diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 0ea1331c448..d240c1b05e0 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -18,7 +18,9 @@ use crate::{ core::errors, services, types::{ - self, api, domain, storage::enums as storage_enums, transformers::ForeignFrom, + self, api, domain, + storage::enums as storage_enums, + transformers::{ForeignFrom, ForeignTryFrom}, ConnectorAuthType, VerifyWebhookSourceResponseData, }, }; @@ -387,28 +389,33 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP let paypal_auth: PaypalAuthType = PaypalAuthType::try_from(&item.router_data.connector_auth_type)?; let payee = get_payee(&paypal_auth); + + let amount = OrderRequestAmount::from(item); + + let intent = if item.router_data.request.is_auto_capture()? { + PaypalPaymentIntent::Capture + } else { + PaypalPaymentIntent::Authorize + }; + + let connector_request_reference_id = + item.router_data.connector_request_reference_id.clone(); + + let shipping_address = ShippingAddress::try_from(item)?; + let item_details = vec![ItemDetails::from(item)]; + + let purchase_units = vec![PurchaseUnitRequest { + reference_id: Some(connector_request_reference_id.clone()), + custom_id: Some(connector_request_reference_id.clone()), + invoice_id: Some(connector_request_reference_id), + amount, + payee, + shipping: Some(shipping_address), + items: item_details, + }]; + match item.router_data.request.payment_method_data { domain::PaymentMethodData::Card(ref ccard) => { - let intent = if item.router_data.request.is_auto_capture()? { - PaypalPaymentIntent::Capture - } else { - PaypalPaymentIntent::Authorize - }; - let amount = OrderRequestAmount::from(item); - let connector_request_reference_id = - item.router_data.connector_request_reference_id.clone(); - let shipping_address = ShippingAddress::try_from(item)?; - let item_details = vec![ItemDetails::from(item)]; - - let purchase_units = vec![PurchaseUnitRequest { - reference_id: Some(connector_request_reference_id.clone()), - custom_id: Some(connector_request_reference_id.clone()), - invoice_id: Some(connector_request_reference_id), - amount, - payee, - shipping: Some(shipping_address), - items: item_details, - }]; let card = item.router_data.request.get_card()?; let expiry = Some(card.get_expiry_date_as_yyyymm("-")); @@ -441,27 +448,6 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP } domain::PaymentMethodData::Wallet(ref wallet_data) => match wallet_data { domain::WalletData::PaypalRedirect(_) => { - let intent = if item.router_data.request.is_auto_capture()? { - PaypalPaymentIntent::Capture - } else { - PaypalPaymentIntent::Authorize - }; - let amount = OrderRequestAmount::from(item); - - let connector_req_reference_id = - item.router_data.connector_request_reference_id.clone(); - let shipping_address = ShippingAddress::try_from(item)?; - let item_details = vec![ItemDetails::from(item)]; - - let purchase_units = vec![PurchaseUnitRequest { - reference_id: Some(connector_req_reference_id.clone()), - custom_id: Some(connector_req_reference_id.clone()), - invoice_id: Some(connector_req_reference_id), - amount, - payee, - shipping: Some(shipping_address), - items: item_details, - }]; let payment_source = Some(PaymentSourceItem::Paypal(PaypalRedirectionRequest { experience_context: ContextStruct { @@ -486,6 +472,23 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP payment_source, }) } + domain::WalletData::PaypalSdk(_) => { + let payment_source = + Some(PaymentSourceItem::Paypal(PaypalRedirectionRequest { + experience_context: ContextStruct { + return_url: None, + cancel_url: None, + shipping_preference: ShippingPreference::GetFromFile, + user_action: Some(UserAction::PayNow), + }, + })); + + Ok(Self { + intent, + purchase_units, + payment_source, + }) + } domain::WalletData::AliPayQr(_) | domain::WalletData::AliPayRedirect(_) | domain::WalletData::AliPayHkRedirect(_) @@ -502,7 +505,6 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP | domain::WalletData::GooglePayThirdPartySdk(_) | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) - | domain::WalletData::PaypalSdk(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -515,7 +517,7 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP ))?, }, domain::PaymentMethodData::BankRedirect(ref bank_redirection_data) => { - let intent = if item.router_data.request.is_auto_capture()? { + let bank_redirect_intent = if item.router_data.request.is_auto_capture()? { PaypalPaymentIntent::Capture } else { Err(errors::ConnectorError::FlowNotSupported { @@ -523,26 +525,12 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP connector: "Paypal".to_string(), })? }; - let amount = OrderRequestAmount::from(item); - let connector_req_reference_id = - item.router_data.connector_request_reference_id.clone(); - let shipping_address = ShippingAddress::try_from(item)?; - let item_details = vec![ItemDetails::from(item)]; - - let purchase_units = vec![PurchaseUnitRequest { - reference_id: Some(connector_req_reference_id.clone()), - custom_id: Some(connector_req_reference_id.clone()), - invoice_id: Some(connector_req_reference_id), - amount, - payee, - shipping: Some(shipping_address), - items: item_details, - }]; + let payment_source = Some(get_payment_source(item.router_data, bank_redirection_data)?); Ok(Self { - intent, + intent: bank_redirect_intent, purchase_units, payment_source, }) @@ -1060,6 +1048,7 @@ pub struct PaypalMeta { pub authorize_id: Option<String>, pub capture_id: Option<String>, pub psync_flow: PaypalPaymentIntent, + pub next_action: Option<api_models::payments::NextActionCall>, } fn get_id_based_on_intent( @@ -1112,7 +1101,8 @@ impl<F, T> serde_json::json!(PaypalMeta { authorize_id: None, capture_id: Some(id), - psync_flow: item.response.intent.clone() + psync_flow: item.response.intent.clone(), + next_action: None, }), types::ResponseId::ConnectorTransactionId(item.response.id.clone()), ), @@ -1121,7 +1111,8 @@ impl<F, T> serde_json::json!(PaypalMeta { authorize_id: Some(id), capture_id: None, - psync_flow: item.response.intent.clone() + psync_flow: item.response.intent.clone(), + next_action: None, }), types::ResponseId::ConnectorTransactionId(item.response.id.clone()), ), @@ -1183,23 +1174,27 @@ fn get_redirect_url( } impl<F> - TryFrom< + ForeignTryFrom<( types::ResponseRouterData< F, PaypalSyncResponse, types::PaymentsSyncData, types::PaymentsResponseData, >, - > for types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData> + Option<common_enums::PaymentExperience>, + )> for types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: types::ResponseRouterData< - F, - PaypalSyncResponse, - types::PaymentsSyncData, - types::PaymentsResponseData, - >, + fn foreign_try_from( + (item, payment_experience): ( + types::ResponseRouterData< + F, + PaypalSyncResponse, + types::PaymentsSyncData, + types::PaymentsResponseData, + >, + Option<common_enums::PaymentExperience>, + ), ) -> Result<Self, Self::Error> { match item.response { PaypalSyncResponse::PaypalOrdersSyncResponse(response) => { @@ -1209,13 +1204,14 @@ impl<F> http_code: item.http_code, }) } - PaypalSyncResponse::PaypalRedirectSyncResponse(response) => { - Self::try_from(types::ResponseRouterData { + PaypalSyncResponse::PaypalRedirectSyncResponse(response) => Self::foreign_try_from(( + types::ResponseRouterData { response, data: item.data, http_code: item.http_code, - }) - } + }, + payment_experience, + )), PaypalSyncResponse::PaypalPaymentsSyncResponse(response) => { Self::try_from(types::ResponseRouterData { response, @@ -1235,25 +1231,96 @@ impl<F> } impl<F, T> - TryFrom<types::ResponseRouterData<F, PaypalRedirectResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> + ForeignTryFrom<( + types::ResponseRouterData<F, PaypalRedirectResponse, T, types::PaymentsResponseData>, + Option<common_enums::PaymentExperience>, + )> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: types::ResponseRouterData<F, PaypalRedirectResponse, T, types::PaymentsResponseData>, + fn foreign_try_from( + (item, payment_experience): ( + types::ResponseRouterData<F, PaypalRedirectResponse, T, types::PaymentsResponseData>, + Option<common_enums::PaymentExperience>, + ), ) -> Result<Self, Self::Error> { let status = storage_enums::AttemptStatus::foreign_from(( item.response.clone().status, item.response.intent.clone(), )); let link = get_redirect_url(item.response.links.clone())?; + + // For Paypal SDK flow, we need to trigger SDK client and then complete authorize + let next_action = + if let Some(common_enums::PaymentExperience::InvokeSdkClient) = payment_experience { + Some(api_models::payments::NextActionCall::CompleteAuthorize) + } else { + None + }; let connector_meta = serde_json::json!(PaypalMeta { authorize_id: None, capture_id: None, - psync_flow: item.response.intent + psync_flow: item.response.intent, + next_action, }); let purchase_units = item.response.purchase_units.first(); + Ok(Self { + status, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), + redirection_data: Some(services::RedirectForm::from(( + link.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?, + services::Method::Get, + ))), + mandate_reference: None, + connector_metadata: Some(connector_meta), + network_txn_id: None, + connector_response_reference_id: Some( + purchase_units.map_or(item.response.id, |item| item.invoice_id.clone()), + ), + incremental_authorization_allowed: None, + charge_id: None, + }), + ..item.data + }) + } +} +impl<F, T> + ForeignTryFrom<( + types::ResponseRouterData<F, PaypalRedirectResponse, T, types::PaymentsResponseData>, + domain::PaymentMethodData, + )> for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn foreign_try_from( + (item, payment_method_data): ( + types::ResponseRouterData<F, PaypalRedirectResponse, T, types::PaymentsResponseData>, + domain::PaymentMethodData, + ), + ) -> Result<Self, Self::Error> { + let status = storage_enums::AttemptStatus::foreign_from(( + item.response.clone().status, + item.response.intent.clone(), + )); + let link = get_redirect_url(item.response.links.clone())?; + + // For Paypal SDK flow, we need to trigger SDK client and then complete authorize + let next_action = + if let domain::PaymentMethodData::Wallet(domain::WalletData::PaypalSdk(_)) = + payment_method_data + { + Some(api_models::payments::NextActionCall::CompleteAuthorize) + } else { + None + }; + + let connector_meta = serde_json::json!(PaypalMeta { + authorize_id: None, + capture_id: None, + psync_flow: item.response.intent, + next_action, + }); + let purchase_units = item.response.purchase_units.first(); Ok(Self { status, response: Ok(types::PaymentsResponseData::TransactionResponse { @@ -1336,7 +1403,8 @@ impl<F> let connector_meta = serde_json::json!(PaypalMeta { authorize_id: None, capture_id: None, - psync_flow: PaypalPaymentIntent::Authenticate // when there is no capture or auth id present + psync_flow: PaypalPaymentIntent::Authenticate, // when there is no capture or auth id present + next_action: None, }); let status = storage_enums::AttemptStatus::foreign_from(( @@ -1755,7 +1823,8 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaypalCaptureResponse>> connector_metadata: Some(serde_json::json!(PaypalMeta { authorize_id: connector_payment_id.authorize_id, capture_id: Some(item.response.id.clone()), - psync_flow: PaypalPaymentIntent::Capture + psync_flow: PaypalPaymentIntent::Capture, + next_action: None, })), network_txn_id: None, connector_response_reference_id: item diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index f760e907288..a39f0deb3ca 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1012,6 +1012,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { api_models::payments::NextActionData::DisplayVoucherInformation{ .. } => None, api_models::payments::NextActionData::WaitScreenInformation{..} => None, api_models::payments::NextActionData::ThreeDsInvoke{..} => None, + api_models::payments::NextActionData::InvokeSdkClient{..} => None, }) .ok_or(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 76ff96c7021..c74ed4bae15 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -634,6 +634,42 @@ where ) -> RouterResult<Self>; } +fn create_paypal_sdk_session_token( + _state: &routes::AppState, + router_data: &types::PaymentsSessionRouterData, + connector: &api::ConnectorData, + _business_profile: &storage::business_profile::BusinessProfile, +) -> RouterResult<types::PaymentsSessionRouterData> { + let connector_metadata = router_data.connector_meta_data.clone(); + + let paypal_sdk_data = connector_metadata + .clone() + .parse_value::<payment_types::PaypalSdkSessionTokenData>("PaypalSdkSessionTokenData") + .change_context(errors::ConnectorError::NoConnectorMetaData) + .attach_printable(format!( + "cannot parse paypal_sdk metadata from the given value {connector_metadata:?}" + )) + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "connector_metadata".to_string(), + expected_format: "paypal_sdk_metadata_format".to_string(), + })?; + + Ok(types::PaymentsSessionRouterData { + response: Ok(types::PaymentsResponseData::SessionResponse { + session_token: payment_types::SessionToken::Paypal(Box::new( + payment_types::PaypalSessionTokenResponse { + connector: connector.connector_name.to_string(), + session_token: paypal_sdk_data.data.client_id, + sdk_next_action: payment_types::SdkNextAction { + next_action: payment_types::NextActionCall::Confirm, + }, + }, + )), + }), + ..router_data.clone() + }) +} + #[async_trait] impl RouterDataSession for types::PaymentsSessionRouterData { async fn decide_flow<'a, 'b>( @@ -651,6 +687,9 @@ impl RouterDataSession for types::PaymentsSessionRouterData { api::GetToken::ApplePayMetadata => { create_applepay_session_token(state, self, connector, business_profile).await } + api::GetToken::PaypalSdkMetadata => { + create_paypal_sdk_session_token(state, self, connector, business_profile) + } api::GetToken::Connector => { let connector_integration: services::BoxedConnectorIntegration< '_, diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index e4d91d4a068..2aa01cd587f 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -471,6 +471,7 @@ impl From<api_models::enums::PaymentMethodType> for api::GetToken { match value { api_models::enums::PaymentMethodType::GooglePay => Self::GpayMetadata, api_models::enums::PaymentMethodType::ApplePay => Self::ApplePayMetadata, + api_models::enums::PaymentMethodType::Paypal => Self::PaypalSdkMetadata, _ => Self::Connector, } } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 11ce9cd7ede..7f6b0cc1f61 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -539,6 +539,8 @@ where let next_action_containing_qr_code_url = qr_code_next_steps_check(payment_attempt.clone())?; + let papal_sdk_next_action = paypal_sdk_next_steps_check(payment_attempt.clone())?; + let next_action_containing_wait_screen = wait_screen_next_steps_check(payment_attempt.clone())?; @@ -547,6 +549,7 @@ where || next_action_voucher.is_some() || next_action_containing_qr_code_url.is_some() || next_action_containing_wait_screen.is_some() + || papal_sdk_next_action.is_some() || payment_data.authentication.is_some() { next_action_response = bank_transfer_next_steps @@ -563,6 +566,11 @@ where .or(next_action_containing_qr_code_url.map(|qr_code_data| { api_models::payments::NextActionData::foreign_from(qr_code_data) })) + .or(papal_sdk_next_action.map(|paypal_next_action_data| { + api_models::payments::NextActionData::InvokeSdkClient{ + next_action_data: paypal_next_action_data + } + })) .or(next_action_containing_wait_screen.map(|wait_screen_data| { api_models::payments::NextActionData::WaitScreenInformation { display_from_timestamp: wait_screen_data.display_from_timestamp, @@ -875,6 +883,21 @@ pub fn qr_code_next_steps_check( let qr_code_instructions = qr_code_steps.transpose().ok().flatten(); Ok(qr_code_instructions) } +pub fn paypal_sdk_next_steps_check( + payment_attempt: storage::PaymentAttempt, +) -> RouterResult<Option<api_models::payments::SdkNextActionData>> { + let paypal_connector_metadata: Option<Result<api_models::payments::SdkNextActionData, _>> = + payment_attempt.connector_metadata.map(|metadata| { + metadata.parse_value("SdkNextActionData").map_err(|_| { + crate::logger::warn!( + "SdkNextActionData parsing failed for paypal_connector_metadata" + ) + }) + }); + + let paypal_next_steps = paypal_connector_metadata.transpose().ok().flatten(); + Ok(paypal_next_steps) +} pub fn wait_screen_next_steps_check( payment_attempt: storage::PaymentAttempt, @@ -1275,6 +1298,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData }, payment_method_type: payment_data.payment_attempt.payment_method_type, currency: payment_data.currency, + payment_experience: payment_data.payment_attempt.payment_experience, }) } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index e2f2f6c0b70..89c2629c105 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -466,6 +466,7 @@ pub struct PaymentsSyncData { pub mandate_id: Option<api_models::payments::MandateIds>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub currency: storage_enums::Currency, + pub payment_experience: Option<storage_enums::PaymentExperience>, } #[derive(Debug, Default, Clone)] diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 2013f482750..aea5e326cf7 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -217,6 +217,7 @@ type BoxedConnector = Box<&'static (dyn Connector + Sync)>; pub enum GetToken { GpayMetadata, ApplePayMetadata, + PaypalSdkMetadata, Connector, } diff --git a/crates/router/tests/connectors/bambora.rs b/crates/router/tests/connectors/bambora.rs index 3115c1143d7..d0bc77e7500 100644 --- a/crates/router/tests/connectors/bambora.rs +++ b/crates/router/tests/connectors/bambora.rs @@ -110,6 +110,7 @@ async fn should_sync_authorized_payment() { connector_meta: None, payment_method_type: None, currency: enums::Currency::USD, + payment_experience: None, }), None, ) @@ -226,6 +227,7 @@ async fn should_sync_auto_captured_payment() { connector_meta: None, payment_method_type: None, currency: enums::Currency::USD, + payment_experience: None, }), None, ) diff --git a/crates/router/tests/connectors/forte.rs b/crates/router/tests/connectors/forte.rs index d690524bd12..11153aa7088 100644 --- a/crates/router/tests/connectors/forte.rs +++ b/crates/router/tests/connectors/forte.rs @@ -159,6 +159,7 @@ async fn should_sync_authorized_payment() { mandate_id: None, payment_method_type: None, currency: enums::Currency::USD, + payment_experience: None, }), get_default_payment_info(), ) diff --git a/crates/router/tests/connectors/nexinets.rs b/crates/router/tests/connectors/nexinets.rs index cdf94113c5a..c6a14ac202f 100644 --- a/crates/router/tests/connectors/nexinets.rs +++ b/crates/router/tests/connectors/nexinets.rs @@ -126,6 +126,7 @@ async fn should_sync_authorized_payment() { mandate_id: None, payment_method_type: None, currency: enums::Currency::EUR, + payment_experience: None, }), None, ) diff --git a/crates/router/tests/connectors/paypal.rs b/crates/router/tests/connectors/paypal.rs index 704aeca5936..b53cf71acfd 100644 --- a/crates/router/tests/connectors/paypal.rs +++ b/crates/router/tests/connectors/paypal.rs @@ -143,6 +143,7 @@ async fn should_sync_authorized_payment() { connector_meta, payment_method_type: None, currency: enums::Currency::USD, + payment_experience: None, }), get_default_payment_info(), ) @@ -341,6 +342,7 @@ async fn should_sync_auto_captured_payment() { connector_meta, payment_method_type: None, currency: enums::Currency::USD, + payment_experience: None, }), get_default_payment_info(), ) diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 6718611b0c8..9955cb77df7 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -1002,6 +1002,7 @@ impl Default for PaymentSyncType { connector_meta: None, payment_method_type: None, currency: enums::Currency::USD, + payment_experience: None, }; Self(data) } diff --git a/crates/router/tests/connectors/zen.rs b/crates/router/tests/connectors/zen.rs index b11b78025d0..552edcaaf6f 100644 --- a/crates/router/tests/connectors/zen.rs +++ b/crates/router/tests/connectors/zen.rs @@ -105,6 +105,7 @@ async fn should_sync_authorized_payment() { mandate_id: None, payment_method_type: None, currency: enums::Currency::USD, + payment_experience: None, }), None, ) @@ -221,6 +222,7 @@ async fn should_sync_auto_captured_payment() { mandate_id: None, payment_method_type: None, currency: enums::Currency::USD, + payment_experience: None, }), None, ) diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 47da1ae1074..b87b516de28 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -11660,7 +11660,8 @@ "type": "string", "enum": [ "confirm", - "sync" + "sync", + "complete_authorize" ] }, "NextActionData": { @@ -11816,6 +11817,24 @@ ] } } + }, + { + "type": "object", + "required": [ + "next_action_data", + "type" + ], + "properties": { + "next_action_data": { + "$ref": "#/components/schemas/SdkNextActionData" + }, + "type": { + "type": "string", + "enum": [ + "invoke_sdk_client" + ] + } + } } ], "discriminator": { @@ -16780,12 +16799,21 @@ "PaypalSessionTokenResponse": { "type": "object", "required": [ - "session_token" + "connector", + "session_token", + "sdk_next_action" ], "properties": { + "connector": { + "type": "string", + "description": "Name of the connector" + }, "session_token": { "type": "string", "description": "The session token for PayPal" + }, + "sdk_next_action": { + "$ref": "#/components/schemas/SdkNextAction" } } }, @@ -18030,6 +18058,17 @@ } } }, + "SdkNextActionData": { + "type": "object", + "required": [ + "next_action" + ], + "properties": { + "next_action": { + "$ref": "#/components/schemas/NextActionCall" + } + } + }, "SecretInfoToInitiateSdk": { "type": "object", "required": [
2024-05-19T17:37:00Z
## Description <!-- Describe your changes in detail --> Add session_token flow to enable Paypal via Paypal SDK - Accept data in `metadata` field of the MCA - create call - Return that data in the sessions call - Change payment_experience for paypal via paypal to sdk ### 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). --> #4698 ## 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 Paypal MCA with payment_experience as `invoke_sdk_client` for Paypal Wallet ``` curl --location 'http://localhost:8080/account/merchant_1716757295/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "business_country": "US", "connector_name": "paypal", "connector_account_details": { "auth_type": "BodyKey", "api_key": "********************************", "key1": "ASK*****************************_2" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "paypal", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "paypal_sdk": { "client_id": "ASK****************************_2" } } }' ``` ### Payments Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_33Ad6faEcusLrqrqSeeFWyGRyTfOkKMoPMTSirAhCg0qqwkxQ25t7K1ucBEoq26M' \ --data-raw '{ "amount": 6100, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "amount_to_capture": 6100, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "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", "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" } } }' ``` ### Session Token ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_77ee3a2eb65741a0a4a3f1f6f3f0aa94' \ --data '{ "payment_id": "pay_msQQCSrBSCeNAZjBgwj9", "client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW", "wallets": [] }' ``` Response ``` { "payment_id": "pay_msQQCSrBSCeNAZjBgwj9", "client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW", "session_token": [ { "wallet_name": "paypal", "connector": "paypal", "session_token": "ASK************************_2", "sdk_next_action": { "next_action": "confirm" } } ] } ``` ### Payments - Confirm ``` curl --location 'http://localhost:8080/payments/pay_msQQCSrBSCeNAZjBgwj9/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_33Ad6faEcusLrqrqSeeFWyGRyTfOkKMoPMTSirAhCg0qqwkxQ25t7K1ucBEoq26M' \ --data '{ "confirm": true, "payment_method": "wallet", "payment_method_type": "paypal", "payment_method_data": { "wallet": { "paypal_sdk": { "token":"" } } } }' ``` Response: ``` { "payment_id": "pay_msQQCSrBSCeNAZjBgwj9", "merchant_id": "merchant_1716757295", "status": "requires_customer_action", "amount": 6100, "net_amount": 6100, "amount_capturable": 6100, "amount_received": null, "connector": "paypal", "client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW", "created": "2024-05-26T21:03:19.068Z", "currency": "USD", "customer_id": null, "customer": null, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "next_action": { "type": "invoke_sdk_client", "next_action_data": { "next_action": "complete_authorize" } }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "paypal", "connector_label": "paypal_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "39X68391D53803705", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pay_msQQCSrBSCeNAZjBgwj9_1", "payment_link": null, "profile_id": "pro_L6gjuuDhzdKR9wlyV8yA", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_ziKihOYd8bxdqpoLhP3u", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-26T21:18:19.068Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-26T21:06:09.286Z", "charges": null, "frm_metadata": null } ``` ### Authenticate Payment via SDK ### Payments - Complete Authorize ``` curl --location 'http://localhost:8080/payments/pay_msQQCSrBSCeNAZjBgwj9/complete_authorize' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_77ee3a2eb65741a0a4a3f1f6f3f0aa94' \ --data-raw '{ "shipping": { "address": { "line1": "1467", "line2": "Kormangala", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "guest@example.com" }, "client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW" }' ``` Test Scenarios - Test all the payments flow: Authorize, Manual Capture, Auto Capture, Refunds and webhooks - Test for backwards compatibility: i.e use an older account where `redirect_to_url` is configured as payment_experience none of the flow should get affected by new code - Update the connector account to SDK experience and then sync older payments and try new payments as well
1026f4783000a13b43f22e4db0b36c217d39e541
### Create Paypal MCA with payment_experience as `invoke_sdk_client` for Paypal Wallet ``` curl --location 'http://localhost:8080/account/merchant_1716757295/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "business_country": "US", "connector_name": "paypal", "connector_account_details": { "auth_type": "BodyKey", "api_key": "********************************", "key1": "ASK*****************************_2" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "paypal", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "paypal_sdk": { "client_id": "ASK****************************_2" } } }' ``` ### Payments Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_33Ad6faEcusLrqrqSeeFWyGRyTfOkKMoPMTSirAhCg0qqwkxQ25t7K1ucBEoq26M' \ --data-raw '{ "amount": 6100, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "amount_to_capture": 6100, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "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", "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" } } }' ``` ### Session Token ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_77ee3a2eb65741a0a4a3f1f6f3f0aa94' \ --data '{ "payment_id": "pay_msQQCSrBSCeNAZjBgwj9", "client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW", "wallets": [] }' ``` Response ``` { "payment_id": "pay_msQQCSrBSCeNAZjBgwj9", "client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW", "session_token": [ { "wallet_name": "paypal", "connector": "paypal", "session_token": "ASK************************_2", "sdk_next_action": { "next_action": "confirm" } } ] } ``` ### Payments - Confirm ``` curl --location 'http://localhost:8080/payments/pay_msQQCSrBSCeNAZjBgwj9/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_33Ad6faEcusLrqrqSeeFWyGRyTfOkKMoPMTSirAhCg0qqwkxQ25t7K1ucBEoq26M' \ --data '{ "confirm": true, "payment_method": "wallet", "payment_method_type": "paypal", "payment_method_data": { "wallet": { "paypal_sdk": { "token":"" } } } }' ``` Response: ``` { "payment_id": "pay_msQQCSrBSCeNAZjBgwj9", "merchant_id": "merchant_1716757295", "status": "requires_customer_action", "amount": 6100, "net_amount": 6100, "amount_capturable": 6100, "amount_received": null, "connector": "paypal", "client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW", "created": "2024-05-26T21:03:19.068Z", "currency": "USD", "customer_id": null, "customer": null, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "next_action": { "type": "invoke_sdk_client", "next_action_data": { "next_action": "complete_authorize" } }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "paypal", "connector_label": "paypal_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "39X68391D53803705", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pay_msQQCSrBSCeNAZjBgwj9_1", "payment_link": null, "profile_id": "pro_L6gjuuDhzdKR9wlyV8yA", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_ziKihOYd8bxdqpoLhP3u", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-26T21:18:19.068Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-26T21:06:09.286Z", "charges": null, "frm_metadata": null } ``` ### Authenticate Payment via SDK ### Payments - Complete Authorize ``` curl --location 'http://localhost:8080/payments/pay_msQQCSrBSCeNAZjBgwj9/complete_authorize' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_77ee3a2eb65741a0a4a3f1f6f3f0aa94' \ --data-raw '{ "shipping": { "address": { "line1": "1467", "line2": "Kormangala", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "guest@example.com" }, "client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW" }' ``` Test Scenarios - Test all the payments flow: Authorize, Manual Capture, Auto Capture, Refunds and webhooks - Test for backwards compatibility: i.e use an older account where `redirect_to_url` is configured as payment_experience none of the flow should get affected by new code - Update the connector account to SDK experience and then sync older payments and try new payments as well
[ "crates/api_models/src/payments.rs", "crates/connector_configs/src/common_config.rs", "crates/connector_configs/src/connector.rs", "crates/connector_configs/src/response_modifier.rs", "crates/connector_configs/src/transformer.rs", "crates/connector_configs/toml/development.toml", "crates/connector_confi...
juspay/hyperswitch
juspay__hyperswitch-4689
Bug: [REFACTOR] add support for passing ttl to locker entries Add config support for passing ttl to locker entries. By default keep the ttl to 7 years
diff --git a/config/config.example.toml b/config/config.example.toml index d5bdfb5a6a7..d10e8216e9f 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -124,11 +124,12 @@ recon_admin_api_key = "recon_test_admin" # recon_admin API key for recon authent # PCI Compliant storage entity which stores payment method information # like card details [locker] -host = "" # Locker host -host_rs = "" # Rust Locker host -mock_locker = true # Emulate a locker locally using Postgres -locker_signing_key_id = "1" # Key_id to sign basilisk hs locker -locker_enabled = true # Boolean to enable or disable saving cards in locker +host = "" # Locker host +host_rs = "" # Rust Locker host +mock_locker = true # Emulate a locker locally using Postgres +locker_signing_key_id = "1" # Key_id to sign basilisk hs locker +locker_enabled = true # Boolean to enable or disable saving cards in locker +ttl_for_storage_in_secs = 220752000 # Time to live for storage entries in locker [delayed_session_response] connectors_with_delayed_session_response = "trustpay,payme" # List of connectors which has delayed session response diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index c725a8bd69d..fc02335dcf5 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -115,6 +115,8 @@ mock_locker = true # Emulate locker_signing_key_id = "1" # Key_id to sign basilisk hs locker locker_enabled = true # Boolean to enable or disable saving cards in locker redis_temp_locker_encryption_key = "redis_temp_locker_encryption_key" # Encryption key for redis temp locker +ttl_for_storage_in_secs = 220752000 # Time to live for storage entries in locker + [log.console] enabled = true diff --git a/config/development.toml b/config/development.toml index a9f7f4d7b4d..dfba91b514d 100644 --- a/config/development.toml +++ b/config/development.toml @@ -71,6 +71,7 @@ host_rs = "" mock_locker = true basilisk_host = "" locker_enabled = true +ttl_for_storage_in_secs = 220752000 [forex_api] call_delay = 21600 diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 6661d164032..d371d08148a 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -61,6 +61,7 @@ host_rs = "" mock_locker = true basilisk_host = "" locker_enabled = true +ttl_for_storage_in_secs = 220752000 [jwekey] vault_encryption_key = "" diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 1fe86a209e3..d3be5cd5248 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -68,6 +68,8 @@ impl Default for super::settings::Locker { locker_signing_key_id: "1".into(), //true or false locker_enabled: true, + //Time to live for storage entries in locker + ttl_for_storage_in_secs: 60 * 60 * 24 * 365 * 7, } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index b8a315f944b..8ac27cce318 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -407,6 +407,7 @@ pub struct Locker { pub basilisk_host: String, pub locker_signing_key_id: String, pub locker_enabled: bool, + pub ttl_for_storage_in_secs: i64, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 379050ba73e..cd51face62d 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1070,6 +1070,7 @@ pub async fn add_bank_to_locker( merchant_id: &merchant_account.merchant_id, merchant_customer_id: customer_id.to_owned(), enc_data, + ttl: state.conf.locker.ttl_for_storage_in_secs, }); let store_resp = call_to_locker_hs( state, @@ -1229,6 +1230,7 @@ pub async fn add_card_hs( card_isin: None, nick_name: card.nick_name.as_ref().map(Secret::peek).cloned(), }, + ttl: state.conf.locker.ttl_for_storage_in_secs, }); let store_card_payload = diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 08e87b47f91..86b41d1d0fe 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -43,6 +43,7 @@ pub struct StoreCardReq<'a> { #[serde(skip_serializing_if = "Option::is_none")] pub requestor_card_reference: Option<String>, pub card: Card, + pub ttl: i64, } #[derive(Debug, Deserialize, Serialize)] @@ -51,6 +52,7 @@ pub struct StoreGenericReq<'a> { pub merchant_customer_id: String, #[serde(rename = "enc_card_data")] pub enc_data: String, + pub ttl: i64, } #[derive(Debug, Deserialize, Serialize)] diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index dad0739879f..9c6cdbd8881 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -220,6 +220,7 @@ pub async fn save_payout_data_to_locker( nick_name: None, }, requestor_card_reference: None, + ttl: state.conf.locker.ttl_for_storage_in_secs, }); ( payload, @@ -255,6 +256,7 @@ pub async fn save_payout_data_to_locker( merchant_id: merchant_account.merchant_id.as_ref(), merchant_customer_id: payout_attempt.customer_id.to_owned(), enc_data, + ttl: state.conf.locker.ttl_for_storage_in_secs, }); match payout_method_data { payouts::PayoutMethodData::Bank(bank) => ( diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 2c3e83ad2ba..878451080e3 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -38,6 +38,7 @@ host_rs = "" mock_locker = true basilisk_host = "" locker_enabled = true +ttl_for_storage_in_secs = 220752000 [forex_api] call_delay = 21600 @@ -320,4 +321,4 @@ client_secret = "" partner_id = "" [unmasked_headers] -keys = "user-agent" \ No newline at end of file +keys = "user-agent"
2024-05-17T13:43:49Z
## Description <!-- Describe your changes in detail --> This PR adds config support for passing ttl to locker entries as application config. By default ttl is kept to 7 years. ### 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)? --> TTL assignment in locker cannot be known (unless we access the locker db). Hyperswitch just sends the TTL as 7 years to locker. Hyperswitch doesn't store the TTL. Even during payment methods retrieve in Hyperswitch, the TTL is not fetched from locker. So basic card saving flow has to be tested Local testing - 1. Save card in locker ``` curl --location 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_sQtjddP5dtSitN2ZB01xgmzYnQboxyx4u3m9nWjMSRCZlApGGjqAnXyVGAPl8OlI' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "Visa", "card": { "card_number": "4111111111111111", "card_exp_month": "04", "card_exp_year": "25", "card_holder_name": "John", "card_network": "Visa" }, "customer_id": "cus_kr9m9hY3ZpS7oJLtJ4mo", "metadata": { "city": "NY", "unit": "245" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/15d7a9d1-508f-49d9-b6e7-dd42d21a1f70) 2. Locker DB (ttl is 7 years from created time) ![image](https://github.com/juspay/hyperswitch/assets/70657455/4ee33346-b047-49fb-8028-25eb608abec8)
8d9c7bc45ce2515759b9e2a36eb2d8a8a2c813ad
TTL assignment in locker cannot be known (unless we access the locker db). Hyperswitch just sends the TTL as 7 years to locker. Hyperswitch doesn't store the TTL. Even during payment methods retrieve in Hyperswitch, the TTL is not fetched from locker. So basic card saving flow has to be tested Local testing - 1. Save card in locker ``` curl --location 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_sQtjddP5dtSitN2ZB01xgmzYnQboxyx4u3m9nWjMSRCZlApGGjqAnXyVGAPl8OlI' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "Visa", "card": { "card_number": "4111111111111111", "card_exp_month": "04", "card_exp_year": "25", "card_holder_name": "John", "card_network": "Visa" }, "customer_id": "cus_kr9m9hY3ZpS7oJLtJ4mo", "metadata": { "city": "NY", "unit": "245" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/15d7a9d1-508f-49d9-b6e7-dd42d21a1f70) 2. Locker DB (ttl is 7 years from created time) ![image](https://github.com/juspay/hyperswitch/assets/70657455/4ee33346-b047-49fb-8028-25eb608abec8)
[ "config/config.example.toml", "config/deployments/env_specific.toml", "config/development.toml", "config/docker_compose.toml", "crates/router/src/configs/defaults.rs", "crates/router/src/configs/settings.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/payment_methods/tr...
juspay/hyperswitch
juspay__hyperswitch-4691
Bug: [FEATURE] The Eligibility Analysis during payments confirmation makes use of the Constraint Graph framework to carry out checks. ### Feature Description The Eligibility Analysis during payments confirmation makes use of the Constraint Graph framework to carry out checks. ### Possible Implementation We can make use of the constraint graph framework to represent all the checks as a constraint graph. One thing to be aware of is that the Payment Methods filtering logic checks the eligibility of payment methods whereas the Eligibility Analysis checks the eligibility of a connector for a particular payment, i.e. the goals differ even if the underlying checks are based on the same data. ### 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/Cargo.lock b/Cargo.lock index abc265ad692..e3cc2e32387 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3944,6 +3944,7 @@ dependencies = [ "masking", "serde", "serde_json", + "strum 0.26.2", "thiserror", ] diff --git a/crates/euclid/src/dssa/graph.rs b/crates/euclid/src/dssa/graph.rs index 0ffafe4d48b..ce61fa57bf5 100644 --- a/crates/euclid/src/dssa/graph.rs +++ b/crates/euclid/src/dssa/graph.rs @@ -12,6 +12,7 @@ use crate::{ pub mod euclid_graph_prelude { pub use hyperswitch_constraint_graph as cgraph; pub use rustc_hash::{FxHashMap, FxHashSet}; + pub use strum::EnumIter; pub use crate::{ dssa::graph::*, @@ -71,6 +72,7 @@ impl<V: cgraph::ValueNode> AnalysisError<V> { } } +#[derive(Debug)] pub struct AnalysisContext { keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>>, } diff --git a/crates/euclid/src/enums.rs b/crates/euclid/src/enums.rs index f473c5980c7..1aba6338d9d 100644 --- a/crates/euclid/src/enums.rs +++ b/crates/euclid/src/enums.rs @@ -1,5 +1,5 @@ pub use common_enums::{ - AuthenticationType, CaptureMethod, CardNetwork, Country, Currency, + AuthenticationType, CaptureMethod, CardNetwork, Country, CountryAlpha2, Currency, FutureUsage as SetupFutureUsage, PaymentMethod, PaymentMethodType, RoutableConnectors, }; use strum::VariantNames; diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index 941fc9d7465..c5f864bf770 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -3,8 +3,8 @@ use strum::VariantNames; use crate::enums::collect_variants; pub use crate::enums::{ AuthenticationType, CaptureMethod, CardNetwork, Country, Country as BusinessCountry, - Country as BillingCountry, Currency as PaymentCurrency, MandateAcceptanceType, MandateType, - PaymentMethod, PaymentType, RoutableConnectors, SetupFutureUsage, + Country as BillingCountry, CountryAlpha2, Currency as PaymentCurrency, MandateAcceptanceType, + MandateType, PaymentMethod, PaymentType, RoutableConnectors, SetupFutureUsage, }; #[cfg(feature = "payouts")] pub use crate::enums::{PayoutBankTransferType, PayoutType, PayoutWalletType}; diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs index 3668130608e..df78786a579 100644 --- a/crates/euclid_wasm/src/lib.rs +++ b/crates/euclid_wasm/src/lib.rs @@ -91,8 +91,12 @@ pub fn seed_knowledge_graph(mcas: JsValue) -> JsResult { .collect::<Result<_, _>>() .map_err(|_| "invalid connector name received") .err_to_js()?; - - let mca_graph = kgraph_utils::mca::make_mca_graph(mcas).err_to_js()?; + let pm_filter = kgraph_utils::types::PaymentMethodFilters(HashMap::new()); + let config = kgraph_utils::types::CountryCurrencyFilter { + connector_configs: HashMap::new(), + default_configs: Some(pm_filter), + }; + let mca_graph = kgraph_utils::mca::make_mca_graph(mcas, &config).err_to_js()?; let analysis_graph = hyperswitch_constraint_graph::ConstraintGraph::combine(&mca_graph, &truth::ANALYSIS_GRAPH) .err_to_js()?; diff --git a/crates/hyperswitch_constraint_graph/src/builder.rs b/crates/hyperswitch_constraint_graph/src/builder.rs index c1343eff885..fdd87eac51c 100644 --- a/crates/hyperswitch_constraint_graph/src/builder.rs +++ b/crates/hyperswitch_constraint_graph/src/builder.rs @@ -28,7 +28,7 @@ impl From<DomainId> for DomainIdOrIdentifier<'_> { Self::DomainId(value) } } - +#[derive(Debug)] pub struct ConstraintGraphBuilder<'a, V: ValueNode> { domain: DenseMap<DomainId, DomainInfo<'a>>, nodes: DenseMap<NodeId, Node<V>>, diff --git a/crates/hyperswitch_constraint_graph/src/graph.rs b/crates/hyperswitch_constraint_graph/src/graph.rs index d0a98e19520..4a93419df57 100644 --- a/crates/hyperswitch_constraint_graph/src/graph.rs +++ b/crates/hyperswitch_constraint_graph/src/graph.rs @@ -13,6 +13,7 @@ use crate::{ }, }; +#[derive(Debug)] struct CheckNodeContext<'a, V: ValueNode, C: CheckingContext<Value = V>> { ctx: &'a C, node: &'a Node<V>, @@ -24,6 +25,7 @@ struct CheckNodeContext<'a, V: ValueNode, C: CheckingContext<Value = V>> { domains: Option<&'a [DomainId]>, } +#[derive(Debug)] pub struct ConstraintGraph<'a, V: ValueNode> { pub domain: DenseMap<DomainId, DomainInfo<'a>>, pub domain_identifier_map: FxHashMap<DomainIdentifier<'a>, DomainId>, @@ -139,6 +141,7 @@ where ctx, domains, }; + match &node.node_type { NodeType::AllAggregator => self.validate_all_aggregator(check_node_context), @@ -206,6 +209,7 @@ where } else { vald.memo .insert((vald.node_id, vald.relation, vald.strength), Ok(())); + Ok(()) } } diff --git a/crates/kgraph_utils/Cargo.toml b/crates/kgraph_utils/Cargo.toml index 86de6002c32..d068ee89692 100644 --- a/crates/kgraph_utils/Cargo.toml +++ b/crates/kgraph_utils/Cargo.toml @@ -21,6 +21,7 @@ masking = { version = "0.1.0", path = "../masking/" } serde = "1.0.197" serde_json = "1.0.115" thiserror = "1.0.58" +strum = { version = "0.26", features = ["derive"] } [dev-dependencies] criterion = "0.5" diff --git a/crates/kgraph_utils/benches/evaluation.rs b/crates/kgraph_utils/benches/evaluation.rs index 9921ee7af35..4cc526f973f 100644 --- a/crates/kgraph_utils/benches/evaluation.rs +++ b/crates/kgraph_utils/benches/evaluation.rs @@ -1,6 +1,6 @@ #![allow(unused, clippy::expect_used)] -use std::str::FromStr; +use std::{collections::HashMap, str::FromStr}; use api_models::{ admin as admin_api, enums as api_enums, payment_methods::RequestPaymentMethodTypes, @@ -13,7 +13,7 @@ use euclid::{ types::{NumValue, NumValueRefinement}, }; use hyperswitch_constraint_graph::{CycleCheck, Memoization}; -use kgraph_utils::{error::KgraphError, transformers::IntoDirValue}; +use kgraph_utils::{error::KgraphError, transformers::IntoDirValue, types::CountryCurrencyFilter}; fn build_test_data<'a>( total_enabled: usize, @@ -71,8 +71,12 @@ fn build_test_data<'a>( pm_auth_config: None, status: api_enums::ConnectorStatus::Inactive, }; - - kgraph_utils::mca::make_mca_graph(vec![stripe_account]).expect("Failed graph construction") + let config = CountryCurrencyFilter { + connector_configs: HashMap::new(), + default_configs: None, + }; + kgraph_utils::mca::make_mca_graph(vec![stripe_account], &config) + .expect("Failed graph construction") } fn evaluation(c: &mut Criterion) { diff --git a/crates/kgraph_utils/src/lib.rs b/crates/kgraph_utils/src/lib.rs index eb8eef6dedb..20c2abf0533 100644 --- a/crates/kgraph_utils/src/lib.rs +++ b/crates/kgraph_utils/src/lib.rs @@ -1,3 +1,4 @@ pub mod error; pub mod mca; pub mod transformers; +pub mod types; diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index 14a88dd1c6e..ed96cd9b545 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -4,15 +4,138 @@ use api_models::{ admin as admin_api, enums as api_enums, payment_methods::RequestPaymentMethodTypes, }; use euclid::{ + dirval, frontend::{ast, dir}, types::{NumValue, NumValueRefinement}, }; use hyperswitch_constraint_graph as cgraph; +use strum::IntoEnumIterator; -use crate::{error::KgraphError, transformers::IntoDirValue}; +use crate::{error::KgraphError, transformers::IntoDirValue, types as kgraph_types}; pub const DOMAIN_IDENTIFIER: &str = "payment_methods_enabled_for_merchantconnectoraccount"; +fn get_dir_value_payment_method( + from: api_enums::PaymentMethodType, +) -> Result<dir::DirValue, KgraphError> { + match from { + api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)), + api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)), + api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)), + api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)), + api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)), + api_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)), + api_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)), + api_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)), + api_enums::PaymentMethodType::AfterpayClearpay => { + Ok(dirval!(PayLaterType = AfterpayClearpay)) + } + api_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)), + api_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)), + api_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)), + api_enums::PaymentMethodType::CryptoCurrency => Ok(dirval!(CryptoType = CryptoCurrency)), + api_enums::PaymentMethodType::Ach => Ok(dirval!(BankDebitType = Ach)), + + api_enums::PaymentMethodType::Bacs => Ok(dirval!(BankDebitType = Bacs)), + + api_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)), + api_enums::PaymentMethodType::Sepa => Ok(dirval!(BankDebitType = Sepa)), + + api_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)), + api_enums::PaymentMethodType::AliPayHk => Ok(dirval!(WalletType = AliPayHk)), + api_enums::PaymentMethodType::BancontactCard => { + Ok(dirval!(BankRedirectType = BancontactCard)) + } + api_enums::PaymentMethodType::Blik => Ok(dirval!(BankRedirectType = Blik)), + api_enums::PaymentMethodType::MbWay => Ok(dirval!(WalletType = MbWay)), + api_enums::PaymentMethodType::MobilePay => Ok(dirval!(WalletType = MobilePay)), + api_enums::PaymentMethodType::Cashapp => Ok(dirval!(WalletType = Cashapp)), + api_enums::PaymentMethodType::Multibanco => Ok(dirval!(BankTransferType = Multibanco)), + api_enums::PaymentMethodType::Pix => Ok(dirval!(BankTransferType = Pix)), + api_enums::PaymentMethodType::Pse => Ok(dirval!(BankTransferType = Pse)), + api_enums::PaymentMethodType::Interac => Ok(dirval!(BankRedirectType = Interac)), + api_enums::PaymentMethodType::OnlineBankingCzechRepublic => { + Ok(dirval!(BankRedirectType = OnlineBankingCzechRepublic)) + } + api_enums::PaymentMethodType::OnlineBankingFinland => { + Ok(dirval!(BankRedirectType = OnlineBankingFinland)) + } + api_enums::PaymentMethodType::OnlineBankingPoland => { + Ok(dirval!(BankRedirectType = OnlineBankingPoland)) + } + api_enums::PaymentMethodType::OnlineBankingSlovakia => { + Ok(dirval!(BankRedirectType = OnlineBankingSlovakia)) + } + api_enums::PaymentMethodType::Swish => Ok(dirval!(WalletType = Swish)), + api_enums::PaymentMethodType::Trustly => Ok(dirval!(BankRedirectType = Trustly)), + api_enums::PaymentMethodType::Bizum => Ok(dirval!(BankRedirectType = Bizum)), + + api_enums::PaymentMethodType::PayBright => Ok(dirval!(PayLaterType = PayBright)), + api_enums::PaymentMethodType::Walley => Ok(dirval!(PayLaterType = Walley)), + api_enums::PaymentMethodType::Przelewy24 => Ok(dirval!(BankRedirectType = Przelewy24)), + api_enums::PaymentMethodType::WeChatPay => Ok(dirval!(WalletType = WeChatPay)), + + api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)), + api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)), + api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)), + api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)), + api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)), + api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)), + api_enums::PaymentMethodType::Twint => Ok(dirval!(WalletType = Twint)), + api_enums::PaymentMethodType::Gcash => Ok(dirval!(WalletType = Gcash)), + api_enums::PaymentMethodType::Vipps => Ok(dirval!(WalletType = Vipps)), + api_enums::PaymentMethodType::Momo => Ok(dirval!(WalletType = Momo)), + api_enums::PaymentMethodType::Alma => Ok(dirval!(PayLaterType = Alma)), + api_enums::PaymentMethodType::Dana => Ok(dirval!(WalletType = Dana)), + api_enums::PaymentMethodType::OnlineBankingFpx => { + Ok(dirval!(BankRedirectType = OnlineBankingFpx)) + } + api_enums::PaymentMethodType::OnlineBankingThailand => { + Ok(dirval!(BankRedirectType = OnlineBankingThailand)) + } + api_enums::PaymentMethodType::TouchNGo => Ok(dirval!(WalletType = TouchNGo)), + api_enums::PaymentMethodType::Atome => Ok(dirval!(PayLaterType = Atome)), + api_enums::PaymentMethodType::Boleto => Ok(dirval!(VoucherType = Boleto)), + api_enums::PaymentMethodType::Efecty => Ok(dirval!(VoucherType = Efecty)), + api_enums::PaymentMethodType::PagoEfectivo => Ok(dirval!(VoucherType = PagoEfectivo)), + api_enums::PaymentMethodType::RedCompra => Ok(dirval!(VoucherType = RedCompra)), + api_enums::PaymentMethodType::RedPagos => Ok(dirval!(VoucherType = RedPagos)), + api_enums::PaymentMethodType::Alfamart => Ok(dirval!(VoucherType = Alfamart)), + api_enums::PaymentMethodType::BcaBankTransfer => { + Ok(dirval!(BankTransferType = BcaBankTransfer)) + } + api_enums::PaymentMethodType::BniVa => Ok(dirval!(BankTransferType = BniVa)), + api_enums::PaymentMethodType::BriVa => Ok(dirval!(BankTransferType = BriVa)), + api_enums::PaymentMethodType::CimbVa => Ok(dirval!(BankTransferType = CimbVa)), + api_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)), + api_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)), + api_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)), + api_enums::PaymentMethodType::LocalBankTransfer => { + Ok(dirval!(BankTransferType = LocalBankTransfer)) + } + api_enums::PaymentMethodType::PermataBankTransfer => { + Ok(dirval!(BankTransferType = PermataBankTransfer)) + } + api_enums::PaymentMethodType::PaySafeCard => Ok(dirval!(GiftCardType = PaySafeCard)), + api_enums::PaymentMethodType::SevenEleven => Ok(dirval!(VoucherType = SevenEleven)), + api_enums::PaymentMethodType::Lawson => Ok(dirval!(VoucherType = Lawson)), + api_enums::PaymentMethodType::MiniStop => Ok(dirval!(VoucherType = MiniStop)), + api_enums::PaymentMethodType::FamilyMart => Ok(dirval!(VoucherType = FamilyMart)), + api_enums::PaymentMethodType::Seicomart => Ok(dirval!(VoucherType = Seicomart)), + api_enums::PaymentMethodType::PayEasy => Ok(dirval!(VoucherType = PayEasy)), + api_enums::PaymentMethodType::Givex => Ok(dirval!(GiftCardType = Givex)), + api_enums::PaymentMethodType::Benefit => Ok(dirval!(CardRedirectType = Benefit)), + api_enums::PaymentMethodType::Knet => Ok(dirval!(CardRedirectType = Knet)), + api_enums::PaymentMethodType::OpenBankingUk => { + Ok(dirval!(BankRedirectType = OpenBankingUk)) + } + api_enums::PaymentMethodType::MomoAtm => Ok(dirval!(CardRedirectType = MomoAtm)), + api_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)), + api_enums::PaymentMethodType::CardRedirect => Ok(dirval!(CardRedirectType = CardRedirect)), + api_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)), + } +} + fn compile_request_pm_types( builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>, pm_types: RequestPaymentMethodTypes, @@ -258,16 +381,220 @@ fn compile_payment_method_enabled( Ok(agg_id) } +macro_rules! collect_global_variants { + ($parent_enum:ident) => { + &mut dir::enums::$parent_enum::iter() + .map(dir::DirValue::$parent_enum) + .collect::<Vec<_>>() + }; +} +fn global_vec_pmt( + enabled_pmt: Vec<dir::DirValue>, + builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>, +) -> Vec<cgraph::NodeId> { + let mut global_vector: Vec<dir::DirValue> = Vec::new(); + + global_vector.append(collect_global_variants!(PayLaterType)); + global_vector.append(collect_global_variants!(WalletType)); + global_vector.append(collect_global_variants!(BankRedirectType)); + global_vector.append(collect_global_variants!(BankDebitType)); + global_vector.append(collect_global_variants!(CryptoType)); + global_vector.append(collect_global_variants!(RewardType)); + global_vector.append(collect_global_variants!(UpiType)); + global_vector.append(collect_global_variants!(VoucherType)); + global_vector.append(collect_global_variants!(GiftCardType)); + global_vector.append(collect_global_variants!(BankTransferType)); + global_vector.append(collect_global_variants!(CardRedirectType)); + 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)) + .collect::<Vec<_>>(); + + global_vector + .into_iter() + .map(|dir_v| { + builder.make_value_node( + cgraph::NodeValue::Value(dir_v), + Some("Payment Method Type"), + None::<()>, + ) + }) + .collect::<Vec<_>>() +} + +fn compile_graph_for_countries_and_currencies( + builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>, + config: &kgraph_types::CurrencyCountryFlowFilter, + payment_method_type_node: cgraph::NodeId, +) -> Result<cgraph::NodeId, KgraphError> { + let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); + agg_nodes.push(( + payment_method_type_node, + cgraph::Relation::Positive, + cgraph::Strength::Normal, + )); + if let Some(country) = config.country.clone() { + let node_country = country + .into_iter() + .map(|country| dir::DirValue::BillingCountry(api_enums::Country::from_alpha2(country))) + .collect(); + let country_agg = builder + .make_in_aggregator(node_country, Some("Configs for Country"), None::<()>) + .map_err(KgraphError::GraphConstructionError)?; + agg_nodes.push(( + country_agg, + cgraph::Relation::Positive, + cgraph::Strength::Weak, + )) + } + + if let Some(currency) = config.currency.clone() { + let node_currency = currency + .into_iter() + .map(IntoDirValue::into_dir_value) + .collect::<Result<Vec<_>, _>>()?; + let currency_agg = builder + .make_in_aggregator(node_currency, Some("Configs for Currency"), None::<()>) + .map_err(KgraphError::GraphConstructionError)?; + agg_nodes.push(( + currency_agg, + cgraph::Relation::Positive, + cgraph::Strength::Normal, + )) + } + if let Some(capture_method) = config + .not_available_flows + .and_then(|naf| naf.capture_method) + { + let make_capture_node = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(capture_method)), + Some("Configs for CaptureMethod"), + None::<()>, + ); + agg_nodes.push(( + make_capture_node, + cgraph::Relation::Negative, + cgraph::Strength::Normal, + )) + } + + builder + .make_all_aggregator( + &agg_nodes, + Some("Country & Currency Configs With Payment Method Type"), + None::<()>, + None, + ) + .map_err(KgraphError::GraphConstructionError) +} + +fn compile_config_graph( + builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>, + config: &kgraph_types::CountryCurrencyFilter, + connector: &api_enums::RoutableConnectors, +) -> Result<cgraph::NodeId, KgraphError> { + let mut agg_node_id: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); + let mut pmt_enabled: Vec<dir::DirValue> = Vec::new(); + if let Some(pmt) = config + .connector_configs + .get(connector) + .or(config.default_configs.as_ref()) + .map(|inner| inner.0.clone()) + { + for pm_filter_key in pmt { + match pm_filter_key { + (kgraph_types::PaymentMethodFilterKey::PaymentMethodType(pm), filter) => { + let dir_val_pm = get_dir_value_payment_method(pm)?; + + let pm_node = if pm == api_enums::PaymentMethodType::Credit + || pm == api_enums::PaymentMethodType::Debit + { + pmt_enabled + .push(dir::DirValue::PaymentMethod(api_enums::PaymentMethod::Card)); + builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::PaymentMethod( + dir::enums::PaymentMethod::Card, + )), + Some("PaymentMethod"), + None::<()>, + ) + } else { + pmt_enabled.push(dir_val_pm.clone()); + builder.make_value_node( + cgraph::NodeValue::Value(dir_val_pm), + Some("PaymentMethodType"), + None::<()>, + ) + }; + + let node_config = + compile_graph_for_countries_and_currencies(builder, &filter, pm_node)?; + + agg_node_id.push(( + node_config, + cgraph::Relation::Positive, + cgraph::Strength::Normal, + )); + } + (kgraph_types::PaymentMethodFilterKey::CardNetwork(cn), filter) => { + let dir_val_cn = cn.clone().into_dir_value()?; + pmt_enabled.push(dir_val_cn); + let cn_node = builder.make_value_node( + cn.clone().into_dir_value().map(Into::into)?, + Some("CardNetwork"), + None::<()>, + ); + let node_config = + compile_graph_for_countries_and_currencies(builder, &filter, cn_node)?; + + agg_node_id.push(( + node_config, + cgraph::Relation::Positive, + cgraph::Strength::Normal, + )); + } + } + } + } + let global_vector_pmt: Vec<cgraph::NodeId> = global_vec_pmt(pmt_enabled, builder); + let any_agg_pmt: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = global_vector_pmt + .into_iter() + .map(|node| (node, cgraph::Relation::Positive, cgraph::Strength::Normal)) + .collect::<Vec<_>>(); + let any_agg_node = builder + .make_any_aggregator( + &any_agg_pmt, + Some("Any Aggregator For Payment Method Types"), + None::<()>, + None, + ) + .map_err(KgraphError::GraphConstructionError)?; + + agg_node_id.push(( + any_agg_node, + cgraph::Relation::Positive, + cgraph::Strength::Normal, + )); + + builder + .make_any_aggregator(&agg_node_id, Some("Configs"), None::<()>, None) + .map_err(KgraphError::GraphConstructionError) +} + fn compile_merchant_connector_graph( builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>, mca: admin_api::MerchantConnectorResponse, + config: &kgraph_types::CountryCurrencyFilter, ) -> Result<(), KgraphError> { let connector = common_enums::RoutableConnectors::from_str(&mca.connector_name) .map_err(|_| KgraphError::InvalidConnectorName(mca.connector_name.clone()))?; let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); - if let Some(pms_enabled) = mca.payment_methods_enabled { + if let Some(pms_enabled) = mca.payment_methods_enabled.clone() { for pm_enabled in pms_enabled { let maybe_pm_enabled_id = compile_payment_method_enabled(builder, pm_enabled)?; if let Some(pm_enabled_id) = maybe_pm_enabled_id { @@ -285,10 +612,33 @@ fn compile_merchant_connector_graph( .make_any_aggregator(&agg_nodes, Some(aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError)?; + let config_info = "Config for respective PaymentMethodType for the connector"; + + let config_enabled_agg_id = compile_config_graph(builder, config, &connector)?; + + let domain_level_node_id = builder + .make_all_aggregator( + &[ + ( + config_enabled_agg_id, + cgraph::Relation::Positive, + cgraph::Strength::Normal, + ), + ( + pms_enabled_agg_id, + cgraph::Relation::Positive, + cgraph::Strength::Normal, + ), + ], + Some(config_info), + None::<()>, + None, + ) + .map_err(KgraphError::GraphConstructionError)?; let connector_dir_val = dir::DirValue::Connector(Box::new(ast::ConnectorChoice { connector, #[cfg(not(feature = "connector_choice_mca_id"))] - sub_label: mca.business_sub_label, + sub_label: mca.business_sub_label.clone(), })); let connector_info = "Connector"; @@ -297,7 +647,7 @@ fn compile_merchant_connector_graph( builder .make_edge( - pms_enabled_agg_id, + domain_level_node_id, connector_node_id, cgraph::Strength::Normal, cgraph::Relation::Positive, @@ -310,6 +660,7 @@ fn compile_merchant_connector_graph( pub fn make_mca_graph<'a>( accts: Vec<admin_api::MerchantConnectorResponse>, + config: &kgraph_types::CountryCurrencyFilter, ) -> Result<cgraph::ConstraintGraph<'a, dir::DirValue>, KgraphError> { let mut builder = cgraph::ConstraintGraphBuilder::new(); let _domain = builder.make_domain( @@ -317,7 +668,7 @@ pub fn make_mca_graph<'a>( "Payment methods enabled for MerchantConnectorAccount", ); for acct in accts { - compile_merchant_connector_graph(&mut builder, acct)?; + compile_merchant_connector_graph(&mut builder, acct, config)?; } Ok(builder.build()) @@ -327,6 +678,8 @@ pub fn make_mca_graph<'a>( mod tests { #![allow(clippy::expect_used)] + use std::collections::{HashMap, HashSet}; + use api_models::enums as api_enums; use euclid::{ dirval, @@ -335,6 +688,7 @@ mod tests { use hyperswitch_constraint_graph::{ConstraintGraph, CycleCheck, Memoization}; use super::*; + use crate::types as kgraph_types; fn build_test_data<'a>() -> ConstraintGraph<'a, dir::DirValue> { use api_models::{admin::*, payment_methods::*}; @@ -398,7 +752,36 @@ mod tests { status: api_enums::ConnectorStatus::Inactive, }; - make_mca_graph(vec![stripe_account]).expect("Failed graph construction") + let currency_country_flow_filter = kgraph_types::CurrencyCountryFlowFilter { + currency: Some(HashSet::from([api_enums::Currency::INR])), + country: Some(HashSet::from([api_enums::CountryAlpha2::IN])), + not_available_flows: Some(kgraph_types::NotAvailableFlows { + capture_method: Some(api_enums::CaptureMethod::Manual), + }), + }; + + let config_map = kgraph_types::CountryCurrencyFilter { + connector_configs: HashMap::from([( + api_enums::RoutableConnectors::Stripe, + kgraph_types::PaymentMethodFilters(HashMap::from([ + ( + kgraph_types::PaymentMethodFilterKey::PaymentMethodType( + api_enums::PaymentMethodType::Credit, + ), + currency_country_flow_filter.clone(), + ), + ( + kgraph_types::PaymentMethodFilterKey::PaymentMethodType( + api_enums::PaymentMethodType::Debit, + ), + currency_country_flow_filter, + ), + ])), + )]), + default_configs: None, + }; + + make_mca_graph(vec![stripe_account], &config_map).expect("Failed graph construction") } #[test] @@ -412,8 +795,8 @@ mod tests { dirval!(PaymentMethod = Card), dirval!(CardType = Credit), dirval!(CardNetwork = Visa), - dirval!(PaymentCurrency = USD), - dirval!(PaymentAmount = 100), + dirval!(PaymentCurrency = INR), + dirval!(PaymentAmount = 101), ]), &mut Memoization::new(), &mut CycleCheck::new(), @@ -711,8 +1094,11 @@ mod tests { let data: Vec<admin_api::MerchantConnectorResponse> = serde_json::from_value(value).expect("data"); - - let graph = make_mca_graph(data).expect("graph"); + let config = kgraph_types::CountryCurrencyFilter { + connector_configs: HashMap::new(), + default_configs: None, + }; + let graph = make_mca_graph(data, &config).expect("graph"); let context = AnalysisContext::from_dir_values([ dirval!(Connector = Stripe), dirval!(PaymentAmount = 212), diff --git a/crates/kgraph_utils/src/types.rs b/crates/kgraph_utils/src/types.rs new file mode 100644 index 00000000000..26f27896e0a --- /dev/null +++ b/crates/kgraph_utils/src/types.rs @@ -0,0 +1,35 @@ +use std::collections::{HashMap, HashSet}; + +use api_models::enums as api_enums; +use serde::Deserialize; +#[derive(Debug, Deserialize, Clone, Default)] + +pub struct CountryCurrencyFilter { + pub connector_configs: HashMap<api_enums::RoutableConnectors, PaymentMethodFilters>, + pub default_configs: Option<PaymentMethodFilters>, +} + +#[derive(Debug, Deserialize, Clone, Default)] +#[serde(transparent)] +pub struct PaymentMethodFilters(pub HashMap<PaymentMethodFilterKey, CurrencyCountryFlowFilter>); + +#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)] +#[serde(untagged)] +pub enum PaymentMethodFilterKey { + PaymentMethodType(api_enums::PaymentMethodType), + CardNetwork(api_enums::CardNetwork), +} + +#[derive(Debug, Deserialize, Clone, Default)] +#[serde(default)] +pub struct CurrencyCountryFlowFilter { + pub currency: Option<HashSet<api_enums::Currency>>, + pub country: Option<HashSet<api_enums::CountryAlpha2>>, + pub not_available_flows: Option<NotAvailableFlows>, +} + +#[derive(Debug, Deserialize, Copy, Clone, Default)] +#[serde(default)] +pub struct NotAvailableFlows { + pub capture_method: Option<api_enums::CaptureMethod>, +} diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 6967c977753..4218fe3462c 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1,8 +1,9 @@ mod transformers; use std::{ - collections::hash_map, + collections::{hash_map, HashMap}, hash::{Hash, Hasher}, + str::FromStr, sync::Arc, }; @@ -24,6 +25,7 @@ use euclid::{ use kgraph_utils::{ mca as mca_graph, transformers::{IntoContext, IntoDirValue}, + types::CountryCurrencyFilter, }; use masking::PeekInterface; use rand::{ @@ -43,8 +45,9 @@ use crate::{ }, logger, types::{ - api, api::routing as routing_types, domain, storage as oss_storage, - transformers::ForeignInto, + api::{self, routing as routing_types}, + domain, storage as oss_storage, + transformers::{ForeignFrom, ForeignInto}, }, utils::{OptionExt, ValueExt}, AppState, @@ -104,7 +107,6 @@ impl Default for MerchantAccountRoutingAlgorithm { pub fn make_dsl_input_for_payouts( payout_data: &payouts::PayoutData, ) -> RoutingResult<dsl_inputs::BackendInput> { - use crate::types::transformers::ForeignFrom; let mandate = dsl_inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, @@ -645,8 +647,32 @@ pub async fn refresh_kgraph_cache( .map(admin_api::MerchantConnectorResponse::try_from) .collect::<Result<Vec<_>, _>>() .change_context(errors::RoutingError::KgraphCacheRefreshFailed)?; - - let kgraph = mca_graph::make_mca_graph(api_mcas) + let connector_configs = state + .conf + .pm_filters + .0 + .clone() + .into_iter() + .filter(|(key, _)| key != "default") + .map(|(key, value)| { + let key = api_enums::RoutableConnectors::from_str(&key) + .map_err(|_| errors::RoutingError::InvalidConnectorName(key))?; + + Ok((key, value.foreign_into())) + }) + .collect::<Result<HashMap<_, _>, errors::RoutingError>>()?; + let default_configs = state + .conf + .pm_filters + .0 + .get("default") + .cloned() + .map(ForeignFrom::foreign_from); + let config_pm_filters = CountryCurrencyFilter { + connector_configs, + default_configs, + }; + let kgraph = mca_graph::make_mca_graph(api_mcas, &config_pm_filters) .change_context(errors::RoutingError::KgraphCacheRefreshFailed) .attach_printable("when construction kgraph")?; diff --git a/crates/router/src/core/payments/routing/transformers.rs b/crates/router/src/core/payments/routing/transformers.rs index b273f18f3fd..ae779a6551f 100644 --- a/crates/router/src/core/payments/routing/transformers.rs +++ b/crates/router/src/core/payments/routing/transformers.rs @@ -1,8 +1,14 @@ +use std::collections::HashMap; + use api_models::{self, routing as routing_types}; use diesel_models::enums as storage_enums; use euclid::{enums as dsl_enums, frontend::ast as dsl_ast}; +use kgraph_utils::types; -use crate::types::transformers::ForeignFrom; +use crate::{ + configs::settings, + types::transformers::{ForeignFrom, ForeignInto}, +}; impl ForeignFrom<routing_types::RoutableConnectorChoice> for dsl_ast::ConnectorChoice { fn foreign_from(from: routing_types::RoutableConnectorChoice) -> Self { @@ -52,3 +58,40 @@ impl ForeignFrom<storage_enums::MandateDataType> for dsl_enums::MandateType { } } } + +impl ForeignFrom<settings::PaymentMethodFilterKey> for types::PaymentMethodFilterKey { + fn foreign_from(from: settings::PaymentMethodFilterKey) -> Self { + match from { + settings::PaymentMethodFilterKey::PaymentMethodType(pmt) => { + Self::PaymentMethodType(pmt) + } + settings::PaymentMethodFilterKey::CardNetwork(cn) => Self::CardNetwork(cn), + } + } +} +impl ForeignFrom<settings::CurrencyCountryFlowFilter> for types::CurrencyCountryFlowFilter { + fn foreign_from(from: settings::CurrencyCountryFlowFilter) -> Self { + Self { + currency: from.currency, + country: from.country, + not_available_flows: from.not_available_flows.map(ForeignInto::foreign_into), + } + } +} +impl ForeignFrom<settings::NotAvailableFlows> for types::NotAvailableFlows { + fn foreign_from(from: settings::NotAvailableFlows) -> Self { + Self { + capture_method: from.capture_method, + } + } +} +impl ForeignFrom<settings::PaymentMethodFilters> for types::PaymentMethodFilters { + fn foreign_from(from: settings::PaymentMethodFilters) -> Self { + let iter_map = from + .0 + .into_iter() + .map(|(key, val)| (key.foreign_into(), val.foreign_into())) + .collect::<HashMap<_, _>>(); + Self(iter_map) + } +} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario13-BNPL-afterpay/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario13-BNPL-afterpay/Payments - Create/request.json index 273ed5ee3c6..d108e1198a7 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario13-BNPL-afterpay/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario13-BNPL-afterpay/Payments - Create/request.json @@ -41,7 +41,7 @@ "zip": "94122", "first_name": "John", "last_name": "Doe", - "country": "SE" + "country": "ES" }, "email": "narayan@example.com" }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario15-Bank Redirect-Ideal/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario15-Bank Redirect-Ideal/Payments - Create/request.json index 21e71ad037a..048893f3511 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario15-Bank Redirect-Ideal/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario15-Bank Redirect-Ideal/Payments - Create/request.json @@ -42,7 +42,7 @@ "city": "San Fransico", "state": "California", "zip": "94122", - "country": "DE" + "country": "NL" } }, "browser_info": { diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/request.json index 61add73d411..c0e2a2a3d5e 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/request.json @@ -48,7 +48,7 @@ }, "bank_name": "hypo_oberosterreich_salzburg_steiermark", "preferred_language": "en", - "country": "DE" + "country": "AT" } } }, diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json index 21e71ad037a..026af8449ce 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json @@ -42,7 +42,7 @@ "city": "San Fransico", "state": "California", "zip": "94122", - "country": "DE" + "country": "AT" } }, "browser_info": { diff --git a/postman/collection-json/stripe.postman_collection.json b/postman/collection-json/stripe.postman_collection.json index 47f732f2153..397864885cb 100644 --- a/postman/collection-json/stripe.postman_collection.json +++ b/postman/collection-json/stripe.postman_collection.json @@ -13677,7 +13677,7 @@ "language": "json" } }, - "raw": "{\"amount\":7000,\"currency\":\"USD\",\"confirm\":false,\"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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"first_name\":\"John\",\"last_name\":\"Doe\",\"country\":\"SE\"},\"email\":\"narayan@example.com\"},\"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\":\"SE\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":7000,\"currency\":\"USD\",\"confirm\":false,\"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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"first_name\":\"John\",\"last_name\":\"Doe\",\"country\":\"ES\"},\"email\":\"narayan@example.com\"},\"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\":\"SE\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -14537,7 +14537,7 @@ "language": "json" } }, - "raw": "{\"amount\":1000,\"currency\":\"EUR\",\"confirm\":false,\"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://duck.com\",\"billing\":{\"address\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"DE\"}},\"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\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":1000,\"currency\":\"EUR\",\"confirm\":false,\"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://duck.com\",\"billing\":{\"address\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"NL\"}},\"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\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -15397,7 +15397,7 @@ "language": "json" } }, - "raw": "{\"amount\":1000,\"currency\":\"EUR\",\"confirm\":false,\"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://duck.com\",\"billing\":{\"address\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"DE\"}},\"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\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" + "raw": "{\"amount\":1000,\"currency\":\"EUR\",\"confirm\":false,\"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://duck.com\",\"billing\":{\"address\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"AT\"}},\"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\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -15576,7 +15576,7 @@ "language": "json" } }, - "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"eps\",\"payment_method_data\":{\"bank_redirect\":{\"eps\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"hypo_oberosterreich_salzburg_steiermark\",\"preferred_language\":\"en\",\"country\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}" + "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"eps\",\"payment_method_data\":{\"bank_redirect\":{\"eps\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"hypo_oberosterreich_salzburg_steiermark\",\"preferred_language\":\"en\",\"country\":\"AT\"}}},\"client_secret\":\"{{client_secret}}\"}" }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm",
2024-05-17T13:14:13Z
## Description Refactor the Knowledge Graph to include configs(pm_filters) check, while eligibility analysis ### 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? - Wrote unit test - To test it, - You can create MCA for 2 connectors - Do a payment using BOA and with some currency that it doesn't support , for eg:INR ``` Create curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ylNGvTk4tI1OQFRGQN1CzMZMANf1jFHzTZqOkD4Ha4L4ubnngKMp98C6puzz1XPr' \ --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://duck.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" }, "email": "example@example.com" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "routing": { "type": "single", "data": "bankofamerica" } }' ``` - The payment would go through Stripe , as the eligibility analysis would fail ``` Response { "payment_id": "pay_dhTO36kNBB03SWsTvSKC", "merchant_id": "merchant_1716296468", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "stripe", "client_secret": "pay_dhTO36kNBB03SWsTvSKC_secret_siY75j9e6hsgwNuAC3rS", "created": "2024-05-21T13:04:21.786Z", "currency": "INR", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": { "address_line1_check": "pass", "address_postal_code_check": "pass", "cvc_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "example@example.com" }, "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": 1716296661, "expires": 1716300261, "secret": "epk_a404fe01e93d445da59f0a1d7346ad90" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3PIsMcD5R7gDAGff0O0dJvGC", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3PIsMcD5R7gDAGff0O0dJvGC", "payment_link": null, "profile_id": "pro_vucql9T54ccffbKNdOvw", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_41ElW94TenDAaISxhaVj", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-21T13:19:21.786Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-21T13:04:23.236Z", "frm_metadata": null } ```
be9343affeb178e646d4046785a105a9c6040037
- Wrote unit test - To test it, - You can create MCA for 2 connectors - Do a payment using BOA and with some currency that it doesn't support , for eg:INR ``` Create curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ylNGvTk4tI1OQFRGQN1CzMZMANf1jFHzTZqOkD4Ha4L4ubnngKMp98C6puzz1XPr' \ --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://duck.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" }, "email": "example@example.com" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "routing": { "type": "single", "data": "bankofamerica" } }' ``` - The payment would go through Stripe , as the eligibility analysis would fail ``` Response { "payment_id": "pay_dhTO36kNBB03SWsTvSKC", "merchant_id": "merchant_1716296468", "status": "succeeded", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": 6540, "connector": "stripe", "client_secret": "pay_dhTO36kNBB03SWsTvSKC_secret_siY75j9e6hsgwNuAC3rS", "created": "2024-05-21T13:04:21.786Z", "currency": "INR", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": { "address_line1_check": "pass", "address_postal_code_check": "pass", "cvc_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "example@example.com" }, "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": 1716296661, "expires": 1716300261, "secret": "epk_a404fe01e93d445da59f0a1d7346ad90" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3PIsMcD5R7gDAGff0O0dJvGC", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3PIsMcD5R7gDAGff0O0dJvGC", "payment_link": null, "profile_id": "pro_vucql9T54ccffbKNdOvw", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_41ElW94TenDAaISxhaVj", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-21T13:19:21.786Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-21T13:04:23.236Z", "frm_metadata": null } ```
[ "Cargo.lock", "crates/euclid/src/dssa/graph.rs", "crates/euclid/src/enums.rs", "crates/euclid/src/frontend/dir/enums.rs", "crates/euclid_wasm/src/lib.rs", "crates/hyperswitch_constraint_graph/src/builder.rs", "crates/hyperswitch_constraint_graph/src/graph.rs", "crates/kgraph_utils/Cargo.toml", "crat...
juspay/hyperswitch
juspay__hyperswitch-4699
Bug: [FEATURE]: Add a new endpoint Complete Authorize ### Feature Description Add a new endpoint Complete Authorize ### Possible Implementation - This will be used in the cases where we get shipping after confirm call and we need to call the connector 2nd time. - Collect shipping address in complete authorize call ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index 59e65c0605f..cd1671b2b8e 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -11,10 +11,10 @@ use crate::{ ExtendedCardInfoResponse, PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints, PaymentListFilters, PaymentListFiltersV2, PaymentListResponse, PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelRequest, - PaymentsCaptureRequest, PaymentsExternalAuthenticationRequest, - PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest, - PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsRetrieveRequest, - PaymentsStartRequest, RedirectionResponse, + PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, + PaymentsExternalAuthenticationRequest, PaymentsExternalAuthenticationResponse, + PaymentsIncrementalAuthorizationRequest, PaymentsRejectRequest, PaymentsRequest, + PaymentsResponse, PaymentsRetrieveRequest, PaymentsStartRequest, RedirectionResponse, }, }; impl ApiEventMetric for PaymentsRetrieveRequest { @@ -44,6 +44,14 @@ impl ApiEventMetric for PaymentsCaptureRequest { } } +impl ApiEventMetric for PaymentsCompleteAuthorizeRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Payment { + payment_id: self.payment_id.clone(), + }) + } +} + impl ApiEventMetric for PaymentsCancelRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index f00be78a039..8f4fca59d26 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4343,6 +4343,18 @@ pub struct PaymentRetrieveBodyWithCredentials { pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] +pub struct PaymentsCompleteAuthorizeRequest { + /// The unique identifier for the payment + #[serde(skip_deserializing)] + pub payment_id: String, + /// The shipping address for the payment + pub shipping: Option<Address>, + /// Client Secret + #[schema(value_type = String)] + pub client_secret: Secret<String>, +} + #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index d65fa6868b9..660db4d8b8b 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -202,6 +202,9 @@ pub enum PaymentIntentUpdate { AuthorizationCountUpdate { authorization_count: i32, }, + CompleteAuthorizeUpdate { + shipping_address_id: Option<String>, + }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] @@ -503,6 +506,12 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { authorization_count: Some(authorization_count), ..Default::default() }, + PaymentIntentUpdate::CompleteAuthorizeUpdate { + shipping_address_id, + } => Self { + shipping_address_id, + ..Default::default() + }, } } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 84dc56403c6..1322e66a149 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -203,6 +203,9 @@ pub enum PaymentIntentUpdate { AuthorizationCountUpdate { authorization_count: i32, }, + CompleteAuthorizeUpdate { + shipping_address_id: Option<String>, + }, } #[derive(Clone, Debug, Default)] @@ -425,6 +428,12 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { authorization_count: Some(authorization_count), ..Default::default() }, + PaymentIntentUpdate::CompleteAuthorizeUpdate { + shipping_address_id, + } => Self { + shipping_address_id, + ..Default::default() + }, } } } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 5f5597387b1..018ea342099 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -81,6 +81,7 @@ Never share your secret api keys. Keep them guarded and secure. routes::payments::payments_incremental_authorization, routes::payment_link::payment_link_retrieve, routes::payments::payments_external_authentication, + routes::payments::payments_complete_authorize, // Routes for refunds routes::refunds::refunds_create, @@ -402,6 +403,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::CaptureResponse, api_models::payments::PaymentsIncrementalAuthorizationRequest, api_models::payments::IncrementalAuthorizationResponse, + api_models::payments::PaymentsCompleteAuthorizeRequest, api_models::payments::PaymentsExternalAuthenticationRequest, api_models::payments::PaymentsExternalAuthenticationResponse, api_models::payments::SdkInformation, diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs index 20d87b91e79..1273bde7a36 100644 --- a/crates/openapi/src/routes/payments.rs +++ b/crates/openapi/src/routes/payments.rs @@ -486,3 +486,23 @@ pub fn payments_incremental_authorization() {} security(("publishable_key" = [])) )] pub fn payments_external_authentication() {} + +/// Payments - Complete Authorize +/// +/// +#[utoipa::path( + post, + path = "/{payment_id}/complete_authorize", + request_body=PaymentsCompleteAuthorizeRequest, + params( + ("payment_id" =String, Path, description = "The identifier for payment") + ), + responses( + (status = 200, description = "Payments Complete Authorize Success", body = PaymentsResponse), + (status = 400, description = "Missing mandatory fields") + ), + tag = "Payments", + operation_id = "Complete Authorize a Payment", + security(("publishable_key" = [])) +)] +pub fn payments_complete_authorize() {} 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 a9736516725..3f57ba2830f 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -59,6 +59,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co .setup_future_usage .or(payment_intent.setup_future_usage); + helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; + helpers::validate_payment_status_against_not_allowed_statuses( &payment_intent.status, &[ @@ -173,16 +175,22 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co .or_else(|| request.customer_id.clone()), )?; - let shipping_address = helpers::get_address_by_id( + let shipping_address = helpers::create_or_update_address_for_payment_by_request( db, - payment_intent.shipping_address_id.clone(), + request.shipping.as_ref(), + payment_intent.shipping_address_id.clone().as_deref(), + merchant_id.as_ref(), + payment_intent.customer_id.as_ref(), key_store, - &payment_intent.payment_id, - merchant_id, - merchant_account.storage_scheme, + payment_id.as_ref(), + storage_scheme, ) .await?; + payment_intent.shipping_address_id = shipping_address + .as_ref() + .map(|shipping_address| shipping_address.address_id.clone()); + let billing_address = helpers::get_address_by_id( db, payment_intent.billing_address_id.clone(), @@ -421,11 +429,11 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, - _state: &'b AppState, + state: &'b AppState, _req_state: ReqState, - payment_data: PaymentData<F>, + mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, - _storage_scheme: storage_enums::MerchantStorageScheme, + storage_scheme: storage_enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, _merchant_key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, @@ -434,6 +442,19 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple where F: 'b + Send, { + let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::CompleteAuthorizeUpdate { + shipping_address_id: payment_data.payment_intent.shipping_address_id.clone() + }; + + let db = &*state.store; + let payment_intent = payment_data.payment_intent.clone(); + + let updated_payment_intent = db + .update_payment_intent(payment_intent, payment_intent_update, storage_scheme) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + payment_data.payment_intent = updated_payment_intent; Ok((Box::new(self), payment_data)) } } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 21cc994381e..ba8dd94b332 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -386,7 +386,11 @@ impl Payments { ) .service( web::resource("/{payment_id}/{merchant_id}/redirect/complete/{connector}") - .route(web::get().to(payments_complete_authorize)) + .route(web::get().to(payments_complete_authorize_redirect)) + .route(web::post().to(payments_complete_authorize_redirect)), + ) + .service( + web::resource("/{payment_id}/complete_authorize") .route(web::post().to(payments_complete_authorize)), ) .service( diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 30b582079e3..6a73643ce68 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -121,7 +121,8 @@ impl From<Flow> for ApiIdentifier { | Flow::PaymentsIncrementalAuthorization | Flow::PaymentsExternalAuthentication | Flow::PaymentsAuthorize - | Flow::GetExtendedCardInfo => Self::Payments, + | Flow::GetExtendedCardInfo + | Flow::PaymentsCompleteAuthorize => Self::Payments, Flow::PayoutsCreate | Flow::PayoutsRetrieve diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 06bdd3ed05a..f28cad89004 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -7,6 +7,7 @@ pub mod helpers; use actix_web::{web, Responder}; use api_models::payments::HeaderPayload; use error_stack::report; +use masking::PeekInterface; use router_env::{env, instrument, tracing, types, Flow}; use super::app::ReqState; @@ -749,7 +750,7 @@ pub async fn payments_redirect_response_with_creds_identifier( .await } #[instrument(skip_all, fields(flow =? Flow::PaymentsRedirect, payment_id))] -pub async fn payments_complete_authorize( +pub async fn payments_complete_authorize_redirect( state: web::Data<app::AppState>, req: actix_web::HttpRequest, json_payload: Option<web::Form<serde_json::Value>>, @@ -792,6 +793,70 @@ pub async fn payments_complete_authorize( ) .await } + +/// Payments - Complete Authorize +#[instrument(skip_all, fields(flow =? Flow::PaymentsCompleteAuthorize, payment_id))] +pub async fn payments_complete_authorize( + state: web::Data<app::AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<payment_types::PaymentsCompleteAuthorizeRequest>, + path: web::Path<String>, +) -> impl Responder { + let flow = Flow::PaymentsCompleteAuthorize; + let mut payload = json_payload.into_inner(); + + let payment_id = path.into_inner(); + payload.payment_id.clone_from(&payment_id); + + tracing::Span::current().record("payment_id", &payment_id); + + let payment_confirm_req = payment_types::PaymentsRequest { + payment_id: Some(payment_types::PaymentIdType::PaymentIntentId( + payment_id.clone(), + )), + shipping: payload.shipping.clone(), + client_secret: Some(payload.client_secret.peek().clone()), + ..Default::default() + }; + + let (auth_type, auth_flow) = + match auth::check_client_secret_and_get_auth(req.headers(), &payment_confirm_req) { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(report!(err)), + }; + + let locking_action = payload.get_locking_input(flow.clone()); + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth, _req, req_state| { + payments::payments_core::< + api_types::CompleteAuthorize, + payment_types::PaymentsResponse, + _, + _, + _, + >( + state.clone(), + req_state, + auth.merchant_account, + auth.key_store, + payments::operations::payment_complete_authorize::CompleteAuthorize, + payment_confirm_req.clone(), + auth_flow, + payments::CallConnectorAction::Trigger, + None, + HeaderPayload::default(), + ) + }, + &*auth_type, + locking_action, + )) + .await +} + /// Payments - Cancel /// /// A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action @@ -1465,6 +1530,22 @@ impl GetLockingInput for payments::PaymentsRedirectResponseData { } } +impl GetLockingInput for payment_types::PaymentsCompleteAuthorizeRequest { + fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction + where + F: types::FlowMetric, + lock_utils::ApiIdentifier: From<F>, + { + api_locking::LockAction::Hold { + input: api_locking::LockingInput { + unique_locking_key: self.payment_id.to_owned(), + api_identifier: lock_utils::ApiIdentifier::from(flow), + override_lock_retries: None, + }, + } + } +} + impl GetLockingInput for payment_types::PaymentsCancelRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 9f68cac98c9..a2201936299 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -6,12 +6,13 @@ pub use api_models::payments::{ PaymentListFilters, PaymentListFiltersV2, PaymentListResponse, PaymentListResponseV2, PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp, PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsApproveRequest, - PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsExternalAuthenticationRequest, - PaymentsIncrementalAuthorizationRequest, PaymentsRedirectRequest, PaymentsRedirectionResponse, - PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsResponseForm, - PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse, PaymentsStartRequest, - PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken, TimeRange, UrlDetails, - VerifyRequest, VerifyResponse, WalletData, + PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, + PaymentsExternalAuthenticationRequest, PaymentsIncrementalAuthorizationRequest, + PaymentsRedirectRequest, PaymentsRedirectionResponse, PaymentsRejectRequest, PaymentsRequest, + PaymentsResponse, PaymentsResponseForm, PaymentsRetrieveRequest, PaymentsSessionRequest, + PaymentsSessionResponse, PaymentsStartRequest, PgRedirectResponse, PhoneDetails, + RedirectionResponse, SessionToken, TimeRange, UrlDetails, VerifyRequest, VerifyResponse, + WalletData, }; use error_stack::ResultExt; diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index ffa492bc60d..07a45f5cdbc 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -180,6 +180,8 @@ pub enum Flow { PayoutsAccounts, /// Payments Redirect flow. PaymentsRedirect, + /// Payemnts Complete Authorize Flow + PaymentsCompleteAuthorize, /// Refunds create flow. RefundsCreate, /// Refunds retrieve flow. diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index c7592e48211..720a3b6d024 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -1152,6 +1152,11 @@ impl DataModelExt for PaymentIntentUpdate { } => DieselPaymentIntentUpdate::AuthorizationCountUpdate { authorization_count, }, + Self::CompleteAuthorizeUpdate { + shipping_address_id, + } => DieselPaymentIntentUpdate::CompleteAuthorizeUpdate { + shipping_address_id, + }, } } diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index a3cd88d2ee9..2365f165d65 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -853,6 +853,57 @@ ] } }, + "/{payment_id}/complete_authorize": { + "post": { + "tags": [ + "Payments" + ], + "summary": "Payments - Complete Authorize", + "description": "Payments - Complete Authorize\n\n", + "operationId": "Complete Authorize a Payment", + "parameters": [ + { + "name": "payment_id", + "in": "path", + "description": "The identifier for payment", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentsCompleteAuthorizeRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Payments Complete Authorize Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentsResponse" + } + } + } + }, + "400": { + "description": "Missing mandatory fields" + } + }, + "security": [ + { + "publishable_key": [] + } + ] + } + }, "/refunds": { "post": { "tags": [ @@ -13522,6 +13573,26 @@ } } }, + "PaymentsCompleteAuthorizeRequest": { + "type": "object", + "required": [ + "client_secret" + ], + "properties": { + "shipping": { + "allOf": [ + { + "$ref": "#/components/schemas/Address" + } + ], + "nullable": true + }, + "client_secret": { + "type": "string", + "description": "Client Secret" + } + } + }, "PaymentsConfirmRequest": { "type": "object", "properties": {
2024-05-17T12:56:33Z
## Description - Add a new end point `/{payment_id}/complete_authorize`. - This will be used in the cases where we get shipping after confirm call and we need to call the connector 2nd time. - Collect shipping address in complete authorize call ### 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? 1. Create a Paypal Payment request via Paypal (without adding shipping in request) ``` { "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer223", "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://duck.com", "setup_future_usage": "off_session", "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" }, "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": "paypal", "payment_method_data": { "wallet": { "paypal_redirect": {} } } } ``` Response ``` { "payment_id": "pay_kgDXnhkYLQ19FfXW5HlC", "merchant_id": "merchant_1715932962", "status": "requires_customer_action", "amount": 6540, "net_amount": 6540, "amount_capturable": 6540, "amount_received": null, "connector": "paypal", "client_secret": "pay_kgDXnhkYLQ19FfXW5HlC_secret_cCq0P0y8hP1rOwjjSXQW", "created": "2024-05-17T11:54:56.365Z", "currency": "USD", "customer_id": "StripeCustomer223", "customer": { "id": "StripeCustomer223", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": null, "last_name": null }, "phone": null, "email": 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": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_kgDXnhkYLQ19FfXW5HlC/merchant_1715932962/pay_kgDXnhkYLQ19FfXW5HlC_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "paypal", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer223", "created_at": 1715946896, "expires": 1715950496, "secret": "epk_1612889c945d4948b4ea7df75aa819ec" }, "manual_retry_allowed": null, "connector_transaction_id": "9LY92988UP8943014", "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_kgDXnhkYLQ19FfXW5HlC_1", "payment_link": null, "profile_id": "pro_o6Rw573Vwz3izj70A7ua", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_hmRahHIqSmAlgOR6UQAu", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-17T12:09:56.365Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-17T11:54:58.187Z" } ``` ______________________________________________________________ 2. Hit Complete Authorize end point ``` curl --location '{{baseUrl}}/payments/:id/complete_authorize' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_e41911bdeff647c1bb6e3276e5bc621d' \ --data-raw '{ "shipping": { "address": { "line1": "1467", "line2": "Kormangala", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "guest@example.com" }, "client_secret": "{{client_secret}}" }' ``` Response In Response we should shipping details. ``` { "payment_id": "pay_lxZFT0OfS55HekMEdeJ5", "merchant_id": "merchant_1716021280", "status": "failed", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": null, "connector": "paypal", "client_secret": "pay_lxZFT0OfS55HekMEdeJ5_secret_oHIG40VJWaJv206oQQmV", "created": "2024-05-18T08:34:52.094Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Kormangala", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "guest@example.com" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "guest@example.com" }, "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": "ORDER_NOT_APPROVED", "error_message": "description - Payer has not yet approved the Order for payment. Please redirect the payer to the 'rel':'approve' url returned as part of the HATEOAS links within the Create Order call or provide a valid payment_source in the request. ;", "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "paypal", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": true, "connector_transaction_id": "4Y3612593C2698259", "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_lxZFT0OfS55HekMEdeJ5_1", "payment_link": null, "profile_id": "pro_p0FqSgqYAfU1Z93fJXDo", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bjUetR7rWBdXgCjGLrBa", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-18T08:49:52.094Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-18T08:36:08.387Z", "frm_metadata": null } ``` _________________________________________________________ 3. Retrieve Payment with same payment_id In Response we should shipping details. ``` { "payment_id": "pay_lxZFT0OfS55HekMEdeJ5", "merchant_id": "merchant_1716021280", "status": "failed", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": null, "connector": "paypal", "client_secret": "pay_lxZFT0OfS55HekMEdeJ5_secret_oHIG40VJWaJv206oQQmV", "created": "2024-05-18T08:34:52.094Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Kormangala", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "guest@example.com" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "guest@example.com" }, "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": "ORDER_NOT_APPROVED", "error_message": "description - Payer has not yet approved the Order for payment. Please redirect the payer to the 'rel':'approve' url returned as part of the HATEOAS links within the Create Order call or provide a valid payment_source in the request. ;", "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "paypal", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": true, "connector_transaction_id": "4Y3612593C2698259", "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_lxZFT0OfS55HekMEdeJ5_1", "payment_link": null, "profile_id": "pro_p0FqSgqYAfU1Z93fJXDo", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bjUetR7rWBdXgCjGLrBa", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-18T08:49:52.094Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-18T08:36:08.387Z", "frm_metadata": null } ```
7e44bbca63c1818c0fabdf2734d9b0ae5d639fe1
1. Create a Paypal Payment request via Paypal (without adding shipping in request) ``` { "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer223", "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://duck.com", "setup_future_usage": "off_session", "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" }, "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": "paypal", "payment_method_data": { "wallet": { "paypal_redirect": {} } } } ``` Response ``` { "payment_id": "pay_kgDXnhkYLQ19FfXW5HlC", "merchant_id": "merchant_1715932962", "status": "requires_customer_action", "amount": 6540, "net_amount": 6540, "amount_capturable": 6540, "amount_received": null, "connector": "paypal", "client_secret": "pay_kgDXnhkYLQ19FfXW5HlC_secret_cCq0P0y8hP1rOwjjSXQW", "created": "2024-05-17T11:54:56.365Z", "currency": "USD", "customer_id": "StripeCustomer223", "customer": { "id": "StripeCustomer223", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": null, "last_name": null }, "phone": null, "email": 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": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_kgDXnhkYLQ19FfXW5HlC/merchant_1715932962/pay_kgDXnhkYLQ19FfXW5HlC_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "paypal", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer223", "created_at": 1715946896, "expires": 1715950496, "secret": "epk_1612889c945d4948b4ea7df75aa819ec" }, "manual_retry_allowed": null, "connector_transaction_id": "9LY92988UP8943014", "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_kgDXnhkYLQ19FfXW5HlC_1", "payment_link": null, "profile_id": "pro_o6Rw573Vwz3izj70A7ua", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_hmRahHIqSmAlgOR6UQAu", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-17T12:09:56.365Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-17T11:54:58.187Z" } ``` ______________________________________________________________ 2. Hit Complete Authorize end point ``` curl --location '{{baseUrl}}/payments/:id/complete_authorize' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_e41911bdeff647c1bb6e3276e5bc621d' \ --data-raw '{ "shipping": { "address": { "line1": "1467", "line2": "Kormangala", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "guest@example.com" }, "client_secret": "{{client_secret}}" }' ``` Response In Response we should shipping details. ``` { "payment_id": "pay_lxZFT0OfS55HekMEdeJ5", "merchant_id": "merchant_1716021280", "status": "failed", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": null, "connector": "paypal", "client_secret": "pay_lxZFT0OfS55HekMEdeJ5_secret_oHIG40VJWaJv206oQQmV", "created": "2024-05-18T08:34:52.094Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Kormangala", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "guest@example.com" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "guest@example.com" }, "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": "ORDER_NOT_APPROVED", "error_message": "description - Payer has not yet approved the Order for payment. Please redirect the payer to the 'rel':'approve' url returned as part of the HATEOAS links within the Create Order call or provide a valid payment_source in the request. ;", "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "paypal", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": true, "connector_transaction_id": "4Y3612593C2698259", "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_lxZFT0OfS55HekMEdeJ5_1", "payment_link": null, "profile_id": "pro_p0FqSgqYAfU1Z93fJXDo", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bjUetR7rWBdXgCjGLrBa", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-18T08:49:52.094Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-18T08:36:08.387Z", "frm_metadata": null } ``` _________________________________________________________ 3. Retrieve Payment with same payment_id In Response we should shipping details. ``` { "payment_id": "pay_lxZFT0OfS55HekMEdeJ5", "merchant_id": "merchant_1716021280", "status": "failed", "amount": 6540, "net_amount": 6540, "amount_capturable": 0, "amount_received": null, "connector": "paypal", "client_secret": "pay_lxZFT0OfS55HekMEdeJ5_secret_oHIG40VJWaJv206oQQmV", "created": "2024-05-18T08:34:52.094Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Kormangala", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "guest@example.com" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "guest@example.com" }, "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": "ORDER_NOT_APPROVED", "error_message": "description - Payer has not yet approved the Order for payment. Please redirect the payer to the 'rel':'approve' url returned as part of the HATEOAS links within the Create Order call or provide a valid payment_source in the request. ;", "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "paypal", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": true, "connector_transaction_id": "4Y3612593C2698259", "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_lxZFT0OfS55HekMEdeJ5_1", "payment_link": null, "profile_id": "pro_p0FqSgqYAfU1Z93fJXDo", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bjUetR7rWBdXgCjGLrBa", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-18T08:49:52.094Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-18T08:36:08.387Z", "frm_metadata": null } ```
[ "crates/api_models/src/events/payment.rs", "crates/api_models/src/payments.rs", "crates/diesel_models/src/payment_intent.rs", "crates/hyperswitch_domain_models/src/payments/payment_intent.rs", "crates/openapi/src/openapi.rs", "crates/openapi/src/routes/payments.rs", "crates/router/src/core/payments/oper...
juspay/hyperswitch
juspay__hyperswitch-4670
Bug: [REFACTOR] remove `deref` impl on `Cache` type Currently `Cache` is a type having inner value as `MokaCache`. ``` pub struct Cache { inner: MokaCache<String, Arc<dyn Cacheable>>, } ``` There's a deref impl for this type which returns the inner `MokaCache`. We should instead have custom methods on `Cache` which calls the `MokaCache` methods instead of deref doing the job. There's already custom methods available on `Cache`. Invoke these method instead of calling it on the deref of `Cache`.
diff --git a/crates/router/src/db/cache.rs b/crates/router/src/db/cache.rs index d9db13dde80..ba0aae55e89 100644 --- a/crates/router/src/db/cache.rs +++ b/crates/router/src/db/cache.rs @@ -88,7 +88,7 @@ where Fut: futures::Future<Output = CustomResult<T, errors::StorageError>> + Send, { let data = fun().await?; - in_memory.async_map(|cache| cache.invalidate(key)).await; + in_memory.async_map(|cache| cache.remove(key)).await; let redis_conn = store .get_redis_conn() diff --git a/crates/router/tests/cache.rs b/crates/router/tests/cache.rs index 040e0dddf97..c6eef06db7b 100644 --- a/crates/router/tests/cache.rs +++ b/crates/router/tests/cache.rs @@ -50,8 +50,14 @@ async fn invalidate_existing_cache_success() { let response_body = response.body().await; println!("invalidate Cache: {response:?} : {response_body:?}"); assert_eq!(response.status(), awc::http::StatusCode::OK); - assert!(cache::CONFIG_CACHE.get(&cache_key).await.is_none()); - assert!(cache::ACCOUNTS_CACHE.get(&cache_key).await.is_none()); + assert!(cache::CONFIG_CACHE + .get_val::<String>(&cache_key) + .await + .is_none()); + assert!(cache::ACCOUNTS_CACHE + .get_val::<String>(&cache_key) + .await + .is_none()); } #[actix_web::test] diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs index dc2a2225dc9..4cd2fc0c504 100644 --- a/crates/storage_impl/src/redis/cache.rs +++ b/crates/storage_impl/src/redis/cache.rs @@ -94,13 +94,6 @@ pub struct Cache { inner: MokaCache<String, Arc<dyn Cacheable>>, } -impl std::ops::Deref for Cache { - type Target = MokaCache<String, Arc<dyn Cacheable>>; - fn deref(&self) -> &Self::Target { - &self.inner - } -} - impl Cache { /// With given `time_to_live` and `time_to_idle` creates a moka cache. /// @@ -122,16 +115,16 @@ impl Cache { } pub async fn push<T: Cacheable>(&self, key: String, val: T) { - self.insert(key, Arc::new(val)).await; + self.inner.insert(key, Arc::new(val)).await; } pub async fn get_val<T: Clone + Cacheable>(&self, key: &str) -> Option<T> { - let val = self.get(key).await?; + let val = self.inner.get(key).await?; (*val).as_any().downcast_ref::<T>().cloned() } pub async fn remove(&self, key: &str) { - self.invalidate(key).await; + self.inner.invalidate(key).await; } } @@ -208,7 +201,7 @@ where Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send, { let data = fun().await?; - in_memory.async_map(|cache| cache.invalidate(key)).await; + in_memory.async_map(|cache| cache.remove(key)).await; let redis_conn = store .get_redis_conn() diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs index 349d1872d2a..2922dbcadba 100644 --- a/crates/storage_impl/src/redis/pub_sub.rs +++ b/crates/storage_impl/src/redis/pub_sub.rs @@ -60,16 +60,16 @@ impl PubSubInterface for redis_interface::RedisConnectionPool { let key = match key { CacheKind::Config(key) => { - CONFIG_CACHE.invalidate(key.as_ref()).await; + CONFIG_CACHE.remove(key.as_ref()).await; key } CacheKind::Accounts(key) => { - ACCOUNTS_CACHE.invalidate(key.as_ref()).await; + ACCOUNTS_CACHE.remove(key.as_ref()).await; key } CacheKind::All(key) => { - CONFIG_CACHE.invalidate(key.as_ref()).await; - ACCOUNTS_CACHE.invalidate(key.as_ref()).await; + CONFIG_CACHE.remove(key.as_ref()).await; + ACCOUNTS_CACHE.remove(key.as_ref()).await; key } };
2024-05-17T10:26:23Z
## Description <!-- Describe your changes in detail --> Currently `Cache` is a type having inner value as `MokaCache`. ``` pub struct Cache { inner: MokaCache<String, Arc<dyn Cacheable>>, } ``` There's a deref impl on this type which returns the inner `MokaCache`. We should instead have custom methods on `Cache` which calls the `MokaCache` methods instead of deref doing the job. There's already custom methods available on `Cache`. This PR refactors it to invoke these methods instead of calling it on the deref of `Cache`. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Basic sanity tests should suffice
a62f69d447245273c73611309055d2341a47b783
Basic sanity tests should suffice
[ "crates/router/src/db/cache.rs", "crates/router/tests/cache.rs", "crates/storage_impl/src/redis/cache.rs", "crates/storage_impl/src/redis/pub_sub.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4773
Bug: [FEATURE] Process tracker flow for PaymentMethod Status update ### Feature Description For vaulting flows, currently, the `PaymentMethodStatus` is kept as `awaiting_data` during the generation of client_secret, we want to implement a process tracker flow to update the status to `inactive` upon session expiry. ### Possible Implementation Implementing a new flow for `PaymentMethodStatus` update. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs index 135c8e2b055..342ad8453af 100644 --- a/crates/diesel_models/src/process_tracker.rs +++ b/crates/diesel_models/src/process_tracker.rs @@ -208,6 +208,7 @@ pub enum ProcessTrackerRunner { ApiKeyExpiryWorkflow, OutgoingWebhookRetryWorkflow, AttachPayoutAccountWorkflow, + PaymentMethodStatusUpdateWorkflow, } #[cfg(test)] diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index 167e7a6b6ed..1afc09e5a6a 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -310,6 +310,9 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner { ) } } + storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow => Ok(Box::new( + workflows::payment_method_status_update::PaymentMethodStatusUpdateWorkflow, + )), } }; diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index f0aa0480d09..a4d4f38bfaf 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -8,11 +8,18 @@ use api_models::payments::CardToken; #[cfg(feature = "payouts")] pub use api_models::{enums::PayoutConnectors, payouts as payout_types}; use diesel_models::enums; +use error_stack::ResultExt; use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent}; use router_env::{instrument, tracing}; use crate::{ - core::{errors::RouterResult, payments::helpers, pm_auth as core_pm_auth}, + consts, + core::{ + errors::{self, RouterResult}, + payments::helpers, + pm_auth as core_pm_auth, + }, + db, routes::SessionState, types::{ api::{self, payments}, @@ -20,6 +27,9 @@ use crate::{ }, }; +const PAYMENT_METHOD_STATUS_UPDATE_TASK: &str = "PAYMENT_METHOD_STATUS_UPDATE"; +const PAYMENT_METHOD_STATUS_TAG: &str = "PAYMENT_METHOD_STATUS"; + #[instrument(skip_all)] pub async fn retrieve_payment_method( pm_data: &Option<payments::PaymentMethodData>, @@ -94,6 +104,66 @@ pub async fn retrieve_payment_method( } } +fn generate_task_id_for_payment_method_status_update_workflow( + key_id: &str, + runner: &storage::ProcessTrackerRunner, + task: &str, +) -> String { + format!("{runner}_{task}_{key_id}") +} + +pub async fn add_payment_method_status_update_task( + db: &dyn db::StorageInterface, + payment_method: &diesel_models::PaymentMethod, + prev_status: enums::PaymentMethodStatus, + curr_status: enums::PaymentMethodStatus, + merchant_id: &str, +) -> Result<(), errors::ProcessTrackerError> { + let created_at = payment_method.created_at; + let schedule_time = + created_at.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)); + + let tracking_data = storage::PaymentMethodStatusTrackingData { + payment_method_id: payment_method.payment_method_id.clone(), + prev_status, + curr_status, + merchant_id: merchant_id.to_string(), + }; + + let runner = storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow; + let task = PAYMENT_METHOD_STATUS_UPDATE_TASK; + let tag = [PAYMENT_METHOD_STATUS_TAG]; + + let process_tracker_id = generate_task_id_for_payment_method_status_update_workflow( + payment_method.payment_method_id.as_str(), + &runner, + task, + ); + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + tracking_data, + schedule_time, + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct PAYMENT_METHOD_STATUS_UPDATE process tracker task")?; + + db + .insert_process(process_tracker_entry) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!( + "Failed while inserting PAYMENT_METHOD_STATUS_UPDATE reminder to process_tracker for payment_method_id: {}", + payment_method.payment_method_id.clone() + ) + })?; + + Ok(()) +} + #[instrument(skip_all)] pub async fn retrieve_payment_method_with_token( state: &SessionState, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index fad3e6d918d..ff4517a17d9 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -45,7 +45,9 @@ use crate::{ configs::settings, core::{ errors::{self, StorageErrorExt}, - payment_methods::{transformers as payment_methods, vault}, + payment_methods::{ + add_payment_method_status_update_task, transformers as payment_methods, vault, + }, payments::{ helpers, routing::{self, SessionFlowRoutingInput}, @@ -297,6 +299,21 @@ pub async fn get_client_secret_or_add_payment_method( ) .await?; + if res.status == enums::PaymentMethodStatus::AwaitingData { + add_payment_method_status_update_task( + db, + &res, + enums::PaymentMethodStatus::AwaitingData, + enums::PaymentMethodStatus::Inactive, + merchant_id, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed to add payment method status update task in process tracker", + )?; + } + Ok(services::api::ApplicationResponse::Json( api::PaymentMethodResponse::foreign_from(res), )) @@ -357,7 +374,7 @@ pub async fn add_payment_method_data( .attach_printable("Unable to find payment method")?; if payment_method.status != enums::PaymentMethodStatus::AwaitingData { - return Err((errors::ApiErrorResponse::DuplicatePaymentMethod).into()); + return Err((errors::ApiErrorResponse::ClientSecretExpired).into()); } let customer_id = payment_method.customer_id.clone(); diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index d9f96ef482c..308aa362562 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -110,3 +110,11 @@ impl DerefMut for PaymentsMandateReference { &mut self.0 } } + +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] +pub struct PaymentMethodStatusTrackingData { + pub payment_method_id: String, + pub prev_status: enums::PaymentMethodStatus, + pub curr_status: enums::PaymentMethodStatus, + pub merchant_id: String, +} diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs index 7b29ded5185..2f858c59809 100644 --- a/crates/router/src/workflows.rs +++ b/crates/router/src/workflows.rs @@ -3,6 +3,7 @@ pub mod api_key_expiry; #[cfg(feature = "payouts")] pub mod attach_payout_account_workflow; pub mod outgoing_webhook_retry; +pub mod payment_method_status_update; pub mod payment_sync; pub mod refund_router; pub mod tokenized_data; diff --git a/crates/router/src/workflows/payment_method_status_update.rs b/crates/router/src/workflows/payment_method_status_update.rs new file mode 100644 index 00000000000..b8e57360d90 --- /dev/null +++ b/crates/router/src/workflows/payment_method_status_update.rs @@ -0,0 +1,107 @@ +use common_utils::ext_traits::ValueExt; +use scheduler::{ + consumer::types::process_data, utils as pt_utils, workflows::ProcessTrackerWorkflow, +}; + +use crate::{ + errors, + logger::error, + routes::SessionState, + types::storage::{self, PaymentMethodStatusTrackingData}, +}; + +pub struct PaymentMethodStatusUpdateWorkflow; + +#[async_trait::async_trait] +impl ProcessTrackerWorkflow<SessionState> for PaymentMethodStatusUpdateWorkflow { + async fn execute_workflow<'a>( + &'a self, + state: &'a SessionState, + process: storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + let db = &*state.store; + let tracking_data: PaymentMethodStatusTrackingData = process + .tracking_data + .clone() + .parse_value("PaymentMethodStatusTrackingData")?; + + let retry_count = process.retry_count; + let pm_id = tracking_data.payment_method_id; + let prev_pm_status = tracking_data.prev_status; + let curr_pm_status = tracking_data.curr_status; + let merchant_id = tracking_data.merchant_id; + + let key_store = state + .store + .get_merchant_key_store_by_merchant_id( + merchant_id.as_str(), + &state.store.get_master_key().to_vec().into(), + ) + .await?; + + let merchant_account = db + .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .await?; + + let payment_method = db + .find_payment_method(&pm_id, merchant_account.storage_scheme) + .await?; + + if payment_method.status != prev_pm_status { + return db + .as_scheduler() + .finish_process_with_business_status(process, "PROCESS_ALREADY_COMPLETED") + .await + .map_err(Into::<errors::ProcessTrackerError>::into); + } + + let pm_update = storage::PaymentMethodUpdate::StatusUpdate { + status: Some(curr_pm_status), + }; + + let res = db + .update_payment_method(payment_method, pm_update, merchant_account.storage_scheme) + .await + .map_err(errors::ProcessTrackerError::EStorageError); + + if let Ok(_pm) = res { + db.as_scheduler() + .finish_process_with_business_status(process, "COMPLETED_BY_PT") + .await?; + } else { + let mapping = process_data::PaymentMethodsPTMapping::default(); + let time_delta = if retry_count == 0 { + Some(mapping.default_mapping.start_after) + } else { + pt_utils::get_delay(retry_count + 1, &mapping.default_mapping.frequencies) + }; + + let schedule_time = pt_utils::get_time_from_delta(time_delta); + + match schedule_time { + Some(s_time) => db + .as_scheduler() + .retry_process(process, s_time) + .await + .map_err(Into::<errors::ProcessTrackerError>::into)?, + None => db + .as_scheduler() + .finish_process_with_business_status(process, "RETRIES_EXCEEDED") + .await + .map_err(Into::<errors::ProcessTrackerError>::into)?, + }; + }; + + Ok(()) + } + + async fn error_handler<'a>( + &'a self, + _state: &'a SessionState, + process: storage::ProcessTracker, + _error: errors::ProcessTrackerError, + ) -> errors::CustomResult<(), errors::ProcessTrackerError> { + error!(%process.id, "Failed while executing workflow"); + Ok(()) + } +} diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs index 7f073a8e10b..f3253e0ad34 100644 --- a/crates/scheduler/src/utils.rs +++ b/crates/scheduler/src/utils.rs @@ -342,7 +342,7 @@ pub fn get_outgoing_webhook_retry_schedule_time( } /// Get the delay based on the retry count -fn get_delay<'a>( +pub fn get_delay<'a>( retry_count: i32, frequencies: impl IntoIterator<Item = &'a (i32, i32)>, ) -> Option<i32> {
2024-05-17T07:57:24Z
## Description <!-- Describe your changes in detail --> This PR - - Implemented a process tracker workflow for status update after pm client_secret expiry ### 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)? --> When vaulting is done within session - 1. Create a Payment_method ``` curl --location --request POST 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' \ --data-raw '{ "customer_id": "cus_LALaPcTuxxmCBORKevPC" }' ``` Response - ``` { "merchant_id": "sarthak1", "customer_id": "cus_LALaPcTuxxmCBORKevPC", "payment_method_id": "pm_gnnmqGeng12XWnsr3AWy", "payment_method": null, "payment_method_type": null, "card": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": null, "metadata": null, "created": "2024-06-19T08:58:05.050Z", "last_used_at": null, "client_secret": "pm_gnnmqGeng12XWnsr3AWy_secret_ikc5JKsFFREjtR9hk5Co" } ``` 2. Vault using `/save` ``` curl --location --request POST 'http://localhost:8080/payment_methods/pm_gnnmqGeng12XWnsr3AWy/save' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_16e38a16176e45298a70da6c56c5028d' \ --data-raw '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "visa", "client_secret": "pm_gnnmqGeng12XWnsr3AWy_secret_ikc5JKsFFREjtR9hk5Co", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "08", "card_exp_year": "2028", "card_holder_name": "joseph" } } }' ``` Response - ``` { "merchant_id": "sarthak1", "customer_id": null, "payment_method_id": "pm_gnnmqGeng12XWnsr3AWy", "payment_method": "card", "payment_method_type": "credit", "card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "08", "expiry_year": "2028", "card_token": null, "card_holder_name": "joseph", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "metadata": null, "created": "2024-06-19T08:58:19.752Z", "last_used_at": "2024-06-19T08:58:19.752Z", "client_secret": "pm_gnnmqGeng12XWnsr3AWy_secret_ikc5JKsFFREjtR9hk5Co" } ``` DB entry for PT - <img width="1509" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/427e090a-79c0-4efe-ad6a-52968f71bdfb"> When vaulting is not done within session - 1. Create Payment method - ``` curl --location --request POST 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' \ --data-raw '{ "customer_id": "cus_LALaPcTuxxmCBORKevPC" }' ``` Response - ``` { "merchant_id": "sarthak1", "customer_id": "cus_LALaPcTuxxmCBORKevPC", "payment_method_id": "pm_LlMdO3mS6HQ9EJLfDpL3", "payment_method": null, "payment_method_type": null, "card": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": null, "metadata": null, "created": "2024-06-19T09:04:11.634Z", "last_used_at": null, "client_secret": "pm_LlMdO3mS6HQ9EJLfDpL3_secret_4565heI7J2bLsBgTLbJ5" } ``` 2. Vault using `/save` after session expiry - ``` curl --location --request POST 'http://localhost:8080/payment_methods/pm_LlMdO3mS6HQ9EJLfDpL3/save' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_16e38a16176e45298a70da6c56c5028d' \ --data-raw '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "visa", "client_secret": "pm_LlMdO3mS6HQ9EJLfDpL3_secret_4565heI7J2bLsBgTLbJ5", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "08", "card_exp_year": "2028", "card_holder_name": "joseph" } } }' ``` Response - ``` { "error": { "type": "invalid_request", "message": "The payment method with the specified details already exists in our records", "code": "HE_01" } } ``` DB entry after session expiry - <img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/4c574e3d-48f7-4844-b493-a306c1ac3c5a"> <img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/60daa679-d78a-438d-bc3c-7ad769363014">
f84ed6a8a00cd5f28debfbc1bb1f8dba14eaa387
When vaulting is done within session - 1. Create a Payment_method ``` curl --location --request POST 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' \ --data-raw '{ "customer_id": "cus_LALaPcTuxxmCBORKevPC" }' ``` Response - ``` { "merchant_id": "sarthak1", "customer_id": "cus_LALaPcTuxxmCBORKevPC", "payment_method_id": "pm_gnnmqGeng12XWnsr3AWy", "payment_method": null, "payment_method_type": null, "card": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": null, "metadata": null, "created": "2024-06-19T08:58:05.050Z", "last_used_at": null, "client_secret": "pm_gnnmqGeng12XWnsr3AWy_secret_ikc5JKsFFREjtR9hk5Co" } ``` 2. Vault using `/save` ``` curl --location --request POST 'http://localhost:8080/payment_methods/pm_gnnmqGeng12XWnsr3AWy/save' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_16e38a16176e45298a70da6c56c5028d' \ --data-raw '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "visa", "client_secret": "pm_gnnmqGeng12XWnsr3AWy_secret_ikc5JKsFFREjtR9hk5Co", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "08", "card_exp_year": "2028", "card_holder_name": "joseph" } } }' ``` Response - ``` { "merchant_id": "sarthak1", "customer_id": null, "payment_method_id": "pm_gnnmqGeng12XWnsr3AWy", "payment_method": "card", "payment_method_type": "credit", "card": { "scheme": null, "issuer_country": null, "last4_digits": "4242", "expiry_month": "08", "expiry_year": "2028", "card_token": null, "card_holder_name": "joseph", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "424242", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "metadata": null, "created": "2024-06-19T08:58:19.752Z", "last_used_at": "2024-06-19T08:58:19.752Z", "client_secret": "pm_gnnmqGeng12XWnsr3AWy_secret_ikc5JKsFFREjtR9hk5Co" } ``` DB entry for PT - <img width="1509" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/427e090a-79c0-4efe-ad6a-52968f71bdfb"> When vaulting is not done within session - 1. Create Payment method - ``` curl --location --request POST 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' \ --data-raw '{ "customer_id": "cus_LALaPcTuxxmCBORKevPC" }' ``` Response - ``` { "merchant_id": "sarthak1", "customer_id": "cus_LALaPcTuxxmCBORKevPC", "payment_method_id": "pm_LlMdO3mS6HQ9EJLfDpL3", "payment_method": null, "payment_method_type": null, "card": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": null, "metadata": null, "created": "2024-06-19T09:04:11.634Z", "last_used_at": null, "client_secret": "pm_LlMdO3mS6HQ9EJLfDpL3_secret_4565heI7J2bLsBgTLbJ5" } ``` 2. Vault using `/save` after session expiry - ``` curl --location --request POST 'http://localhost:8080/payment_methods/pm_LlMdO3mS6HQ9EJLfDpL3/save' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_16e38a16176e45298a70da6c56c5028d' \ --data-raw '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "visa", "client_secret": "pm_LlMdO3mS6HQ9EJLfDpL3_secret_4565heI7J2bLsBgTLbJ5", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "08", "card_exp_year": "2028", "card_holder_name": "joseph" } } }' ``` Response - ``` { "error": { "type": "invalid_request", "message": "The payment method with the specified details already exists in our records", "code": "HE_01" } } ``` DB entry after session expiry - <img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/4c574e3d-48f7-4844-b493-a306c1ac3c5a"> <img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/60daa679-d78a-438d-bc3c-7ad769363014">
[ "crates/diesel_models/src/process_tracker.rs", "crates/router/src/bin/scheduler.rs", "crates/router/src/core/payment_methods.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/types/storage/payment_method.rs", "crates/router/src/workflows.rs", "crates/router/src/workflows/payment...
juspay/hyperswitch
juspay__hyperswitch-4663
Bug: refactor session call to remove the shipping and billing parameter fields if null for apple pay and google pay remove the shipping and billing parameter fields if null for apple pay and google pay as it not necessary to pass
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index dcabbde7ebe..d7ba24b5a3e 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -3872,6 +3872,7 @@ pub struct GpayAllowedMethodsParameters { /// Is billing address required pub billing_address_required: Option<bool>, /// Billing address parameters + #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, } @@ -4247,7 +4248,9 @@ pub struct ApplePayPaymentRequest { pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector + #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, + #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, }
2024-05-16T11:50:28Z
## Description <!-- Describe your changes in detail --> remove the shipping and billing parameter fields if null for apple pay and google pay. ### 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)? --> -> Apple pay payment create with confirm false ``` { "amount": 650, "currency": "USD", "confirm": false, "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", "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":"eyJkYXRhIjoiQ1ZoTGd5RGU3TzZjdFlhWHFiVWFONFZvRjBCQjhTbDZsenlXYUdCKzhKcXlic2hYVGxoNEFEcTZYb0t6ZWVSVGwvcUp6NDIvUFMwcmMxMCtqSyt5Z1F5NnlkT25EcnVDeVpkaVU4SWFGOEtOS2hJMFFKOU9JTk9aWFlYR0VzZEczNXlVNzcrQ0k1dk5lUjJiK1gyUXZTVTMzSjlOczJuTFRXZHpwb1VUSHJKU1RiSmFmTTlxYjlZOHZuZS9vZUdHQkV1ZU9DQWQxcFhjRE54SEl2dlc5Z0x3WXRPVldKZUEvUnh5MEdsb0VISng3VEhqUEVQUGJwMkVVZjRMQXZQOGlJSEpmUjM0THdEUVBIdmNSeW9nalRJSzJqOXZjUGRqS2xBSG1LUm5wZlhvWkY4VE16ZUJ6eWhGb0dKY3ZRa3JMc216OEcxTXowZGxlV2VmU2V0TkYxT1NMaldCdExrUXpvWG5xdU1ZeExMenU2SkxPZ1E5ejN1OStFNGQ2NHRZS1NYYlZBWGRKNXRMNTdvbSIsInNpZ25hdHVyZSI6Ik1JQUdDU3FHU0liM0RRRUhBcUNBTUlBQ0FRRXhEVEFMQmdsZ2hrZ0JaUU1FQWdFd2dBWUpLb1pJaHZjTkFRY0JBQUNnZ0RDQ0ErTXdnZ09Jb0FNQ0FRSUNDRXd3UVVsUm5WUTJNQW9HQ0NxR1NNNDlCQU1DTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekFlRncweE9UQTFNVGd3TVRNeU5UZGFGdzB5TkRBMU1UWXdNVE15TlRkYU1GOHhKVEFqQmdOVkJBTU1IR1ZqWXkxemJYQXRZbkp2YTJWeUxYTnBaMjVmVlVNMExWQlNUMFF4RkRBU0JnTlZCQXNNQzJsUFV5QlRlWE4wWlcxek1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpCWk1CTUdCeXFHU000OUFnRUdDQ3FHU000OUF3RUhBMElBQk1JVmQrM3Ixc2V5SVk5bzNYQ1FvU0dOeDdDOWJ5d29QWVJnbGRsSzlLVkJHNE5DRHRnUjgwQitnek1mSEZURDkrc3lJTmE2MWRUdjlKS0ppVDU4RHhPamdnSVJNSUlDRFRBTUJnTlZIUk1CQWY4RUFqQUFNQjhHQTFVZEl3UVlNQmFBRkNQeVNjUlBrK1R2SitiRTlpaHNQNks3L1M1TE1FVUdDQ3NHQVFVRkJ3RUJCRGt3TnpBMUJnZ3JCZ0VGQlFjd0FZWXBhSFIwY0RvdkwyOWpjM0F1WVhCd2JHVXVZMjl0TDI5amMzQXdOQzFoY0hCc1pXRnBZMkV6TURJd2dnRWRCZ05WSFNBRWdnRVVNSUlCRURDQ0FRd0dDU3FHU0liM1kyUUZBVENCL2pDQnd3WUlLd1lCQlFVSEFnSXdnYllNZ2JOU1pXeHBZVzVqWlNCdmJpQjBhR2x6SUdObGNuUnBabWxqWVhSbElHSjVJR0Z1ZVNCd1lYSjBlU0JoYzNOMWJXVnpJR0ZqWTJWd2RHRnVZMlVnYjJZZ2RHaGxJSFJvWlc0Z1lYQndiR2xqWVdKc1pTQnpkR0Z1WkdGeVpDQjBaWEp0Y3lCaGJtUWdZMjl1WkdsMGFXOXVjeUJ2WmlCMWMyVXNJR05sY25ScFptbGpZWFJsSUhCdmJHbGplU0JoYm1RZ1kyVnlkR2xtYVdOaGRHbHZiaUJ3Y21GamRHbGpaU0J6ZEdGMFpXMWxiblJ6TGpBMkJnZ3JCZ0VGQlFjQ0FSWXFhSFIwY0RvdkwzZDNkeTVoY0hCc1pTNWpiMjB2WTJWeWRHbG1hV05oZEdWaGRYUm9iM0pwZEhrdk1EUUdBMVVkSHdRdE1Dc3dLYUFub0NXR0kyaDBkSEE2THk5amNtd3VZWEJ3YkdVdVkyOXRMMkZ3Y0d4bFlXbGpZVE11WTNKc01CMEdBMVVkRGdRV0JCU1VWOXR2MVhTQmhvbUpkaTkrVjRVSDU1dFlKREFPQmdOVkhROEJBZjhFQkFNQ0I0QXdEd1lKS29aSWh2ZGpaQVlkQkFJRkFEQUtCZ2dxaGtqT1BRUURBZ05KQURCR0FpRUF2Z2xYSCtjZUhuTmJWZVd2ckxUSEwrdEVYekFZVWlMSEpSQUN0aDY5YjFVQ0lRRFJpelVLWGRiZGJyRjBZRFd4SHJMT2g4K2o1cTlzdllPQWlRM0lMTjJxWXpDQ0F1NHdnZ0oxb0FNQ0FRSUNDRWx0TDc4Nm1OcVhNQW9HQ0NxR1NNNDlCQU1DTUdjeEd6QVpCZ05WQkFNTUVrRndjR3hsSUZKdmIzUWdRMEVnTFNCSE16RW1NQ1FHQTFVRUN3d2RRWEJ3YkdVZ1EyVnlkR2xtYVdOaGRHbHZiaUJCZFhSb2IzSnBkSGt4RXpBUkJnTlZCQW9NQ2tGd2NHeGxJRWx1WXk0eEN6QUpCZ05WQkFZVEFsVlRNQjRYRFRFME1EVXdOakl6TkRZek1Gb1hEVEk1TURVd05qSXpORFl6TUZvd2VqRXVNQ3dHQTFVRUF3d2xRWEJ3YkdVZ1FYQndiR2xqWVhScGIyNGdTVzUwWldkeVlYUnBiMjRnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFOEJjUmhCblhaSVhWR2w0bGdRZDI2SUNpNzk1N3JrM2dqZnhMaytFelZ0Vm1Xeld1SXRDWGRnMGlUbnU2Q1AxMkY4Nkl5M2E3Wm5DK3lPZ3BoUDlVUmFPQjl6Q0I5REJHQmdnckJnRUZCUWNCQVFRNk1EZ3dOZ1lJS3dZQkJRVUhNQUdHS21oMGRIQTZMeTl2WTNOd0xtRndjR3hsTG1OdmJTOXZZM053TURRdFlYQndiR1Z5YjI5MFkyRm5NekFkQmdOVkhRNEVGZ1FVSS9KSnhFK1Q1TzhuNXNUMktHdy9vcnY5TGtzd0R3WURWUjBUQVFIL0JBVXdBd0VCL3pBZkJnTlZIU01FR0RBV2dCUzdzTjZoV0RPSW1xU0ttZDYrdmV1djJzc2txekEzQmdOVkhSOEVNREF1TUN5Z0txQW9oaVpvZEhSd09pOHZZM0pzTG1Gd2NHeGxMbU52YlM5aGNIQnNaWEp2YjNSallXY3pMbU55YkRBT0JnTlZIUThCQWY4RUJBTUNBUVl3RUFZS0tvWklodmRqWkFZQ0RnUUNCUUF3Q2dZSUtvWkl6ajBFQXdJRFp3QXdaQUl3T3M5eWcxRVdtYkdHK3pYRFZzcGl2L1FYN2RrUGRVMmlqcjd4bklGZVFyZUorSmozbTFtZm1OVkJEWStkNmNMK0FqQXlMZFZFSWJDakJYZHNYZk00TzVCbi9SZDhMQ0Z0bGsvR2NtbUNFbTlVK0hwOUc1bkxtd21KSVdFR21ROEpraDBBQURHQ0FZZ3dnZ0dFQWdFQk1JR0dNSG94TGpBc0JnTlZCQU1NSlVGd2NHeGxJRUZ3Y0d4cFkyRjBhVzl1SUVsdWRHVm5jbUYwYVc5dUlFTkJJQzBnUnpNeEpqQWtCZ05WQkFzTUhVRndjR3hsSUVObGNuUnBabWxqWVhScGIyNGdRWFYwYUc5eWFYUjVNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV3SUlUREJCU1ZHZFZEWXdDd1lKWUlaSUFXVURCQUlCb0lHVE1CZ0dDU3FHU0liM0RRRUpBekVMQmdrcWhraUc5dzBCQndFd0hBWUpLb1pJaHZjTkFRa0ZNUThYRFRJME1ETXhOREE1TkRNeU0xb3dLQVlKS29aSWh2Y05BUWswTVJzdNTdMRElUVUQwcVI3RHd5SGx1VG0xMjJCejA5c2FzMkJVWitFRTlVPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXBoMkNUKytubXZpYjU3YWNJZmVKTjFCQmJyZUEveG84N2p1b0xETDFnS1IvYy9wRDZYK0xKSGRYUGJnMFBIT3pYYjJFYm5RR1ZWYmZIWHRkQzBYTTdBPT0iLCJ0cmFuc2FjdGlvbklkIjoiMjBlYzhlM2I2N2YyYmNmMDExMDVmODAwNmEwNWFmNTRiNjBkZDIwMzgyOTdlMmExMmI0Y2FlNDY0ODhjYjZhOSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } } ``` -> Make a `/session` call ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: api_key' \ --data '{ "payment_id": "pay_oit9SUYrdsYlI0WvCh1L", "wallets": [], "client_secret": "pay_oit9SUYrdsYlI0WvCh1L_secret_N61PV7OLGKa7PI0dv2Wo" }' ``` Since the business profile config is not enabled the shipping details field is not present ![image (3)](https://github.com/juspay/hyperswitch/assets/83439957/04b91f04-289f-4846-a241-2c9bd65dbd4f)
4b5b558dae8d2fefb66b8b16c486f07e3e800758
-> Apple pay payment create with confirm false ``` { "amount": 650, "currency": "USD", "confirm": false, "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", "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":"eyJkYXRhIjoiQ1ZoTGd5RGU3TzZjdFlhWHFiVWFONFZvRjBCQjhTbDZsenlXYUdCKzhKcXlic2hYVGxoNEFEcTZYb0t6ZWVSVGwvcUp6NDIvUFMwcmMxMCtqSyt5Z1F5NnlkT25EcnVDeVpkaVU4SWFGOEtOS2hJMFFKOU9JTk9aWFlYR0VzZEczNXlVNzcrQ0k1dk5lUjJiK1gyUXZTVTMzSjlOczJuTFRXZHpwb1VUSHJKU1RiSmFmTTlxYjlZOHZuZS9vZUdHQkV1ZU9DQWQxcFhjRE54SEl2dlc5Z0x3WXRPVldKZUEvUnh5MEdsb0VISng3VEhqUEVQUGJwMkVVZjRMQXZQOGlJSEpmUjM0THdEUVBIdmNSeW9nalRJSzJqOXZjUGRqS2xBSG1LUm5wZlhvWkY4VE16ZUJ6eWhGb0dKY3ZRa3JMc216OEcxTXowZGxlV2VmU2V0TkYxT1NMaldCdExrUXpvWG5xdU1ZeExMenU2SkxPZ1E5ejN1OStFNGQ2NHRZS1NYYlZBWGRKNXRMNTdvbSIsInNpZ25hdHVyZSI6Ik1JQUdDU3FHU0liM0RRRUhBcUNBTUlBQ0FRRXhEVEFMQmdsZ2hrZ0JaUU1FQWdFd2dBWUpLb1pJaHZjTkFRY0JBQUNnZ0RDQ0ErTXdnZ09Jb0FNQ0FRSUNDRXd3UVVsUm5WUTJNQW9HQ0NxR1NNNDlCQU1DTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekFlRncweE9UQTFNVGd3TVRNeU5UZGFGdzB5TkRBMU1UWXdNVE15TlRkYU1GOHhKVEFqQmdOVkJBTU1IR1ZqWXkxemJYQXRZbkp2YTJWeUxYTnBaMjVmVlVNMExWQlNUMFF4RkRBU0JnTlZCQXNNQzJsUFV5QlRlWE4wWlcxek1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpCWk1CTUdCeXFHU000OUFnRUdDQ3FHU000OUF3RUhBMElBQk1JVmQrM3Ixc2V5SVk5bzNYQ1FvU0dOeDdDOWJ5d29QWVJnbGRsSzlLVkJHNE5DRHRnUjgwQitnek1mSEZURDkrc3lJTmE2MWRUdjlKS0ppVDU4RHhPamdnSVJNSUlDRFRBTUJnTlZIUk1CQWY4RUFqQUFNQjhHQTFVZEl3UVlNQmFBRkNQeVNjUlBrK1R2SitiRTlpaHNQNks3L1M1TE1FVUdDQ3NHQVFVRkJ3RUJCRGt3TnpBMUJnZ3JCZ0VGQlFjd0FZWXBhSFIwY0RvdkwyOWpjM0F1WVhCd2JHVXVZMjl0TDI5amMzQXdOQzFoY0hCc1pXRnBZMkV6TURJd2dnRWRCZ05WSFNBRWdnRVVNSUlCRURDQ0FRd0dDU3FHU0liM1kyUUZBVENCL2pDQnd3WUlLd1lCQlFVSEFnSXdnYllNZ2JOU1pXeHBZVzVqWlNCdmJpQjBhR2x6SUdObGNuUnBabWxqWVhSbElHSjVJR0Z1ZVNCd1lYSjBlU0JoYzNOMWJXVnpJR0ZqWTJWd2RHRnVZMlVnYjJZZ2RHaGxJSFJvWlc0Z1lYQndiR2xqWVdKc1pTQnpkR0Z1WkdGeVpDQjBaWEp0Y3lCaGJtUWdZMjl1WkdsMGFXOXVjeUJ2WmlCMWMyVXNJR05sY25ScFptbGpZWFJsSUhCdmJHbGplU0JoYm1RZ1kyVnlkR2xtYVdOaGRHbHZiaUJ3Y21GamRHbGpaU0J6ZEdGMFpXMWxiblJ6TGpBMkJnZ3JCZ0VGQlFjQ0FSWXFhSFIwY0RvdkwzZDNkeTVoY0hCc1pTNWpiMjB2WTJWeWRHbG1hV05oZEdWaGRYUm9iM0pwZEhrdk1EUUdBMVVkSHdRdE1Dc3dLYUFub0NXR0kyaDBkSEE2THk5amNtd3VZWEJ3YkdVdVkyOXRMMkZ3Y0d4bFlXbGpZVE11WTNKc01CMEdBMVVkRGdRV0JCU1VWOXR2MVhTQmhvbUpkaTkrVjRVSDU1dFlKREFPQmdOVkhROEJBZjhFQkFNQ0I0QXdEd1lKS29aSWh2ZGpaQVlkQkFJRkFEQUtCZ2dxaGtqT1BRUURBZ05KQURCR0FpRUF2Z2xYSCtjZUhuTmJWZVd2ckxUSEwrdEVYekFZVWlMSEpSQUN0aDY5YjFVQ0lRRFJpelVLWGRiZGJyRjBZRFd4SHJMT2g4K2o1cTlzdllPQWlRM0lMTjJxWXpDQ0F1NHdnZ0oxb0FNQ0FRSUNDRWx0TDc4Nm1OcVhNQW9HQ0NxR1NNNDlCQU1DTUdjeEd6QVpCZ05WQkFNTUVrRndjR3hsSUZKdmIzUWdRMEVnTFNCSE16RW1NQ1FHQTFVRUN3d2RRWEJ3YkdVZ1EyVnlkR2xtYVdOaGRHbHZiaUJCZFhSb2IzSnBkSGt4RXpBUkJnTlZCQW9NQ2tGd2NHeGxJRWx1WXk0eEN6QUpCZ05WQkFZVEFsVlRNQjRYRFRFME1EVXdOakl6TkRZek1Gb1hEVEk1TURVd05qSXpORFl6TUZvd2VqRXVNQ3dHQTFVRUF3d2xRWEJ3YkdVZ1FYQndiR2xqWVhScGIyNGdTVzUwWldkeVlYUnBiMjRnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFOEJjUmhCblhaSVhWR2w0bGdRZDI2SUNpNzk1N3JrM2dqZnhMaytFelZ0Vm1Xeld1SXRDWGRnMGlUbnU2Q1AxMkY4Nkl5M2E3Wm5DK3lPZ3BoUDlVUmFPQjl6Q0I5REJHQmdnckJnRUZCUWNCQVFRNk1EZ3dOZ1lJS3dZQkJRVUhNQUdHS21oMGRIQTZMeTl2WTNOd0xtRndjR3hsTG1OdmJTOXZZM053TURRdFlYQndiR1Z5YjI5MFkyRm5NekFkQmdOVkhRNEVGZ1FVSS9KSnhFK1Q1TzhuNXNUMktHdy9vcnY5TGtzd0R3WURWUjBUQVFIL0JBVXdBd0VCL3pBZkJnTlZIU01FR0RBV2dCUzdzTjZoV0RPSW1xU0ttZDYrdmV1djJzc2txekEzQmdOVkhSOEVNREF1TUN5Z0txQW9oaVpvZEhSd09pOHZZM0pzTG1Gd2NHeGxMbU52YlM5aGNIQnNaWEp2YjNSallXY3pMbU55YkRBT0JnTlZIUThCQWY4RUJBTUNBUVl3RUFZS0tvWklodmRqWkFZQ0RnUUNCUUF3Q2dZSUtvWkl6ajBFQXdJRFp3QXdaQUl3T3M5eWcxRVdtYkdHK3pYRFZzcGl2L1FYN2RrUGRVMmlqcjd4bklGZVFyZUorSmozbTFtZm1OVkJEWStkNmNMK0FqQXlMZFZFSWJDakJYZHNYZk00TzVCbi9SZDhMQ0Z0bGsvR2NtbUNFbTlVK0hwOUc1bkxtd21KSVdFR21ROEpraDBBQURHQ0FZZ3dnZ0dFQWdFQk1JR0dNSG94TGpBc0JnTlZCQU1NSlVGd2NHeGxJRUZ3Y0d4cFkyRjBhVzl1SUVsdWRHVm5jbUYwYVc5dUlFTkJJQzBnUnpNeEpqQWtCZ05WQkFzTUhVRndjR3hsSUVObGNuUnBabWxqWVhScGIyNGdRWFYwYUc5eWFYUjVNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV3SUlUREJCU1ZHZFZEWXdDd1lKWUlaSUFXVURCQUlCb0lHVE1CZ0dDU3FHU0liM0RRRUpBekVMQmdrcWhraUc5dzBCQndFd0hBWUpLb1pJaHZjTkFRa0ZNUThYRFRJME1ETXhOREE1TkRNeU0xb3dLQVlKS29aSWh2Y05BUWswTVJzdNTdMRElUVUQwcVI3RHd5SGx1VG0xMjJCejA5c2FzMkJVWitFRTlVPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXBoMkNUKytubXZpYjU3YWNJZmVKTjFCQmJyZUEveG84N2p1b0xETDFnS1IvYy9wRDZYK0xKSGRYUGJnMFBIT3pYYjJFYm5RR1ZWYmZIWHRkQzBYTTdBPT0iLCJ0cmFuc2FjdGlvbklkIjoiMjBlYzhlM2I2N2YyYmNmMDExMDVmODAwNmEwNWFmNTRiNjBkZDIwMzgyOTdlMmExMmI0Y2FlNDY0ODhjYjZhOSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } } ``` -> Make a `/session` call ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: api_key' \ --data '{ "payment_id": "pay_oit9SUYrdsYlI0WvCh1L", "wallets": [], "client_secret": "pay_oit9SUYrdsYlI0WvCh1L_secret_N61PV7OLGKa7PI0dv2Wo" }' ``` Since the business profile config is not enabled the shipping details field is not present ![image (3)](https://github.com/juspay/hyperswitch/assets/83439957/04b91f04-289f-4846-a241-2c9bd65dbd4f)
[ "crates/api_models/src/payments.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4666
Bug: Creating a payment will shutdown the server due to stack overflow ### Discussed in https://github.com/juspay/hyperswitch/discussions/4636 <div type='discussions-op-text'> <sup>Originally posted by **Rudy-Zidan** May 14, 2024</sup> When ever i try to run the hyperswitch-web a call to "create-payment-intent" being triggered which will fail for empty reason from the server side i see the following logs: ``` hyperswitch-hyperswitch-server-1 | {"message":"[SERVER_WRAP - EVENT] router::services::api","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"INFO","target":"router::services::api","service":"router","line":1143,"file":"crates/router/src/services/api.rs","fn":"server_wrap","full_name":"router::services::api::server_wrap","time":"2024-05-13T20:54:41.169167836Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","flow":"PaymentsCreate","extra":{"headers":"{\"accept-encoding\": \"**MASKED**\", \"host\": \"**MASKED**\", \"connection\": \"**MASKED**\", \"content-length\": \"**MASKED**\", \"accept\": \"**MASKED**\", \"user-agent\": \"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)\", \"api-key\": \"**MASKED**\", \"content-type\": \"**MASKED**\"}","tag":"BeginRequest","payload":"PaymentsRequest { amount: Some(Value(2999)), currency: Some(USD), amount_to_capture: None, payment_id: Some(PaymentIntentId(\"pay_ey8XCkOrX9XWspjLqoTD\")), merchant_id: None, routing: None, connector: None, capture_method: Some(Automatic), authentication_type: Some(ThreeDs), billing: Some(Address { address: Some(AddressDetails { city: Some(\"San Fransico\"), country: Some(US), line1: Some(*** alloc::string::String ***), line2: Some(*** alloc::string::String ***), line3: Some(*** alloc::string::String ***), zip: Some(*** alloc::string::String ***), state: Some(*** alloc::string::String ***), first_name: Some(*** alloc::string::String ***), last_name: Some(*** alloc::string::String ***) }), phone: Some(PhoneDetails { number: Some(*** alloc::string::String ***), country_code: Some(\"+91\") }), email: None }), capture_on: None, confirm: Some(false), customer: None, customer_id: Some(\"hyperswitch_sdk_demo_id\"), email: Some(Email(***********************@gmail.com)), name: None, phone: None, phone_country_code: None, off_session: None, description: Some(\"Hello this is description\"), return_url: None, setup_future_usage: None, payment_method_data: None, payment_method: None, payment_token: None, card_cvc: None, shipping: Some(Address { address: Some(AddressDetails { city: Some(\"Banglore\"), country: Some(US), line1: Some(*** alloc::string::String ***), line2: Some(*** alloc::string::String ***), line3: Some(*** alloc::string::String ***), zip: Some(*** alloc::string::String ***), state: Some(*** alloc::string::String ***), first_name: Some(*** alloc::string::String ***), last_name: Some(*** alloc::string::String ***) }), phone: Some(PhoneDetails { number: Some(*** alloc::string::String ***), country_code: Some(\"+1\") }), email: None }), statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: Some([OrderDetailsWithAmount { product_name: \"Apple iphone 15\", quantity: 1, amount: 2999, requires_shipping: None, product_img_link: None, product_id: None, category: None, brand: None, product_type: None }]), client_secret: None, mandate_data: None, customer_acceptance: None, mandate_id: None, browser_info: None, payment_experience: None, payment_method_type: None, business_country: None, business_label: None, merchant_connector_details: None, allowed_payment_method_types: None, business_sub_label: None, retry_action: None, metadata: Some(*** serde_json::value::Value ***), connector_metadata: Some(ConnectorMetadata { apple_pay: None, airwallex: None, noon: Some(NoonData { order_category: Some(\"applepay\") }) }), feature_metadata: None, payment_link: None, payment_link_config: None, profile_id: None, surcharge_details: None, payment_type: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, recurring_details: None }","http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"pay_ey8XCkOrX9XWspjLqoTD","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}} hyperswitch-hyperswitch-server-1 | {"message":"[GET_OR_POPULATE_REDIS - EVENT] diesel_models::query::generics","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"DEBUG","target":"diesel_models::query::generics","service":"router","line":376,"file":"crates/diesel_models/src/query/generics.rs","fn":"get_or_populate_redis","full_name":"diesel_models::query::generics::get_or_populate_redis","time":"2024-05-13T20:54:41.200493378Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","flow":"PaymentsCreate","extra":{"query":"SELECT \"api_keys\".\"key_id\", \"api_keys\".\"merchant_id\", \"api_keys\".\"name\", \"api_keys\".\"description\", \"api_keys\".\"hashed_api_key\", \"api_keys\".\"prefix\", \"api_keys\".\"created_at\", \"api_keys\".\"expires_at\", \"api_keys\".\"last_used\" FROM \"api_keys\" WHERE (\"api_keys\".\"hashed_api_key\" = $1) -- binds: [HashedApiKey(\"0e1be6b9d0b81d7ad11a839e2a7c1e5a8b4c206c4cdb30fea9a2971415db42f1\")]","http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"pay_ey8XCkOrX9XWspjLqoTD","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}} hyperswitch-hyperswitch-server-1 | {"message":"[PERFORM_LOCKING_ACTION - EVENT] Lock acquired for locking input LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None }","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"INFO","target":"router::core::api_locking","service":"router","line":83,"file":"crates/router/src/core/api_locking.rs","fn":"perform_locking_action","full_name":"router::core::api_locking::perform_locking_action","time":"2024-05-13T20:54:41.221458336Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","merchant_id":"merchant_1715629529","flow":"PaymentsCreate","extra":{"http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"pay_ey8XCkOrX9XWspjLqoTD","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}} hyperswitch-hyperswitch-server-1 | {"message":"[FIND_BUSINESS_PROFILE_BY_PROFILE_ID - EVENT] diesel_models::query::generics","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"DEBUG","target":"diesel_models::query::generics","service":"router","line":376,"file":"crates/diesel_models/src/query/generics.rs","fn":"find_business_profile_by_profile_id","full_name":"diesel_models::query::generics::find_business_profile_by_profile_id","time":"2024-05-13T20:54:41.223726670Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","merchant_id":"merchant_1715629529","flow":"PaymentsCreate","extra":{"query":"SELECT \"business_profile\".\"profile_id\", \"business_profile\".\"merchant_id\", \"business_profile\".\"profile_name\", \"business_profile\".\"created_at\", \"business_profile\".\"modified_at\", \"business_profile\".\"return_url\", \"business_profile\".\"enable_payment_response_hash\", \"business_profile\".\"payment_response_hash_key\", \"business_profile\".\"redirect_to_merchant_with_http_post\", \"business_profile\".\"webhook_details\", \"business_profile\".\"metadata\", \"business_profile\".\"routing_algorithm\", \"business_profile\".\"intent_fulfillment_time\", \"business_profile\".\"frm_routing_algorithm\", \"business_profile\".\"payout_routing_algorithm\", \"business_profile\".\"is_recon_enabled\", \"business_profile\".\"applepay_verified_domains\", \"business_profile\".\"payment_link_config\", \"business_profile\".\"session_expiry\", \"business_profile\".\"authentication_connector_details\" FROM \"business_profile\" WHERE (\"business_profile\".\"profile_id\" = $1) -- binds: [\"pro_54CtNmzvo0L4wQN9A2bT\"]","http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"payment_intent_id = \"pay_ey8XCkOrX9XWspjLqoTD\"","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}} hyperswitch-hyperswitch-server-1 | {"message":"[FIND_BUSINESS_PROFILE_BY_PROFILE_ID - EVENT] diesel_models::query::generics","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"DEBUG","target":"diesel_models::query::generics","service":"router","line":376,"file":"crates/diesel_models/src/query/generics.rs","fn":"find_business_profile_by_profile_id","full_name":"diesel_models::query::generics::find_business_profile_by_profile_id","time":"2024-05-13T20:54:41.225574920Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","merchant_id":"merchant_1715629529","flow":"PaymentsCreate","extra":{"query":"SELECT \"business_profile\".\"profile_id\", \"business_profile\".\"merchant_id\", \"business_profile\".\"profile_name\", \"business_profile\".\"created_at\", \"business_profile\".\"modified_at\", \"business_profile\".\"return_url\", \"business_profile\".\"enable_payment_response_hash\", \"business_profile\".\"payment_response_hash_key\", \"business_profile\".\"redirect_to_merchant_with_http_post\", \"business_profile\".\"webhook_details\", \"business_profile\".\"metadata\", \"business_profile\".\"routing_algorithm\", \"business_profile\".\"intent_fulfillment_time\", \"business_profile\".\"frm_routing_algorithm\", \"business_profile\".\"payout_routing_algorithm\", \"business_profile\".\"is_recon_enabled\", \"business_profile\".\"applepay_verified_domains\", \"business_profile\".\"payment_link_config\", \"business_profile\".\"session_expiry\", \"business_profile\".\"authentication_connector_details\" FROM \"business_profile\" WHERE (\"business_profile\".\"profile_id\" = $1) -- binds: [\"pro_54CtNmzvo0L4wQN9A2bT\"]","http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"payment_intent_id = \"pay_ey8XCkOrX9XWspjLqoTD\"","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}} hyperswitch-hyperswitch-server-1 | {"message":"[INSERT_ADDRESS_FOR_PAYMENTS - EVENT] diesel_models::query::generics","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"DEBUG","target":"diesel_models::query::generics","service":"router","line":85,"file":"crates/diesel_models/src/query/generics.rs","fn":"insert_address_for_payments","full_name":"diesel_models::query::generics::insert_address_for_payments","time":"2024-05-13T20:54:41.226624211Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","merchant_id":"merchant_1715629529","flow":"PaymentsCreate","extra":{"query":"INSERT INTO \"address\" (\"address_id\", \"city\", \"country\", \"line1\", \"line2\", \"line3\", \"state\", \"zip\", \"first_name\", \"last_name\", \"phone_number\", \"country_code\", \"customer_id\", \"merchant_id\", \"payment_id\", \"created_at\", \"modified_at\", \"updated_by\", \"email\") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, DEFAULT) -- binds: [\"add_3dJ36tWTY2E8KzBegwhi\", \"Banglore\", US, Encryption { inner: *** Encrypted data of length 36 bytes *** }, Encryption { inner: *** Encrypted data of length 35 bytes *** }, Encryption { inner: *** Encrypted data of length 35 bytes *** }, Encryption { inner: *** Encrypted data of length 36 bytes *** }, Encryption { inner: *** Encrypted data of length 34 bytes *** }, Encryption { inner: *** Encrypted data of length 34 bytes *** }, Encryption { inner: *** Encrypted data of length 31 bytes *** }, Encryption { inner: *** Encrypted data of length 37 bytes *** }, \"+1\", \"hyperswitch_sdk_demo_id\", \"merchant_1715629529\", \"pay_ey8XCkOrX9XWspjLqoTD\", 2024-05-13 20:54:41.226276836, 2024-05-13 20:54:41.226276836, \"postgres_only\"]","http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"payment_intent_id = \"pay_ey8XCkOrX9XWspjLqoTD\"","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}} hyperswitch-hyperswitch-server-1 | {"message":"[INSERT_ADDRESS_FOR_PAYMENTS - EVENT] diesel_models::query::generics","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"DEBUG","target":"diesel_models::query::generics","service":"router","line":85,"file":"crates/diesel_models/src/query/generics.rs","fn":"insert_address_for_payments","full_name":"diesel_models::query::generics::insert_address_for_payments","time":"2024-05-13T20:54:41.231528295Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","merchant_id":"merchant_1715629529","flow":"PaymentsCreate","extra":{"query":"INSERT INTO \"address\" (\"address_id\", \"city\", \"country\", \"line1\", \"line2\", \"line3\", \"state\", \"zip\", \"first_name\", \"last_name\", \"phone_number\", \"country_code\", \"customer_id\", \"merchant_id\", \"payment_id\", \"created_at\", \"modified_at\", \"updated_by\", \"email\") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, DEFAULT) -- binds: [\"add_5XjpF5T4tDV7AP1wcqFH\", \"San Fransico\", US, Encryption { inner: *** Encrypted data of length 32 bytes *** }, Encryption { inner: *** Encrypted data of length 43 bytes *** }, Encryption { inner: *** Encrypted data of length 43 bytes *** }, Encryption { inner: *** Encrypted data of length 38 bytes *** }, Encryption { inner: *** Encrypted data of length 33 bytes *** }, Encryption { inner: *** Encrypted data of length 34 bytes *** }, Encryption { inner: *** Encrypted data of length 31 bytes *** }, Encryption { inner: *** Encrypted data of length 38 bytes *** }, \"+91\", \"hyperswitch_sdk_demo_id\", \"merchant_1715629529\", \"pay_ey8XCkOrX9XWspjLqoTD\", 2024-05-13 20:54:41.231505795, 2024-05-13 20:54:41.231505795, \"postgres_only\"]","http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"payment_intent_id = \"pay_ey8XCkOrX9XWspjLqoTD\"","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}} hyperswitch-hyperswitch-server-1 | {"message":"[INSERT_PAYMENT_INTENT - EVENT] diesel_models::query::generics","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"DEBUG","target":"diesel_models::query::generics","service":"router","line":85,"file":"crates/diesel_models/src/query/generics.rs","fn":"insert_payment_intent","full_name":"diesel_models::query::generics::insert_payment_intent","time":"2024-05-13T20:54:41.232687545Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","merchant_id":"merchant_1715629529","flow":"PaymentsCreate","extra":{"query":"INSERT INTO \"payment_intent\" (\"payment_id\", \"merchant_id\", \"status\", \"amount\", \"currency\", \"amount_captured\", \"customer_id\", \"description\", \"return_url\", \"metadata\", \"connector_id\", \"shipping_address_id\", \"billing_address_id\", \"statement_descriptor_name\", \"statement_descriptor_suffix\", \"created_at\", \"modified_at\", \"last_synced\", \"setup_future_usage\", \"off_session\", \"client_secret\", \"active_attempt_id\", \"business_country\", \"business_label\", \"order_details\", \"allowed_payment_method_types\", \"connector_metadata\", \"feature_metadata\", \"attempt_count\", \"profile_id\", \"merchant_decision\", \"payment_link_id\", \"payment_confirm_source\", \"updated_by\", \"surcharge_applicable\", \"request_incremental_authorization\", \"incremental_authorization_allowed\", \"authorization_count\", \"session_expiry\", \"fingerprint_id\", \"request_external_three_ds_authentication\") VALUES ($1, $2, $3, $4, $5, DEFAULT, DEFAULT, $6, DEFAULT, $7, DEFAULT, $8, $9, DEFAULT, DEFAULT, $10, $11, $12, DEFAULT, DEFAULT, $13, $14, DEFAULT, DEFAULT, $15, DEFAULT, $16, DEFAULT, $17, $18, DEFAULT, DEFAULT, DEFAULT, $19, DEFAULT, $20, DEFAULT, DEFAULT, $21, DEFAULT, DEFAULT) -- binds: [\"pay_ey8XCkOrX9XWspjLqoTD\", \"merchant_1715629529\", RequiresPaymentMethod, 2999, USD, \"Hello this is description\", *** serde_json::value::Value ***, \"add_3dJ36tWTY2E8KzBegwhi\", \"add_5XjpF5T4tDV7AP1wcqFH\", 2024-05-13 20:54:41.232288461, 2024-05-13 20:54:41.232288461, 2024-05-13 20:54:41.232288461, \"pay_ey8XCkOrX9XWspjLqoTD_secret_VMJKXn8hFbFOC424eAHo\", \"pay_ey8XCkOrX9XWspjLqoTD_1\", [*** serde_json::value::Value ***], Object {\"apple_pay\": Null, \"airwallex\": Null, \"noon\": Object {\"order_category\": String(\"applepay\")}}, 1, \"pro_54CtNmzvo0L4wQN9A2bT\", \"postgres_only\", Default, 2024-05-13 21:09:41.23227917]","http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"payment_intent_id = \"pay_ey8XCkOrX9XWspjLqoTD\"","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}} hyperswitch-hyperswitch-server-1 | hyperswitch-hyperswitch-server-1 | thread 'actix-server worker 3' has overflowed its stack hyperswitch-hyperswitch-server-1 | fatal runtime error: stack overflow hyperswitch-hyperswitch-server-1 | hyperswitch-hyperswitch-server-1 exited with code 133 ``` i checked my memory for docker container it only use 2GB and the configuration is 12 GB. same happens when i try it from the control center <img width="1725" alt="Screenshot 2024-05-14 at 12 05 32 AM" src="https://github.com/juspay/hyperswitch/assets/19466376/376e1544-3008-49fe-97dd-67ff2cca9785"> Any ideas why?</div>
diff --git a/Dockerfile b/Dockerfile index e9591e5e9f2..a8697177716 100644 --- a/Dockerfile +++ b/Dockerfile @@ -61,7 +61,8 @@ ENV TZ=Etc/UTC \ RUN_ENV=${RUN_ENV} \ CONFIG_DIR=${CONFIG_DIR} \ SCHEDULER_FLOW=${SCHEDULER_FLOW} \ - BINARY=${BINARY} + BINARY=${BINARY} \ + RUST_MIN_STACK=4194304 RUN mkdir -p ${BIN_DIR}
2024-05-16T09:43:53Z
## Description <!-- Describe your changes in detail --> - Add a default `RUST_MIN_STACK` size in the docker images for 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). --> https://github.com/juspay/hyperswitch/discussions/4636 ## 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)? --> - generating a docker image locally and testing it
f79c12d4f78ac622300e56f7159ca72d65a4ac0d
- generating a docker image locally and testing it
[ "Dockerfile" ]
juspay/hyperswitch
juspay__hyperswitch-4651
Bug: Provide access of cypress tests to hyperswitch qa Provide access to Cypress tests for the Hyperswitch QA team. Previously, QA did not have approval access.
2024-05-15T12:02:49Z
## 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? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? -->
e79524b295544a959ec4c0dbdb71e5538adebc9d
[]
juspay/hyperswitch
juspay__hyperswitch-4648
Bug: [FIX] address non-digit character cases in card number validation Enforce following validations on the card number - * non-digit characters in card number * invalid card number length * invalid card number (luhn failure) If any of the above validation fails, raise an appropriate error.
diff --git a/Cargo.lock b/Cargo.lock index 5ba2d0dae6d..abc265ad692 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1728,7 +1728,6 @@ version = "0.1.0" dependencies = [ "common_utils", "error-stack", - "luhn", "masking", "router_env", "serde", @@ -2598,12 +2597,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "digits_iterator" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af83450b771231745d43edf36dc9b7813ab83be5e8cbea344ccced1a09dfebcd" - [[package]] name = "displaydoc" version = "0.2.4" @@ -4089,15 +4082,6 @@ dependencies = [ "linked-hash-map", ] -[[package]] -name = "luhn" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d10b831402a3b10e018c8bc7f0ec3344a67d0725919cbaf393accb9baf8700b" -dependencies = [ - "digits_iterator", -] - [[package]] name = "masking" version = "0.1.0" diff --git a/crates/cards/Cargo.toml b/crates/cards/Cargo.toml index ac8a417fb99..ed2be966559 100644 --- a/crates/cards/Cargo.toml +++ b/crates/cards/Cargo.toml @@ -11,7 +11,6 @@ license.workspace = true [dependencies] error-stack = "0.4.1" -luhn = "1.0.1" serde = { version = "1.0.197", features = ["derive"] } thiserror = "1.0.58" time = "0.3.35" diff --git a/crates/cards/src/lib.rs b/crates/cards/src/lib.rs index 5308718826a..91cb93301a9 100644 --- a/crates/cards/src/lib.rs +++ b/crates/cards/src/lib.rs @@ -7,7 +7,7 @@ use masking::{PeekInterface, StrongSecret}; use serde::{de, Deserialize, Serialize}; use time::{util::days_in_year_month, Date, Duration, PrimitiveDateTime, Time}; -pub use crate::validate::{CCValError, CardNumber, CardNumberStrategy}; +pub use crate::validate::{CardNumber, CardNumberStrategy, CardNumberValidationErr}; #[derive(Serialize)] pub struct CardSecurityCode(StrongSecret<u16>); diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rs index 5a71aaa7863..1eb07599785 100644 --- a/crates/cards/src/validate.rs +++ b/crates/cards/src/validate.rs @@ -6,31 +6,36 @@ use router_env::{logger, which as router_env_which, Env}; use serde::{Deserialize, Deserializer, Serialize}; use thiserror::Error; -#[derive(Debug, Deserialize, Serialize, Error)] -#[error("not a valid credit card number")] -pub struct CCValError; +/// +/// Minimum limit of a card number will not be less than 8 by ISO standards +/// +pub const MIN_CARD_NUMBER_LENGTH: usize = 8; -impl From<core::convert::Infallible> for CCValError { - fn from(_: core::convert::Infallible) -> Self { - Self - } -} +/// +/// Maximum limit of a card number will not exceed 19 by ISO standards +/// +pub const MAX_CARD_NUMBER_LENGTH: usize = 19; + +#[derive(Debug, Deserialize, Serialize, Error)] +#[error("{0}")] +pub struct CardNumberValidationErr(&'static str); /// Card number #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)] pub struct CardNumber(StrongSecret<String, CardNumberStrategy>); impl CardNumber { - pub fn get_card_isin(self) -> String { + pub fn get_card_isin(&self) -> String { self.0.peek().chars().take(6).collect::<String>() } - pub fn get_extended_card_bin(self) -> String { + + pub fn get_extended_card_bin(&self) -> String { self.0.peek().chars().take(8).collect::<String>() } - pub fn get_card_no(self) -> String { + pub fn get_card_no(&self) -> String { self.0.peek().chars().collect::<String>() } - pub fn get_last4(self) -> String { + pub fn get_last4(&self) -> String { self.0 .peek() .chars() @@ -44,9 +49,9 @@ impl CardNumber { } impl FromStr for CardNumber { - type Err = CCValError; + type Err = CardNumberValidationErr; - fn from_str(s: &str) -> Result<Self, Self::Err> { + fn from_str(card_number: &str) -> Result<Self, Self::Err> { // Valid test cards for threedsecureio let valid_test_cards = vec![ "4000100511112003", @@ -59,17 +64,79 @@ impl FromStr for CardNumber { Env::Development | Env::Sandbox => valid_test_cards, Env::Production => vec![], }; - if luhn::valid(s) || valid_test_cards.contains(&s) { - let cc_no_whitespace: String = s.split_whitespace().collect(); - Ok(Self(StrongSecret::from_str(&cc_no_whitespace)?)) + + let card_number = card_number.split_whitespace().collect::<String>(); + + let is_card_valid = sanitize_card_number(&card_number)?; + + if valid_test_cards.contains(&card_number.as_str()) || is_card_valid { + Ok(Self(StrongSecret::new(card_number))) } else { - Err(CCValError) + Err(CardNumberValidationErr("card number invalid")) } } } +pub fn sanitize_card_number(card_number: &str) -> Result<bool, CardNumberValidationErr> { + let is_card_number_valid = Ok(card_number) + .and_then(validate_card_number_chars) + .and_then(validate_card_number_length) + .map(|number| luhn(&number))?; + + Ok(is_card_number_valid) +} + +/// +/// # Panics +/// +/// Never, as a single character will never be greater than 10, or `u8` +/// +pub fn validate_card_number_chars(number: &str) -> Result<Vec<u8>, CardNumberValidationErr> { + let data = number.chars().try_fold( + Vec::with_capacity(MAX_CARD_NUMBER_LENGTH), + |mut data, character| { + data.push( + #[allow(clippy::expect_used)] + character + .to_digit(10) + .ok_or(CardNumberValidationErr( + "invalid character found in card number", + ))? + .try_into() + .expect("error while converting a single character to u8"), // safety, a single character will never be greater `u8` + ); + Ok::<Vec<u8>, CardNumberValidationErr>(data) + }, + )?; + + Ok(data) +} + +pub fn validate_card_number_length(number: Vec<u8>) -> Result<Vec<u8>, CardNumberValidationErr> { + if number.len() >= MIN_CARD_NUMBER_LENGTH && number.len() <= MAX_CARD_NUMBER_LENGTH { + Ok(number) + } else { + Err(CardNumberValidationErr("invalid card number length")) + } +} + +#[allow(clippy::as_conversions)] +pub fn luhn(number: &[u8]) -> bool { + number + .iter() + .rev() + .enumerate() + .map(|(idx, element)| { + ((*element * 2) / 10 + (*element * 2) % 10) * ((idx as u8) % 2) + + (*element) * (((idx + 1) as u8) % 2) + }) + .sum::<u8>() + % 10 + == 0 +} + impl TryFrom<String> for CardNumber { - type Error = CCValError; + type Error = CardNumberValidationErr; fn try_from(value: String) -> Result<Self, Self::Error> { Self::from_str(&value) @@ -131,12 +198,30 @@ mod tests { ); } + #[test] + fn invalid_card_number_length() { + let s = "371446"; + assert_eq!( + CardNumber::from_str(s).unwrap_err().to_string(), + "invalid card number length".to_string() + ); + } + + #[test] + fn card_number_with_non_digit_character() { + let s = "371446431 A"; + assert_eq!( + CardNumber::from_str(s).unwrap_err().to_string(), + "invalid character found in card number".to_string() + ); + } + #[test] fn invalid_card_number() { let s = "371446431"; assert_eq!( CardNumber::from_str(s).unwrap_err().to_string(), - "not a valid credit card number".to_string() + "card number invalid".to_string() ); } @@ -180,6 +265,6 @@ mod tests { fn test_invalid_card_number_deserialization() { let card_number = serde_json::from_str::<CardNumber>(r#""1234 5678""#); let error_msg = card_number.unwrap_err().to_string(); - assert_eq!(error_msg, "not a valid credit card number".to_string()); + assert_eq!(error_msg, "card number invalid".to_string()); } } diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs index 7c01a9aca76..bc8724da823 100644 --- a/crates/router/src/core/blocklist/utils.rs +++ b/crates/router/src/core/blocklist/utils.rs @@ -319,7 +319,7 @@ where { generate_fingerprint( state, - StrongSecret::new(card.card_number.clone().get_card_no()), + StrongSecret::new(card.card_number.get_card_no()), StrongSecret::new(merchant_fingerprint_secret.clone()), api_models::enums::LockerChoice::HyperswitchCardVault, ) @@ -343,7 +343,7 @@ where .as_ref() .and_then(|pm_data| match pm_data { api_models::payments::PaymentMethodData::Card(card) => { - Some(card.card_number.clone().get_card_isin()) + Some(card.card_number.get_card_isin()) } _ => None, }); @@ -355,7 +355,7 @@ where .as_ref() .and_then(|pm_data| match pm_data { api_models::payments::PaymentMethodData::Card(card) => { - Some(card.card_number.clone().get_extended_card_bin()) + Some(card.card_number.get_extended_card_bin()) } _ => None, }); @@ -464,7 +464,7 @@ pub async fn generate_payment_fingerprint( { generate_fingerprint( state, - StrongSecret::new(card.card_number.clone().get_card_no()), + StrongSecret::new(card.card_number.get_card_no()), StrongSecret::new(merchant_fingerprint_secret), api_models::enums::LockerChoice::HyperswitchCardVault, ) diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index d3870a9e598..f7667baefa1 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -427,7 +427,7 @@ pub async fn add_payment_method_data( pm_resp.payment_method_id.clone_from(&pm_id); pm_resp.client_secret = Some(client_secret.clone()); - let card_isin = card.card_number.clone().get_card_isin(); + let card_isin = card.card_number.get_card_isin(); let card_info = db .get_card_info(card_isin.as_str()) @@ -439,7 +439,7 @@ pub async fn add_payment_method_data( issuer_country: card_info .as_ref() .and_then(|ci| ci.card_issuing_country.clone()), - last4_digits: Some(card.card_number.clone().get_last4()), + last4_digits: Some(card.card_number.get_last4()), expiry_month: Some(card.card_exp_month), expiry_year: Some(card.card_exp_year), nick_name: card.nick_name, @@ -644,7 +644,7 @@ pub async fn add_payment_method( let updated_card = Some(api::CardDetailFromLocker { scheme: None, - last4_digits: Some(card.card_number.clone().get_last4()), + last4_digits: Some(card.card_number.get_last4()), issuer_country: None, card_number: Some(card.card_number), expiry_month: Some(card.card_exp_month), @@ -894,7 +894,7 @@ pub async fn update_customer_payment_method( // Construct new updated card object. Consider a field if passed in request or else populate it with the existing value from existing_card_data let updated_card = Some(api::CardDetailFromLocker { scheme: existing_card_data.scheme, - last4_digits: Some(card_data_from_locker.card_number.clone().get_last4()), + last4_digits: Some(card_data_from_locker.card_number.get_last4()), issuer_country: existing_card_data.issuer_country, card_number: existing_card_data.card_number, expiry_month: card_update diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 009e9e54467..08e87b47f91 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -339,7 +339,7 @@ pub fn mk_add_card_response_hs( merchant_id: &str, ) -> api::PaymentMethodResponse { let card_number = card.card_number.clone(); - let last4_digits = card_number.clone().get_last4(); + let last4_digits = card_number.get_last4(); let card_isin = card_number.get_card_isin(); let card = api::CardDetailFromLocker { @@ -550,13 +550,13 @@ pub fn get_card_detail( response: Card, ) -> CustomResult<api::CardDetailFromLocker, errors::VaultError> { let card_number = response.card_number; - let mut last4_digits = card_number.peek().to_owned(); + let last4_digits = card_number.clone().get_last4(); //fetch form card bin let card_detail = api::CardDetailFromLocker { scheme: pm.scheme.to_owned(), issuer_country: pm.issuer_country.clone(), - last4_digits: Some(last4_digits.split_off(last4_digits.len() - 4)), + last4_digits: Some(last4_digits), card_number: Some(card_number), expiry_month: Some(response.card_exp_month), expiry_year: Some(response.card_exp_year), diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 38acf574a7c..6f3dd1d33df 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3710,7 +3710,7 @@ pub async fn get_additional_payment_data( ) -> api_models::payments::AdditionalPaymentData { match pm_data { api_models::payments::PaymentMethodData::Card(card_data) => { - let card_isin = Some(card_data.card_number.clone().get_card_isin()); + let card_isin = Some(card_data.card_number.get_card_isin()); let enable_extended_bin =db .find_config_by_key_unwrap_or( format!("{}_enable_extended_card_bin", profile_id).as_str(), @@ -3719,11 +3719,11 @@ pub async fn get_additional_payment_data( let card_extended_bin = match enable_extended_bin { Some(config) if config.config == "true" => { - Some(card_data.card_number.clone().get_extended_card_bin()) + Some(card_data.card_number.get_extended_card_bin()) } _ => None, }; - let last4 = Some(card_data.card_number.clone().get_last4()); + let last4 = Some(card_data.card_number.get_last4()); if card_data.card_issuer.is_some() && card_data.card_network.is_some() && card_data.card_type.is_some() diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 081dac14df0..f5a4265a9fb 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -470,7 +470,7 @@ where let updated_card = Some(CardDetailFromLocker { scheme: None, - last4_digits: Some(card.card_number.clone().get_last4()), + last4_digits: Some(card.card_number.get_last4()), issuer_country: None, card_number: Some(card.card_number), expiry_month: Some(card.card_exp_month), diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index c22f74bab4a..e8baba0d126 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -371,9 +371,7 @@ pub async fn save_payout_data_to_locker( metadata_update.as_ref(), ) { // Fetch card info from db - let card_isin = card_details - .as_ref() - .map(|c| c.card_number.clone().get_card_isin()); + let card_isin = card_details.as_ref().map(|c| c.card_number.get_card_isin()); let mut payment_method = api::PaymentMethodCreate { payment_method: Some(api_enums::PaymentMethod::foreign_from( @@ -410,9 +408,7 @@ pub async fn save_payout_data_to_locker( card_info.card_network.clone().map(|cn| cn.to_string()); api::payment_methods::PaymentMethodsData::Card( api::payment_methods::CardDetailsPaymentMethod { - last4_digits: card_details - .as_ref() - .map(|c| c.card_number.clone().get_last4()), + last4_digits: card_details.as_ref().map(|c| c.card_number.get_last4()), issuer_country: card_info.card_issuing_country, expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), @@ -432,9 +428,7 @@ pub async fn save_payout_data_to_locker( .unwrap_or_else(|| { api::payment_methods::PaymentMethodsData::Card( api::payment_methods::CardDetailsPaymentMethod { - last4_digits: card_details - .as_ref() - .map(|c| c.card_number.clone().get_last4()), + last4_digits: card_details.as_ref().map(|c| c.card_number.get_last4()), issuer_country: None, expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()),
2024-05-15T09:49:54Z
## Description <!-- Describe your changes in detail --> This PR enforces following validations on the card number - * non-digit characters in card number * invalid card number length * invalid card number (luhn failure) If any of the above validation fails, appropriate error is raised. This PR also fixes the failing CI 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 <!-- 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. Unit tests - ![image](https://github.com/juspay/hyperswitch/assets/70657455/bfa28c38-a208-4e0c-85d1-82402c08e6f8) 2. Invalid card number length - ``` curl --location 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ekfmmqSYoY0bvjOGGO0Pe5CQdP9oS0ycImpRG78tjNTrgp03HGxvDAhHCrmHrYoO' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "Visa", "card": { "card_number": "1234567", "card_exp_month": "10", "card_exp_year": "26", "card_holder_name": "Chethan" }, "customer_id": "cus_Cbszk87dvhH7EuBp2ZoB", "metadata": { "city": "NY", "unit": "245" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/2150eade-534c-4fb4-8d64-416119613f7f) 3. Non-digit character in card number ``` curl --location 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ekfmmqSYoY0bvjOGGO0Pe5CQdP9oS0ycImpRG78tjNTrgp03HGxvDAhHCrmHrYoO' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "Visa", "card": { "card_number": "411111111111111🦀", "card_exp_month": "10", "card_exp_year": "26", "card_holder_name": "Chethan" }, "customer_id": "cus_Cbszk87dvhH7EuBp2ZoB", "metadata": { "city": "NY", "unit": "245" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/284d2e28-c9d6-4779-8aa3-31d2f2ada249) 4. Invalid card number (Failing luhn check): ``` curl --location 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ekfmmqSYoY0bvjOGGO0Pe5CQdP9oS0ycImpRG78tjNTrgp03HGxvDAhHCrmHrYoO' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "Visa", "card": { "card_number": "411111111111112", "card_exp_month": "10", "card_exp_year": "26", "card_holder_name": "Chethan" }, "customer_id": "cus_Cbszk87dvhH7EuBp2ZoB", "metadata": { "city": "NY", "unit": "245" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/cb34dc2b-56c9-4e35-ad39-df6815903fa7)
0d45f854a2cc18cc421a3d449a6dc2c830ef9dd5
1. Unit tests - ![image](https://github.com/juspay/hyperswitch/assets/70657455/bfa28c38-a208-4e0c-85d1-82402c08e6f8) 2. Invalid card number length - ``` curl --location 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ekfmmqSYoY0bvjOGGO0Pe5CQdP9oS0ycImpRG78tjNTrgp03HGxvDAhHCrmHrYoO' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "Visa", "card": { "card_number": "1234567", "card_exp_month": "10", "card_exp_year": "26", "card_holder_name": "Chethan" }, "customer_id": "cus_Cbszk87dvhH7EuBp2ZoB", "metadata": { "city": "NY", "unit": "245" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/2150eade-534c-4fb4-8d64-416119613f7f) 3. Non-digit character in card number ``` curl --location 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ekfmmqSYoY0bvjOGGO0Pe5CQdP9oS0ycImpRG78tjNTrgp03HGxvDAhHCrmHrYoO' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "Visa", "card": { "card_number": "411111111111111🦀", "card_exp_month": "10", "card_exp_year": "26", "card_holder_name": "Chethan" }, "customer_id": "cus_Cbszk87dvhH7EuBp2ZoB", "metadata": { "city": "NY", "unit": "245" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/284d2e28-c9d6-4779-8aa3-31d2f2ada249) 4. Invalid card number (Failing luhn check): ``` curl --location 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ekfmmqSYoY0bvjOGGO0Pe5CQdP9oS0ycImpRG78tjNTrgp03HGxvDAhHCrmHrYoO' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "Visa", "card": { "card_number": "411111111111112", "card_exp_month": "10", "card_exp_year": "26", "card_holder_name": "Chethan" }, "customer_id": "cus_Cbszk87dvhH7EuBp2ZoB", "metadata": { "city": "NY", "unit": "245" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/cb34dc2b-56c9-4e35-ad39-df6815903fa7)
[ "Cargo.lock", "crates/cards/Cargo.toml", "crates/cards/src/lib.rs", "crates/cards/src/validate.rs", "crates/router/src/core/blocklist/utils.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/payment_methods/transformers.rs", "crates/router/src/core/payments/helpers.rs", ...
juspay/hyperswitch
juspay__hyperswitch-4647
Bug: [BUG]: 2-Letter State abbreviation is not accepted ### Bug Description Currently 2-Letter State abbreviation is not accepted, in `billing.state` if you pass 2 letter valid state it should not throw an error ### Expected Behavior Both 2 letter and full state name shall be accepted in `billing.state` and should be manipulated according to the requirements before sending it to the connector. ### Actual Behavior Currently 2-Letter State abbreviation is not accepted, in `billing.state` if you pass 2 letter valid state it should not throw an error ### 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/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 8b0974cc4f8..74eb8c048f9 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2010,7 +2010,9 @@ pub enum FileUploadProvider { Checkout, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display)] +#[derive( + Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, +)] pub enum UsStatesAbbreviation { AL, AK, @@ -2073,7 +2075,9 @@ pub enum UsStatesAbbreviation { WY, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display)] +#[derive( + Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, +)] pub enum CanadaStatesAbbreviation { AB, BC, diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 6a569e76a62..0d8f42e6504 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -10,6 +10,7 @@ use base64::Engine; use common_utils::{ date_time, errors::ReportSwitchExt, + ext_traits::StringExt, pii::{self, Email, IpAddress}, }; use diesel_models::enums; @@ -1801,72 +1802,80 @@ pub fn get_webhook_merchant_secret_key(connector_label: &str, merchant_id: &str) impl ForeignTryFrom<String> for UsStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { - let binding = value.as_str().to_lowercase(); - let state = binding.as_str(); - match state { - "alabama" => Ok(Self::AL), - "alaska" => Ok(Self::AK), - "american samoa" => Ok(Self::AS), - "arizona" => Ok(Self::AZ), - "arkansas" => Ok(Self::AR), - "california" => Ok(Self::CA), - "colorado" => Ok(Self::CO), - "connecticut" => Ok(Self::CT), - "delaware" => Ok(Self::DE), - "district of columbia" | "columbia" => Ok(Self::DC), - "federated states of micronesia" | "micronesia" => Ok(Self::FM), - "florida" => Ok(Self::FL), - "georgia" => Ok(Self::GA), - "guam" => Ok(Self::GU), - "hawaii" => Ok(Self::HI), - "idaho" => Ok(Self::ID), - "illinois" => Ok(Self::IL), - "indiana" => Ok(Self::IN), - "iowa" => Ok(Self::IA), - "kansas" => Ok(Self::KS), - "kentucky" => Ok(Self::KY), - "louisiana" => Ok(Self::LA), - "maine" => Ok(Self::ME), - "marshall islands" => Ok(Self::MH), - "maryland" => Ok(Self::MD), - "massachusetts" => Ok(Self::MA), - "michigan" => Ok(Self::MI), - "minnesota" => Ok(Self::MN), - "mississippi" => Ok(Self::MS), - "missouri" => Ok(Self::MO), - "montana" => Ok(Self::MT), - "nebraska" => Ok(Self::NE), - "nevada" => Ok(Self::NV), - "new hampshire" => Ok(Self::NH), - "new jersey" => Ok(Self::NJ), - "new mexico" => Ok(Self::NM), - "new york" => Ok(Self::NY), - "north carolina" => Ok(Self::NC), - "north dakota" => Ok(Self::ND), - "northern mariana islands" => Ok(Self::MP), - "ohio" => Ok(Self::OH), - "oklahoma" => Ok(Self::OK), - "oregon" => Ok(Self::OR), - "palau" => Ok(Self::PW), - "pennsylvania" => Ok(Self::PA), - "puerto rico" => Ok(Self::PR), - "rhode island" => Ok(Self::RI), - "south carolina" => Ok(Self::SC), - "south dakota" => Ok(Self::SD), - "tennessee" => Ok(Self::TN), - "texas" => Ok(Self::TX), - "utah" => Ok(Self::UT), - "vermont" => Ok(Self::VT), - "virgin islands" => Ok(Self::VI), - "virginia" => Ok(Self::VA), - "washington" => Ok(Self::WA), - "west virginia" => Ok(Self::WV), - "wisconsin" => Ok(Self::WI), - "wyoming" => Ok(Self::WY), - _ => Err(errors::ConnectorError::InvalidDataFormat { - field_name: "address.state", + let state_abbreviation_check = + StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "UsStatesAbbreviation"); + + match state_abbreviation_check { + Ok(state_abbreviation) => Ok(state_abbreviation), + Err(_) => { + let binding = value.as_str().to_lowercase(); + let state = binding.as_str(); + match state { + "alabama" => Ok(Self::AL), + "alaska" => Ok(Self::AK), + "american samoa" => Ok(Self::AS), + "arizona" => Ok(Self::AZ), + "arkansas" => Ok(Self::AR), + "california" => Ok(Self::CA), + "colorado" => Ok(Self::CO), + "connecticut" => Ok(Self::CT), + "delaware" => Ok(Self::DE), + "district of columbia" | "columbia" => Ok(Self::DC), + "federated states of micronesia" | "micronesia" => Ok(Self::FM), + "florida" => Ok(Self::FL), + "georgia" => Ok(Self::GA), + "guam" => Ok(Self::GU), + "hawaii" => Ok(Self::HI), + "idaho" => Ok(Self::ID), + "illinois" => Ok(Self::IL), + "indiana" => Ok(Self::IN), + "iowa" => Ok(Self::IA), + "kansas" => Ok(Self::KS), + "kentucky" => Ok(Self::KY), + "louisiana" => Ok(Self::LA), + "maine" => Ok(Self::ME), + "marshall islands" => Ok(Self::MH), + "maryland" => Ok(Self::MD), + "massachusetts" => Ok(Self::MA), + "michigan" => Ok(Self::MI), + "minnesota" => Ok(Self::MN), + "mississippi" => Ok(Self::MS), + "missouri" => Ok(Self::MO), + "montana" => Ok(Self::MT), + "nebraska" => Ok(Self::NE), + "nevada" => Ok(Self::NV), + "new hampshire" => Ok(Self::NH), + "new jersey" => Ok(Self::NJ), + "new mexico" => Ok(Self::NM), + "new york" => Ok(Self::NY), + "north carolina" => Ok(Self::NC), + "north dakota" => Ok(Self::ND), + "northern mariana islands" => Ok(Self::MP), + "ohio" => Ok(Self::OH), + "oklahoma" => Ok(Self::OK), + "oregon" => Ok(Self::OR), + "palau" => Ok(Self::PW), + "pennsylvania" => Ok(Self::PA), + "puerto rico" => Ok(Self::PR), + "rhode island" => Ok(Self::RI), + "south carolina" => Ok(Self::SC), + "south dakota" => Ok(Self::SD), + "tennessee" => Ok(Self::TN), + "texas" => Ok(Self::TX), + "utah" => Ok(Self::UT), + "vermont" => Ok(Self::VT), + "virgin islands" => Ok(Self::VI), + "virginia" => Ok(Self::VA), + "washington" => Ok(Self::WA), + "west virginia" => Ok(Self::WV), + "wisconsin" => Ok(Self::WI), + "wyoming" => Ok(Self::WY), + _ => Err(errors::ConnectorError::InvalidDataFormat { + field_name: "address.state", + } + .into()), + } } - .into()), } } } @@ -1874,26 +1883,33 @@ impl ForeignTryFrom<String> for UsStatesAbbreviation { impl ForeignTryFrom<String> for CanadaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { - let binding = value.as_str().to_lowercase(); - let state = binding.as_str(); - match state { - "alberta" => Ok(Self::AB), - "british columbia" => Ok(Self::BC), - "manitoba" => Ok(Self::MB), - "new brunswick" => Ok(Self::NB), - "newfoundland and labrador" | "newfoundland & labrador" => Ok(Self::NL), - "northwest territories" => Ok(Self::NT), - "nova scotia" => Ok(Self::NS), - "nunavut" => Ok(Self::NU), - "ontario" => Ok(Self::ON), - "prince edward island" => Ok(Self::PE), - "quebec" => Ok(Self::QC), - "saskatchewan" => Ok(Self::SK), - "yukon" => Ok(Self::YT), - _ => Err(errors::ConnectorError::InvalidDataFormat { - field_name: "address.state", + let state_abbreviation_check = + StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "CanadaStatesAbbreviation"); + match state_abbreviation_check { + Ok(state_abbreviation) => Ok(state_abbreviation), + Err(_) => { + let binding = value.as_str().to_lowercase(); + let state = binding.as_str(); + match state { + "alberta" => Ok(Self::AB), + "british columbia" => Ok(Self::BC), + "manitoba" => Ok(Self::MB), + "new brunswick" => Ok(Self::NB), + "newfoundland and labrador" | "newfoundland & labrador" => Ok(Self::NL), + "northwest territories" => Ok(Self::NT), + "nova scotia" => Ok(Self::NS), + "nunavut" => Ok(Self::NU), + "ontario" => Ok(Self::ON), + "prince edward island" => Ok(Self::PE), + "quebec" => Ok(Self::QC), + "saskatchewan" => Ok(Self::SK), + "yukon" => Ok(Self::YT), + _ => Err(errors::ConnectorError::InvalidDataFormat { + field_name: "address.state", + } + .into()), + } } - .into()), } } }
2024-05-15T07:38:22Z
## Description <!-- Describe your changes in detail --> Accept `billing.state` with 2-letter abbreviation for US and CA ### 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). --> #4647 ## 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)? --> ### For CA test with `AB` or any other abbreviation it should pass ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \ --data-raw '{ "amount": 9040, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "shanks57", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "abc-ext.kylta@flowbird.group", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "2027", "card_holder_name": "joseph Doe", "card_cvc": "100", "nick_name": "hehe" } }, "billing": { "address": { "city": "SanFrancisco", "country": "CA", "line1": "1562", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "K1A 0A0", "state": "AB", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "connector_metadata": { "noon": { "order_category": "pay" } }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 10, "account_name": "transaction_processing" } ] }' ``` ### For US test with `ca` or any other abbreviation it should pass ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \ --data-raw '{ "amount": 9040, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "shanks57", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "abc-ext.kylta@flowbird.group", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "2027", "card_holder_name": "joseph Doe", "card_cvc": "100", "nick_name": "hehe" } }, "billing": { "address": { "city": "SanFrancisco", "country": "US", "line1": "1562", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "94122", "state": "CA", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "connector_metadata": { "noon": { "order_category": "pay" } }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 10, "account_name": "transaction_processing" } ] }' ``` ### For US/CA test with full state name it should pass ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \ --data-raw '{ "amount": 9040, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "shanks57", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "abc-ext.kylta@flowbird.group", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "2027", "card_holder_name": "joseph Doe", "card_cvc": "100", "nick_name": "hehe" } }, "billing": { "address": { "city": "SanFrancisco", "country": "US", "line1": "1562", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "connector_metadata": { "noon": { "order_category": "pay" } }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 10, "account_name": "transaction_processing" } ] }' ``` ### For US/CA test with invalid state name or abbreviation it should fail at hyperswitch level. ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \ --data-raw '{ "amount": 9040, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "shanks57", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "abc-ext.kylta@flowbird.group", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "2027", "card_holder_name": "joseph Doe", "card_cvc": "100", "nick_name": "hehe" } }, "billing": { "address": { "city": "SanFrancisco", "country": "US", "line1": "1562", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "94122", "state": "random_state", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "connector_metadata": { "noon": { "order_category": "pay" } }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 10, "account_name": "transaction_processing" } ] }' ```
ff1c2ddf8b9d8f35deee1ab41c2286cc5b349271
### For CA test with `AB` or any other abbreviation it should pass ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \ --data-raw '{ "amount": 9040, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "shanks57", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "abc-ext.kylta@flowbird.group", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "2027", "card_holder_name": "joseph Doe", "card_cvc": "100", "nick_name": "hehe" } }, "billing": { "address": { "city": "SanFrancisco", "country": "CA", "line1": "1562", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "K1A 0A0", "state": "AB", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "connector_metadata": { "noon": { "order_category": "pay" } }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 10, "account_name": "transaction_processing" } ] }' ``` ### For US test with `ca` or any other abbreviation it should pass ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \ --data-raw '{ "amount": 9040, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "shanks57", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "abc-ext.kylta@flowbird.group", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "2027", "card_holder_name": "joseph Doe", "card_cvc": "100", "nick_name": "hehe" } }, "billing": { "address": { "city": "SanFrancisco", "country": "US", "line1": "1562", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "94122", "state": "CA", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "connector_metadata": { "noon": { "order_category": "pay" } }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 10, "account_name": "transaction_processing" } ] }' ``` ### For US/CA test with full state name it should pass ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \ --data-raw '{ "amount": 9040, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "shanks57", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "abc-ext.kylta@flowbird.group", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "2027", "card_holder_name": "joseph Doe", "card_cvc": "100", "nick_name": "hehe" } }, "billing": { "address": { "city": "SanFrancisco", "country": "US", "line1": "1562", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "connector_metadata": { "noon": { "order_category": "pay" } }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 10, "account_name": "transaction_processing" } ] }' ``` ### For US/CA test with invalid state name or abbreviation it should fail at hyperswitch level. ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \ --data-raw '{ "amount": 9040, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "shanks57", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "abc-ext.kylta@flowbird.group", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "2027", "card_holder_name": "joseph Doe", "card_cvc": "100", "nick_name": "hehe" } }, "billing": { "address": { "city": "SanFrancisco", "country": "US", "line1": "1562", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "94122", "state": "random_state", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "connector_metadata": { "noon": { "order_category": "pay" } }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 10, "account_name": "transaction_processing" } ] }' ```
[ "crates/common_enums/src/enums.rs", "crates/router/src/connector/utils.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4640
Bug: [REFACTOR] update api contract for payment methods update endpoint Remove unused fields from update payment method request and update the open api spec
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index b7a58b3b5b6..e045cf2c42d 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -88,24 +88,6 @@ pub struct PaymentMethodUpdate { "card_holder_name": "John Doe"}))] pub card: Option<CardDetailUpdate>, - /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - #[schema(value_type = Option<CardNetwork>,example = "Visa")] - pub card_network: Option<api_enums::CardNetwork>, - - /// Payment method details from locker - #[cfg(feature = "payouts")] - #[schema(value_type = Option<Bank>)] - pub bank_transfer: Option<payouts::Bank>, - - /// Payment method details from locker - #[cfg(feature = "payouts")] - #[schema(value_type = Option<Wallet>)] - pub wallet: Option<payouts::Wallet>, - - /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. - #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] - pub metadata: Option<pii::SecretSerdeValue>, - /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")] pub client_secret: Option<String>, diff --git a/crates/openapi/src/routes/payment_method.rs b/crates/openapi/src/routes/payment_method.rs index 07e6cc35903..3bc593aa5b2 100644 --- a/crates/openapi/src/routes/payment_method.rs +++ b/crates/openapi/src/routes/payment_method.rs @@ -138,7 +138,7 @@ pub async fn payment_method_retrieve_api() {} /// This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments. #[utoipa::path( post, - path = "/payment_methods/{method_id}", + path = "/payment_methods/{method_id}/update", params ( ("method_id" = String, Path, description = "The unique identifier for the Payment Method"), ), @@ -149,7 +149,7 @@ pub async fn payment_method_retrieve_api() {} ), tag = "Payment Methods", operation_id = "Update a Payment method", - security(("api_key" = [])) + security(("api_key" = []), ("publishable_key" = [])) )] pub async fn payment_method_update_api() {} diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 8c946630c8a..307f2dcd085 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -775,6 +775,14 @@ pub async fn update_customer_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + if let Some(cs) = &req.client_secret { + let is_client_secret_expired = authenticate_pm_client_secret_and_check_expiry(cs, &pm)?; + + if is_client_secret_expired { + return Err((errors::ApiErrorResponse::ClientSecretExpired).into()); + }; + }; + if pm.status == enums::PaymentMethodStatus::AwaitingData { return Err(report!(errors::ApiErrorResponse::NotSupported { message: "Payment method is awaiting data so it cannot be updated".into() @@ -849,18 +857,15 @@ pub async fn update_customer_payment_method( payment_method_issuer: pm.payment_method_issuer.clone(), payment_method_issuer_code: pm.payment_method_issuer_code, #[cfg(feature = "payouts")] - bank_transfer: req.bank_transfer, + bank_transfer: None, card: Some(updated_card_details.clone()), #[cfg(feature = "payouts")] - wallet: req.wallet, - metadata: req.metadata, + wallet: None, + metadata: None, customer_id: Some(pm.customer_id.clone()), client_secret: pm.client_secret.clone(), payment_method_data: None, - card_network: req - .card_network - .as_ref() - .map(|card_network| card_network.to_string()), + card_network: None, }; new_pm.validate()?; diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index d9061baebb3..0c3893c4635 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -2612,13 +2612,13 @@ } ] }, - "post": { + "delete": { "tags": [ "Payment Methods" ], - "summary": "Payment Method - Update", - "description": "Payment Method - Update\n\nUpdate an existing payment method of a customer.\nThis API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments.", - "operationId": "Update a Payment method", + "summary": "Payment Method - Delete", + "description": "Payment Method - Delete\n\nDeletes a payment method of a customer.", + "operationId": "Delete a Payment method", "parameters": [ { "name": "method_id", @@ -2630,23 +2630,13 @@ } } ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PaymentMethodUpdate" - } - } - }, - "required": true - }, "responses": { "200": { - "description": "Payment Method updated", + "description": "Payment Method deleted", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentMethodResponse" + "$ref": "#/components/schemas/PaymentMethodDeleteResponse" } } } @@ -2660,14 +2650,16 @@ "api_key": [] } ] - }, - "delete": { + } + }, + "/payment_methods/{method_id}/update": { + "post": { "tags": [ "Payment Methods" ], - "summary": "Payment Method - Delete", - "description": "Payment Method - Delete\n\nDeletes a payment method of a customer.", - "operationId": "Delete a Payment method", + "summary": "Payment Method - Update", + "description": "Payment Method - Update\n\nUpdate an existing payment method of a customer.\nThis API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments.", + "operationId": "Update a Payment method", "parameters": [ { "name": "method_id", @@ -2679,13 +2671,23 @@ } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodUpdate" + } + } + }, + "required": true + }, "responses": { "200": { - "description": "Payment Method deleted", + "description": "Payment Method updated", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentMethodDeleteResponse" + "$ref": "#/components/schemas/PaymentMethodResponse" } } } @@ -2697,6 +2699,9 @@ "security": [ { "api_key": [] + }, + { + "publishable_key": [] } ] } @@ -13258,35 +13263,6 @@ ], "nullable": true }, - "card_network": { - "allOf": [ - { - "$ref": "#/components/schemas/CardNetwork" - } - ], - "nullable": true - }, - "bank_transfer": { - "allOf": [ - { - "$ref": "#/components/schemas/Bank" - } - ], - "nullable": true - }, - "wallet": { - "allOf": [ - { - "$ref": "#/components/schemas/Wallet" - } - ], - "nullable": true - }, - "metadata": { - "type": "object", - "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", - "nullable": true - }, "client_secret": { "type": "string", "description": "This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK",
2024-05-14T10:10:43Z
## Description <!-- Describe your changes in detail --> This PR updates the api contract for payment methods update endpoint and removes few unused fields. This PR adds the missing client secret validation for update endpoint ### 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)? --> `/payment_methods/:id/update` endpoint have to be tested 1. Create a customer ``` curl --location 'http://localhost:8080/customers' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_kxFm2YwE2I8srj4W96v9C5XkZl8VputfqADhqdumTgJFLpuXpgU5I2NlTHOM3ply' \ --data-raw '{ "email": "guest@example.com", "name": "new_cus", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 2. Create a payment method (use `/payment_methods` endpoint) ``` curl --location 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_kxFm2YwE2I8srj4W96v9C5XkZl8VputfqADhqdumTgJFLpuXpgU5I2NlTHOM3ply' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "Visa", "card": { "card_number": "4111111111111111", "card_exp_month": "10", "card_exp_year": "40", "card_holder_name": "John" }, "customer_id": "cus_a05bSJXwCoO01KZmWOdX", "metadata": { "city": "NY", "unit": "245" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/01a8e9c6-7a07-43e6-b95e-7491099ec385) 3. Update the metadata (say `expiry_year` or `nick_name`) using `/payment_methods/:id/update` ``` curl --location 'http://localhost:8080/payment_methods/pm_BuRzGWSAgkNVLRgzyfuu/update' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_kxFm2YwE2I8srj4W96v9C5XkZl8VputfqADhqdumTgJFLpuXpgU5I2NlTHOM3ply' \ --data '{ "card": { "nick_name": "Rock" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/f538ea8d-3f51-4a5a-9d4d-4b4dd8d55696) 4. Do `list_payment_methods_for_customers` and verify whether updation of metadata is successful. 5. Also test the above flow with client secret auth in SDK
040d85826aea88ff242f59edfcdf59b592c7c956
`/payment_methods/:id/update` endpoint have to be tested 1. Create a customer ``` curl --location 'http://localhost:8080/customers' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_kxFm2YwE2I8srj4W96v9C5XkZl8VputfqADhqdumTgJFLpuXpgU5I2NlTHOM3ply' \ --data-raw '{ "email": "guest@example.com", "name": "new_cus", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 2. Create a payment method (use `/payment_methods` endpoint) ``` curl --location 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_kxFm2YwE2I8srj4W96v9C5XkZl8VputfqADhqdumTgJFLpuXpgU5I2NlTHOM3ply' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "Visa", "card": { "card_number": "4111111111111111", "card_exp_month": "10", "card_exp_year": "40", "card_holder_name": "John" }, "customer_id": "cus_a05bSJXwCoO01KZmWOdX", "metadata": { "city": "NY", "unit": "245" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/01a8e9c6-7a07-43e6-b95e-7491099ec385) 3. Update the metadata (say `expiry_year` or `nick_name`) using `/payment_methods/:id/update` ``` curl --location 'http://localhost:8080/payment_methods/pm_BuRzGWSAgkNVLRgzyfuu/update' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_kxFm2YwE2I8srj4W96v9C5XkZl8VputfqADhqdumTgJFLpuXpgU5I2NlTHOM3ply' \ --data '{ "card": { "nick_name": "Rock" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/f538ea8d-3f51-4a5a-9d4d-4b4dd8d55696) 4. Do `list_payment_methods_for_customers` and verify whether updation of metadata is successful. 5. Also test the above flow with client secret auth in SDK
[ "crates/api_models/src/payment_methods.rs", "crates/openapi/src/routes/payment_method.rs", "crates/router/src/core/payment_methods/cards.rs", "openapi/openapi_spec.json" ]
juspay/hyperswitch
juspay__hyperswitch-4659
Bug: [FEATURE] add support for collecting and refunding charges on payments ### Feature Description Charges can be collected on payments for collecting fees for resellers. Adyen, Stripe allows creating charges on payment intents using their marketplace platform. The support for collecting charges on payments and refunding charges needs to be added. ### Possible Implementation #### Payments - A new field `charges` is introduced to read charge specific details - Charge details are sent to the connector where request is transformed and sent - `charge_id` is returned by the connector which is persisted in `payment_attempt` table. This can later be used for refunding charges #### Refunds - A new field `charges` is introduced to read charge id and refund options - `charges` created during payments is fetched and used as a reference - Charge details are sent to the connector where request is transformed and sent ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs index 40e3c2a3665..fb08c1026f2 100644 --- a/connector-template/transformers.rs +++ b/connector-template/transformers.rs @@ -128,7 +128,8 @@ impl<F,T> TryFrom<types::ResponseRouterData<F, {{project-name | downcase | pasca connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, -incremental_authorization_allowed: None, + incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 8c945a03034..59a85841212 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -600,6 +600,50 @@ pub fn convert_authentication_connector(connector_name: &str) -> Option<Authenti AuthenticationConnectors::from_str(connector_name).ok() } +#[derive( + Clone, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + ToSchema, + Hash, +)] +pub enum PaymentChargeType { + #[serde(untagged)] + Stripe(StripeChargeType), +} + +impl Default for PaymentChargeType { + fn default() -> Self { + Self::Stripe(StripeChargeType::default()) + } +} + +#[derive( + Clone, + Debug, + Default, + Hash, + Eq, + PartialEq, + ToSchema, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumString, +)] +#[serde(rename_all = "lowercase")] +#[strum(serialize_all = "lowercase")] +pub enum StripeChargeType { + #[default] + Direct, + Destination, +} + #[cfg(feature = "frm")] pub fn convert_frm_connector(connector_name: &str) -> Option<FrmConnectors> { FrmConnectors::from_str(connector_name).ok() diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 60952ee501f..f0ce3839fce 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -474,6 +474,23 @@ pub struct PaymentsRequest { /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, + + /// Fee information to be charged on the payment being collected + pub charges: Option<PaymentChargeRequest>, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] +#[serde(rename_all = "snake_case")] +pub struct PaymentChargeRequest { + /// Stripe's charge type + #[schema(value_type = PaymentChargeType, example = "direct")] + pub charge_type: api_enums::PaymentChargeType, + + /// Platform fees to be collected on the payment + pub fees: i64, + + /// Identifier for the reseller's account to send the funds to + pub transfer_account_id: String, } impl PaymentsRequest { @@ -3426,11 +3443,30 @@ pub struct PaymentsResponse { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, + /// Fee information to be charged on the payment being collected + pub charges: Option<PaymentChargeResponse>, + /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, } +#[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] +pub struct PaymentChargeResponse { + /// Identifier for charge created for the payment + pub charge_id: Option<String>, + + /// Type of charge (connector specific) + #[schema(value_type = PaymentChargeType, example = "direct")] + pub charge_type: api_enums::PaymentChargeType, + + /// Platform fees collected on the payment + pub application_fees: i64, + + /// Identifier for the reseller's account where the funds were transferred + pub transfer_account_id: String, +} + #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index 369aa0a6602..881cc3912ec 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; use common_utils::pii; +pub use common_utils::types::ChargeRefunds; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; @@ -53,6 +54,10 @@ pub struct RefundRequest { /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, + + /// Charge specific fields for controlling the revert of funds from either platform or connected account + #[schema(value_type = Option<ChargeRefunds>)] + pub charges: Option<ChargeRefunds>, } #[derive(Default, Debug, Clone, Deserialize)] @@ -137,6 +142,9 @@ pub struct RefundResponse { pub profile_id: Option<String>, /// The merchant_connector_id of the processor through which this payment went through pub merchant_connector_id: Option<String>, + /// Charge specific fields for controlling the revert of funds from either platform or connected account + #[schema(value_type = Option<ChargeRefunds>)] + pub charges: Option<ChargeRefunds>, } #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] @@ -168,7 +176,7 @@ pub struct RefundListRequest { pub refund_status: Option<Vec<enums::RefundStatus>>, } -#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)] pub struct RefundListResponse { /// The number of refunds included in the list pub count: usize, diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index e6fd27da31a..ff64d6517c7 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -39,8 +39,8 @@ thiserror = "1.0.58" time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"], optional = true } semver = { version = "1.0.22", features = ["serde"] } -uuid = { version = "1.8.0", features = ["v7"] } utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] } +uuid = { version = "1.8.0", features = ["v7"] } # First party crates common_enums = { version = "0.1.0", path = "../common_enums" } diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 6574d1f1af4..d9a7aef3f57 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -17,7 +17,7 @@ use diesel::{ }; use error_stack::{report, ResultExt}; use semver::Version; -use serde::{de::Visitor, Deserialize, Deserializer}; +use serde::{de::Visitor, Deserialize, Deserializer, Serialize}; use utoipa::ToSchema; use crate::{ @@ -25,7 +25,7 @@ use crate::{ errors::{CustomResult, ParsingError, PercentageError}, }; /// Represents Percentage Value between 0 and 100 both inclusive -#[derive(Clone, Default, Debug, PartialEq, serde::Serialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize)] pub struct Percentage<const PRECISION: u8> { // this value will range from 0 to 100, decimal length defined by precision macro /// Percentage value ranging between 0 and 100 @@ -160,7 +160,7 @@ impl<'de, const PRECISION: u8> Deserialize<'de> for Percentage<PRECISION> { } /// represents surcharge type and value -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case", tag = "type", content = "value")] pub enum Surcharge { /// Fixed Surcharge value @@ -172,7 +172,7 @@ pub enum Surcharge { /// This struct lets us represent a semantic version type #[derive(Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, Ord, PartialOrd)] #[diesel(sql_type = Jsonb)] -#[derive(serde::Serialize, serde::Deserialize)] +#[derive(Serialize, serde::Deserialize)] pub struct SemanticVersion(#[serde(with = "Version")] Version); impl SemanticVersion { @@ -226,6 +226,48 @@ where } } +#[derive( + Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, +)] +#[diesel(sql_type = Jsonb)] +/// Charge object for refunds +pub struct ChargeRefunds { + /// Identifier for charge created for the payment + pub charge_id: String, + + /// Toggle for reverting the application fee that was collected for the payment. + /// If set to false, the funds are pulled from the destination account. + pub revert_platform_fee: Option<bool>, + + /// Toggle for reverting the transfer that was made during the charge. + /// If set to false, the funds are pulled from the main platform's account. + pub revert_transfer: Option<bool>, +} + +impl<DB: Backend> FromSql<Jsonb, DB> for ChargeRefunds +where + serde_json::Value: FromSql<Jsonb, DB>, +{ + fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { + let value = <serde_json::Value as FromSql<Jsonb, DB>>::from_sql(bytes)?; + Ok(serde_json::from_value(value)?) + } +} + +impl ToSql<Jsonb, diesel::pg::Pg> for ChargeRefunds +where + serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>, +{ + fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, diesel::pg::Pg>) -> diesel::serialize::Result { + let value = serde_json::to_value(self)?; + + // the function `reborrow` only works in case of `Pg` backend. But, in case of other backends + // please refer to the diesel migration blog: + // https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations + <serde_json::Value as ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow()) + } +} + /// This Unit struct represents MinorUnit in which core amount works #[derive( Default, diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index ffa9aee1153..6bb286b42a9 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -70,6 +70,7 @@ pub struct PaymentAttempt { pub mandate_data: Option<storage_enums::MandateDetails>, pub fingerprint_id: Option<String>, pub payment_method_billing_address_id: Option<String>, + pub charge_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, } @@ -152,6 +153,7 @@ pub struct PaymentAttemptNew { pub mandate_data: Option<storage_enums::MandateDetails>, pub fingerprint_id: Option<String>, pub payment_method_billing_address_id: Option<String>, + pub charge_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, } @@ -281,6 +283,7 @@ pub enum PaymentAttemptUpdate { unified_code: Option<Option<String>>, unified_message: Option<Option<String>>, payment_method_data: Option<serde_json::Value>, + charge_id: Option<String>, }, UnresolvedResponseUpdate { status: storage_enums::AttemptStatus, @@ -334,6 +337,7 @@ pub enum PaymentAttemptUpdate { encoded_data: Option<String>, connector_transaction_id: Option<String>, connector: Option<String>, + charge_id: Option<String>, updated_by: String, }, IncrementalAuthorizationAmountUpdate { @@ -394,6 +398,7 @@ pub struct PaymentAttemptUpdateInternal { authentication_id: Option<String>, fingerprint_id: Option<String>, payment_method_billing_address_id: Option<String>, + charge_id: Option<String>, client_source: Option<String>, client_version: Option<String>, } @@ -461,6 +466,7 @@ impl PaymentAttemptUpdate { authentication_id, payment_method_billing_address_id, fingerprint_id, + charge_id, client_source, client_version, } = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source); @@ -511,6 +517,7 @@ impl PaymentAttemptUpdate { payment_method_billing_address_id: payment_method_billing_address_id .or(source.payment_method_billing_address_id), fingerprint_id: fingerprint_id.or(source.fingerprint_id), + charge_id: charge_id.or(source.charge_id), client_source: client_source.or(source.client_source), client_version: client_version.or(source.client_version), ..source @@ -698,6 +705,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { unified_code, unified_message, payment_method_data, + charge_id, } => Self { status: Some(status), connector: connector.map(Some), @@ -719,6 +727,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { unified_code, unified_message, payment_method_data, + charge_id, ..Default::default() }, PaymentAttemptUpdate::ErrorUpdate { @@ -841,12 +850,14 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_transaction_id, connector, updated_by, + charge_id, } => Self { authentication_data, encoded_data, connector_transaction_id, connector: connector.map(Some), updated_by, + charge_id, ..Default::default() }, PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 5b5eb0f79e2..2c992554671 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -58,6 +58,7 @@ pub struct PaymentIntent { pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, + pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, } @@ -112,6 +113,7 @@ pub struct PaymentIntentNew { pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, + pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, } @@ -242,6 +244,7 @@ pub struct PaymentIntentUpdateInternal { pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, + pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, } @@ -278,6 +281,7 @@ impl PaymentIntentUpdate { session_expiry, fingerprint_id, request_external_three_ds_authentication, + charges, frm_metadata, } = self.into(); PaymentIntent { @@ -316,6 +320,7 @@ impl PaymentIntentUpdate { session_expiry: session_expiry.or(source.session_expiry), request_external_three_ds_authentication: request_external_three_ds_authentication .or(source.request_external_three_ds_authentication), + charges: charges.or(source.charges), frm_metadata: frm_metadata.or(source.frm_metadata), ..source diff --git a/crates/diesel_models/src/query/connector_response.rs b/crates/diesel_models/src/query/connector_response.rs index 952db945ae3..bdc24139ab6 100644 --- a/crates/diesel_models/src/query/connector_response.rs +++ b/crates/diesel_models/src/query/connector_response.rs @@ -22,6 +22,7 @@ impl ConnectorResponseNew { connector_transaction_id: self.connector_transaction_id.clone(), connector: self.connector_name.clone(), updated_by: self.updated_by.clone(), + charge_id: self.charge_id.clone(), }; let _payment_attempt: Result<PaymentAttempt, _> = @@ -63,12 +64,14 @@ impl ConnectorResponse { authentication_data, encoded_data, connector_name, + charge_id, updated_by, } => PaymentAttemptUpdate::ConnectorResponse { authentication_data, encoded_data, connector_transaction_id, connector: connector_name, + charge_id, updated_by, }, ConnectorResponseUpdate::ErrorUpdate { @@ -79,6 +82,7 @@ impl ConnectorResponse { encoded_data: None, connector_transaction_id: None, connector: connector_name, + charge_id: None, updated_by, }, }; diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index 0ee486bae48..aac282992a8 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -1,4 +1,4 @@ -use common_utils::pii; +use common_utils::{pii, types::ChargeRefunds}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -39,6 +39,7 @@ pub struct Refund { pub profile_id: Option<String>, pub updated_by: String, pub merchant_connector_id: Option<String>, + pub charges: Option<ChargeRefunds>, } #[derive( @@ -81,6 +82,7 @@ pub struct RefundNew { pub profile_id: Option<String>, pub updated_by: String, pub merchant_connector_id: Option<String>, + pub charges: Option<ChargeRefunds>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -275,7 +277,8 @@ mod tests { "refund_error_code": null, "profile_id": null, "updated_by": "admin", - "merchant_connector_id": null + "merchant_connector_id": null, + "charges": null }"#; let deserialized = serde_json::from_str::<super::Refund>(serialized_refund); diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index ba540f7f0bc..de5b536dcda 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -785,6 +785,8 @@ diesel::table! { #[max_length = 64] payment_method_billing_address_id -> Nullable<Varchar>, #[max_length = 64] + charge_id -> Nullable<Varchar>, + #[max_length = 64] client_source -> Nullable<Varchar>, #[max_length = 64] client_version -> Nullable<Varchar>, @@ -856,6 +858,7 @@ diesel::table! { #[max_length = 64] fingerprint_id -> Nullable<Varchar>, request_external_three_ds_authentication -> Nullable<Bool>, + charges -> Nullable<Jsonb>, frm_metadata -> Nullable<Jsonb>, } } @@ -1094,6 +1097,7 @@ diesel::table! { updated_by -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, + charges -> Nullable<Jsonb>, } } diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index 298d82cf31e..1ffaa33a215 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -73,6 +73,7 @@ pub struct PaymentAttemptBatchNew { pub mandate_data: Option<MandateDetails>, pub payment_method_billing_address_id: Option<String>, pub fingerprint_id: Option<String>, + pub charge_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, } @@ -135,6 +136,7 @@ impl PaymentAttemptBatchNew { mandate_data: self.mandate_data, payment_method_billing_address_id: self.payment_method_billing_address_id, fingerprint_id: self.fingerprint_id, + charge_id: self.charge_id, client_source: self.client_source, client_version: self.client_version, } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 0491081e876..b9adc162c47 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -60,5 +60,6 @@ pub struct PaymentIntent { #[serde(with = "common_utils::custom_serde::iso8601::option")] pub session_expiry: Option<PrimitiveDateTime>, pub request_external_three_ds_authentication: Option<bool>, + pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index ff4c7ac017e..ac0c74ea913 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -167,6 +167,7 @@ pub struct PaymentAttempt { pub mandate_data: Option<MandateDetails>, pub payment_method_billing_address_id: Option<String>, pub fingerprint_id: Option<String>, + pub charge_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, } @@ -255,6 +256,7 @@ pub struct PaymentAttemptNew { pub mandate_data: Option<MandateDetails>, pub payment_method_billing_address_id: Option<String>, pub fingerprint_id: Option<String>, + pub charge_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, } @@ -381,6 +383,7 @@ pub enum PaymentAttemptUpdate { unified_code: Option<Option<String>>, unified_message: Option<Option<String>>, payment_method_data: Option<serde_json::Value>, + charge_id: Option<String>, }, UnresolvedResponseUpdate { status: storage_enums::AttemptStatus, @@ -434,6 +437,7 @@ pub enum PaymentAttemptUpdate { encoded_data: Option<String>, connector_transaction_id: Option<String>, connector: Option<String>, + charge_id: Option<String>, updated_by: String, }, IncrementalAuthorizationAmountUpdate { diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index a3353e6dfaf..5cf6f1219f5 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -115,6 +115,7 @@ pub struct PaymentIntentNew { pub fingerprint_id: Option<String>, pub session_expiry: Option<PrimitiveDateTime>, pub request_external_three_ds_authentication: Option<bool>, + pub charges: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index e95f6efd373..026a191977c 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -315,6 +315,33 @@ pub struct RefundsData { /// Arbitrary metadata required for refund pub connector_metadata: Option<serde_json::Value>, pub browser_info: Option<BrowserInformation>, + /// Charges associated with the payment + pub charges: Option<ChargeRefunds>, +} + +#[derive(Debug, serde::Deserialize, Clone)] +pub struct ChargeRefunds { + pub charge_id: String, + pub transfer_account_id: String, + pub charge_type: api_models::enums::PaymentChargeType, + pub options: ChargeRefundsOptions, +} + +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub enum ChargeRefundsOptions { + Destination(DestinationChargeRefund), + Direct(DirectChargeRefund), +} + +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct DirectChargeRefund { + pub revert_platform_fee: bool, +} + +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct DestinationChargeRefund { + pub revert_platform_fee: bool, + pub revert_transfer: bool, } #[derive(Debug, Clone)] diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index b040cb00898..8830c689937 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -521,6 +521,11 @@ Never share your secret api keys. Keep them guarded and secure. api_models::webhook_events::OutgoingWebhookRequestContent, api_models::webhook_events::OutgoingWebhookResponseContent, api_models::enums::WebhookDeliveryAttempt, + api_models::enums::PaymentChargeType, + api_models::enums::StripeChargeType, + api_models::payments::PaymentChargeRequest, + api_models::payments::PaymentChargeResponse, + api_models::refunds::ChargeRefunds, )), modifiers(&SecurityAddon) )] diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index d818fb80dbb..8415453b6ae 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -771,6 +771,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 6e86bfb305d..1c24009c54b 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -3185,6 +3185,7 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>> network_txn_id: None, connector_response_reference_id: Some(item.response.reference), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -3219,6 +3220,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), payment_method_balance: Some(types::PaymentMethodBalance { amount: item.response.balance.value, @@ -3283,6 +3285,7 @@ pub fn get_adyen_response( network_txn_id, connector_response_reference_id: Some(response.merchant_reference), incremental_authorization_allowed: None, + charge_id: None, }; Ok((status, error, payments_response_data)) } @@ -3345,6 +3348,7 @@ pub fn get_webhook_response( network_txn_id: None, connector_response_reference_id: Some(response.merchant_reference_id), incremental_authorization_allowed: None, + charge_id: None, }; Ok((status, error, payments_response_data)) } @@ -3417,6 +3421,7 @@ pub fn get_redirection_response( .clone() .or(response.psp_reference), incremental_authorization_allowed: None, + charge_id: None, }; Ok((status, error, payments_response_data)) } @@ -3474,6 +3479,7 @@ pub fn get_present_to_shopper_response( .clone() .or(response.psp_reference), incremental_authorization_allowed: None, + charge_id: None, }; Ok((status, error, payments_response_data)) } @@ -3530,6 +3536,7 @@ pub fn get_qr_code_response( .clone() .or(response.psp_reference), incremental_authorization_allowed: None, + charge_id: None, }; Ok((status, error, payments_response_data)) } @@ -3566,6 +3573,7 @@ pub fn get_redirection_error_response( network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }; Ok((status, error, payments_response_data)) @@ -3932,6 +3940,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>> network_txn_id: None, connector_response_reference_id: Some(item.response.reference), incremental_authorization_allowed: None, + charge_id: None, }), amount_captured: Some(0), ..item.data diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index fe0cd021ebc..587a14caedf 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -557,6 +557,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -599,6 +600,7 @@ impl network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 8069b925d44..3e4d0a382e6 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -385,6 +385,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }), @@ -922,6 +923,7 @@ impl<F, T> transaction_response.transaction_id.clone(), ), incremental_authorization_allowed: None, + charge_id: None, }), }, ..item.data @@ -994,6 +996,7 @@ impl<F, T> transaction_response.transaction_id.clone(), ), incremental_authorization_allowed: None, + charge_id: None, }), }, ..item.data @@ -1318,6 +1321,7 @@ impl<F, Req> network_txn_id: None, connector_response_reference_id: Some(transaction.transaction_id.clone()), incremental_authorization_allowed: None, + charge_id: None, }), status: payment_status, ..item.data diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index 5fd8c5658a5..af4afeca10d 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -447,6 +447,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: Some(pg_response.order_number.to_string()), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }), @@ -473,6 +474,7 @@ impl<F> item.data.connector_request_reference_id.to_string(), ), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -522,6 +524,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: Some(item.response.order_number.to_string()), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -574,6 +577,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: Some(item.response.order_number.to_string()), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -615,6 +619,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: Some(item.response.order_number.to_string()), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -656,6 +661,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: Some(item.response.order_number.to_string()), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 4a5d99023cf..90151f12aeb 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -415,6 +415,7 @@ impl<F, T> .unwrap_or(info_response.id), ), incremental_authorization_allowed: None, + charge_id: None, }), }, connector_response, @@ -1645,6 +1646,7 @@ fn get_payment_response( .unwrap_or(info_response.id.clone()), ), incremental_authorization_allowed: None, + charge_id: None, }) } } @@ -1697,6 +1699,7 @@ impl<F, T> .unwrap_or(info_response.id.clone()), ), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }), @@ -2052,6 +2055,7 @@ impl<F> network_txn_id: None, connector_response_reference_id, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -2452,6 +2456,7 @@ impl<F> .map(|cref| cref.code) .unwrap_or(Some(app_response.id)), incremental_authorization_allowed: None, + charge_id: None, }), connector_response, ..item.data @@ -2470,6 +2475,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: Some(error_response.id), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }), diff --git a/crates/router/src/connector/billwerk/transformers.rs b/crates/router/src/connector/billwerk/transformers.rs index 372a65af9f3..811076a11da 100644 --- a/crates/router/src/connector/billwerk/transformers.rs +++ b/crates/router/src/connector/billwerk/transformers.rs @@ -276,6 +276,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(item.response.handle), incremental_authorization_allowed: None, + charge_id: None, }; Ok(Self { status: enums::AttemptStatus::from(item.response.state), diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs index a70c4ba3ac2..8a54c79b185 100644 --- a/crates/router/src/connector/bitpay/transformers.rs +++ b/crates/router/src/connector/bitpay/transformers.rs @@ -172,6 +172,7 @@ impl<F, T> .order_id .or(Some(item.response.data.id)), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs index dff76576ace..f2a903c91f3 100644 --- a/crates/router/src/connector/bluesnap.rs +++ b/crates/router/src/connector/bluesnap.rs @@ -728,6 +728,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..data.clone() }) diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index d1dbb9d92e7..b8b5091fe5e 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -869,6 +869,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(item.response.transaction_id), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs index c22b6567732..2ff3e247653 100644 --- a/crates/router/src/connector/boku/transformers.rs +++ b/crates/router/src/connector/boku/transformers.rs @@ -274,6 +274,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, BokuResponse, T, types::Payments network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs index a607d8fc605..729f1f85922 100644 --- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs +++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs @@ -245,6 +245,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -263,6 +264,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }), @@ -427,6 +429,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -445,6 +448,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }), @@ -489,6 +493,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -534,6 +539,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -1062,6 +1068,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -1160,6 +1167,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -1258,6 +1266,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index e278ff40b43..a939f0a83f7 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -282,6 +282,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(id), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/cashtocode/transformers.rs b/crates/router/src/connector/cashtocode/transformers.rs index f8c275df33b..ba55fca9b80 100644 --- a/crates/router/src/connector/cashtocode/transformers.rs +++ b/crates/router/src/connector/cashtocode/transformers.rs @@ -268,6 +268,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ) } @@ -312,6 +313,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index ddf65d23aa4..c92d75f1de8 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -681,6 +681,7 @@ impl TryFrom<types::PaymentsResponseRouterData<PaymentsResponse>> item.response.reference.unwrap_or(item.response.id), ), incremental_authorization_allowed: None, + charge_id: None, }; Ok(Self { status, @@ -733,6 +734,7 @@ impl TryFrom<types::PaymentsSyncResponseRouterData<PaymentsResponse>> item.response.reference.unwrap_or(item.response.id), ), incremental_authorization_allowed: None, + charge_id: None, }; Ok(Self { status, @@ -808,6 +810,7 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<PaymentVoidResponse>> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), status: response.into(), ..item.data @@ -908,6 +911,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaymentCaptureResponse>> network_txn_id: None, connector_response_reference_id: item.response.reference, incremental_authorization_allowed: None, + charge_id: None, }), status, amount_captured, diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/router/src/connector/coinbase/transformers.rs index f02984136bd..82a6add72ee 100644 --- a/crates/router/src/connector/coinbase/transformers.rs +++ b/crates/router/src/connector/coinbase/transformers.rs @@ -149,6 +149,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(item.response.data.id.clone()), incremental_authorization_allowed: None, + charge_id: None, }), |context| { Ok(types::PaymentsResponseData::TransactionUnresolvedResponse{ diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index d9d164ac201..1a1f23b93bf 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -190,6 +190,7 @@ impl<F, T> .custom_id .or(Some(item.response.data.id)), incremental_authorization_allowed: None, + charge_id: None, }) }; diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index a9b1c37ae9c..f1774a0de39 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1778,6 +1778,7 @@ fn get_payment_response( .unwrap_or(info_response.id.clone()), ), incremental_authorization_allowed, + charge_id: None, }) } } @@ -1878,6 +1879,7 @@ impl<F> .unwrap_or(info_response.id.clone()), ), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }), @@ -2246,6 +2248,7 @@ impl<F> network_txn_id: None, connector_response_reference_id, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -2486,6 +2489,7 @@ impl<F, T> incremental_authorization_allowed: Some( mandate_status == enums::AttemptStatus::Authorized, ), + charge_id: None, }), }, connector_response, @@ -2645,6 +2649,7 @@ impl<F> .map(|cref| cref.code) .unwrap_or(Some(app_response.id)), incremental_authorization_allowed, + charge_id: None, }), ..item.data }) @@ -2662,6 +2667,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: Some(error_response.id), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }), diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index c073dc03cc9..b736c6a6c5a 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -330,6 +330,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: item.response.order_id.clone(), incremental_authorization_allowed: None, + charge_id: None, }; Ok(Self { status: enums::AttemptStatus::from(item.response.status), @@ -370,6 +371,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: item.response.order_id.clone(), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -407,6 +409,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: item.response.order_id.clone(), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -444,6 +447,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(item.response.order_id.clone()), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/dummyconnector/transformers.rs b/crates/router/src/connector/dummyconnector/transformers.rs index 52c9522842f..2cf5960bf75 100644 --- a/crates/router/src/connector/dummyconnector/transformers.rs +++ b/crates/router/src/connector/dummyconnector/transformers.rs @@ -259,6 +259,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentsResponse, T, types::Paym network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs index 3d40876c353..2dedb92d1dd 100644 --- a/crates/router/src/connector/fiserv/transformers.rs +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -370,6 +370,7 @@ impl<F, T> gateway_resp.transaction_processing_details.order_id, ), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -412,6 +413,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, FiservSyncResponse, T, types::Pa .clone(), ), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index 861801d1295..9a0881f63d1 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -278,6 +278,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(transaction_id.to_string()), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -326,6 +327,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(transaction_id.to_string()), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -394,6 +396,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<ForteCaptureResponse>> network_txn_id: None, connector_response_reference_id: Some(item.response.transaction_id.to_string()), incremental_authorization_allowed: None, + charge_id: None, }), amount_captured: None, ..item.data @@ -462,6 +465,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(transaction_id.to_string()), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index 6653205c06a..3bdc3360a79 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -235,6 +235,7 @@ fn get_payment_response( network_txn_id: None, connector_response_reference_id: response.reference, incremental_authorization_allowed: None, + charge_id: None, }), } } diff --git a/crates/router/src/connector/globepay/transformers.rs b/crates/router/src/connector/globepay/transformers.rs index efe96454933..dc0f970481c 100644 --- a/crates/router/src/connector/globepay/transformers.rs +++ b/crates/router/src/connector/globepay/transformers.rs @@ -194,6 +194,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -268,6 +269,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index b94dd73dd27..ee1ff91cd47 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -512,6 +512,7 @@ impl<F> redirection_data: None, mandate_reference, network_txn_id: None, + charge_id: None, }), status: enums::AttemptStatus::Charged, ..item.data @@ -664,6 +665,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -699,6 +701,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/router/src/connector/helcim/transformers.rs index 655d8a8663b..a3341ddab47 100644 --- a/crates/router/src/connector/helcim/transformers.rs +++ b/crates/router/src/connector/helcim/transformers.rs @@ -369,6 +369,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: item.response.invoice_number.clone(), incremental_authorization_allowed: None, + charge_id: None, }), status: enums::AttemptStatus::from(item.response), ..item.data @@ -424,6 +425,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: item.response.invoice_number.clone(), incremental_authorization_allowed: None, + charge_id: None, }), status: enums::AttemptStatus::from(item.response), ..item.data @@ -483,6 +485,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: item.response.invoice_number.clone(), incremental_authorization_allowed: None, + charge_id: None, }), status: enums::AttemptStatus::from(item.response), ..item.data @@ -569,6 +572,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: item.response.invoice_number.clone(), incremental_authorization_allowed: None, + charge_id: None, }), status: enums::AttemptStatus::from(item.response), ..item.data @@ -631,6 +635,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: item.response.invoice_number.clone(), incremental_authorization_allowed: None, + charge_id: None, }), status: enums::AttemptStatus::from(item.response), ..item.data diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index 3e337d3a74e..5daa33ab944 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -300,6 +300,7 @@ fn get_iatpay_response( network_txn_id: None, connector_response_reference_id: connector_response_reference_id.clone(), incremental_authorization_allowed: None, + charge_id: None, }, |checkout_methods| types::PaymentsResponseData::TransactionResponse { resource_id: id, @@ -313,6 +314,7 @@ fn get_iatpay_response( network_txn_id: None, connector_response_reference_id: connector_response_reference_id.clone(), incremental_authorization_allowed: None, + charge_id: None, }, ); Ok((status, error, payment_response_data)) diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs index db77b9c30cd..15fed065f06 100644 --- a/crates/router/src/connector/klarna/transformers.rs +++ b/crates/router/src/connector/klarna/transformers.rs @@ -161,6 +161,7 @@ impl TryFrom<types::PaymentsResponseRouterData<KlarnaPaymentsResponse>> network_txn_id: None, connector_response_reference_id: Some(item.response.order_id.clone()), incremental_authorization_allowed: None, + charge_id: None, }), status: item.response.fraud_status.into(), ..item.data diff --git a/crates/router/src/connector/mifinity/transformers.rs b/crates/router/src/connector/mifinity/transformers.rs index 486d91cd57f..b37602e8d76 100644 --- a/crates/router/src/connector/mifinity/transformers.rs +++ b/crates/router/src/connector/mifinity/transformers.rs @@ -134,6 +134,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs index a9fe46cb592..9320aee8d7a 100644 --- a/crates/router/src/connector/mollie/transformers.rs +++ b/crates/router/src/connector/mollie/transformers.rs @@ -540,6 +540,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index 400e5ecd111..8f2cf5f833d 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -699,6 +699,7 @@ impl<F, T> payment_response.data.order_id.clone(), ), incremental_authorization_allowed: None, + charge_id: None, }) }, ..item.data diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index c6ef4ea1ba8..e8c606d7c58 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -372,6 +372,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(item.response.order_id), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -455,6 +456,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(item.response.order.order_id), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index fdc65963fe8..2a8498bfbad 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -225,6 +225,7 @@ impl network_txn_id: None, connector_response_reference_id: Some(item.response.transactionid), incremental_authorization_allowed: None, + charge_id: None, }), enums::AttemptStatus::AuthenticationPending, ), @@ -378,6 +379,7 @@ impl network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), incremental_authorization_allowed: None, + charge_id: None, }), if let Some(diesel_models::enums::CaptureMethod::Automatic) = item.data.request.capture_method @@ -754,6 +756,7 @@ impl network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), incremental_authorization_allowed: None, + charge_id: None, }), enums::AttemptStatus::CaptureInitiated, ), @@ -848,6 +851,7 @@ impl<T> network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), incremental_authorization_allowed: None, + charge_id: None, }), enums::AttemptStatus::Charged, ), @@ -904,6 +908,7 @@ impl TryFrom<types::PaymentsResponseRouterData<StandardResponse>> network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), incremental_authorization_allowed: None, + charge_id: None, }), if let Some(diesel_models::enums::CaptureMethod::Automatic) = item.data.request.capture_method @@ -954,6 +959,7 @@ impl<T> network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), incremental_authorization_allowed: None, + charge_id: None, }), enums::AttemptStatus::VoidInitiated, ), @@ -1004,6 +1010,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, SyncResponse, T, types::Payments network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }), diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index de20f37cf37..7534d32a04a 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -599,6 +599,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id, incremental_authorization_allowed: None, + charge_id: None, }) } }, diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index e0d7a58566d..ace33e3e30f 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -1472,6 +1472,7 @@ where network_txn_id: None, connector_response_reference_id: response.order_id, incremental_authorization_allowed: None, + charge_id: None, }) }, ..item.data diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs index e00f9a331a1..327ec5def05 100644 --- a/crates/router/src/connector/opayo/transformers.rs +++ b/crates/router/src/connector/opayo/transformers.rs @@ -128,6 +128,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(item.response.transaction_id), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs index 09da5fc8f94..8f1579ac1ff 100644 --- a/crates/router/src/connector/opennode/transformers.rs +++ b/crates/router/src/connector/opennode/transformers.rs @@ -144,6 +144,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: item.response.data.order_id, incremental_authorization_allowed: None, + charge_id: None, }) } else { Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index a8442f7ea8a..9b6da9a0e93 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -433,6 +433,7 @@ impl<F, T> .unwrap_or(item.response.transaction_id), ), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index bf20eb1a0b5..634c0a17c7a 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -251,6 +251,7 @@ impl TryFrom<&PaymePaySaleResponse> for types::PaymentsResponseData { network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }) } } @@ -317,6 +318,7 @@ impl From<&SaleQuery> for types::PaymentsResponseData { network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, } } } @@ -525,6 +527,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }), @@ -1080,6 +1083,7 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<PaymeVoidResponse>> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }) }; Ok(Self { diff --git a/crates/router/src/connector/payone/transformers.rs b/crates/router/src/connector/payone/transformers.rs index e9eb3b9ddd7..ebe34111abb 100644 --- a/crates/router/src/connector/payone/transformers.rs +++ b/crates/router/src/connector/payone/transformers.rs @@ -129,6 +129,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index f82317b5afd..9ff6b84a064 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -787,7 +787,8 @@ impl network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, - }), + charge_id: None, + }), ..data.clone() }) } @@ -837,6 +838,7 @@ impl network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..data.clone() }) diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 171d07f6517..0ea1331c448 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -1163,6 +1163,7 @@ impl<F, T> .clone() .or(Some(item.response.id)), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -1268,6 +1269,7 @@ impl<F, T> purchase_units.map_or(item.response.id, |item| item.invoice_id.clone()), ), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -1305,6 +1307,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -1355,6 +1358,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -1423,6 +1427,7 @@ impl<F, T> .clone() .or(Some(item.response.supplementary_data.related_ids.order_id)), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -1758,6 +1763,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaypalCaptureResponse>> .invoice_id .or(Some(item.response.id)), incremental_authorization_allowed: None, + charge_id: None, }), amount_captured: Some(amount_captured), ..item.data @@ -1809,6 +1815,7 @@ impl<F, T> .invoice_id .or(Some(item.response.id)), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/payu/transformers.rs b/crates/router/src/connector/payu/transformers.rs index 575f199b730..5365fc74ef2 100644 --- a/crates/router/src/connector/payu/transformers.rs +++ b/crates/router/src/connector/payu/transformers.rs @@ -211,6 +211,7 @@ impl<F, T> .ext_order_id .or(Some(item.response.order_id)), incremental_authorization_allowed: None, + charge_id: None, }), amount_captured: None, ..item.data @@ -264,6 +265,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), amount_captured: None, ..item.data @@ -350,6 +352,7 @@ impl<F, T> .ext_order_id .or(Some(item.response.order_id)), incremental_authorization_allowed: None, + charge_id: None, }), amount_captured: None, ..item.data @@ -484,6 +487,7 @@ impl<F, T> .clone() .or(Some(order.order_id.clone())), incremental_authorization_allowed: None, + charge_id: None, }), amount_captured: Some( order diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs index e400dc9b399..ef6bde8f1a2 100644 --- a/crates/router/src/connector/placetopay/transformers.rs +++ b/crates/router/src/connector/placetopay/transformers.rs @@ -279,6 +279,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs index 6b0675b1611..e47e0f51206 100644 --- a/crates/router/src/connector/powertranz/transformers.rs +++ b/crates/router/src/connector/powertranz/transformers.rs @@ -337,6 +337,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(item.response.order_identifier), incremental_authorization_allowed: None, + charge_id: None, }), Err, ); diff --git a/crates/router/src/connector/prophetpay/transformers.rs b/crates/router/src/connector/prophetpay/transformers.rs index 7a8cd6e14d0..6862c7c4c80 100644 --- a/crates/router/src/connector/prophetpay/transformers.rs +++ b/crates/router/src/connector/prophetpay/transformers.rs @@ -207,6 +207,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -406,6 +407,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -456,6 +458,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -506,6 +509,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index d949a30a011..128fca65a92 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -480,6 +480,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ) } diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 30f327c700e..7a8bc2587f9 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -677,6 +677,7 @@ impl<F> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -719,6 +720,7 @@ impl<T, F> network_txn_id: None, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs index 0de122d5da2..184b1824362 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/router/src/connector/square/transformers.rs @@ -381,6 +381,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: item.response.payment.reference_id, incremental_authorization_allowed: None, + charge_id: None, }), amount_captured, ..item.data diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index 6477b2325e4..d3072654028 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -360,6 +360,7 @@ impl<F, T> item.response.idempotency_id.unwrap_or(item.response.id), ), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index b41c331b74b..febb039768c 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -877,6 +877,21 @@ impl )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); + + req.request + .charges + .as_ref() + .map(|charge| match &charge.charge_type { + api::enums::PaymentChargeType::Stripe(stripe_charge) => { + if stripe_charge == &api::enums::StripeChargeType::Direct { + let mut customer_account_header = vec![( + headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), + charge.transfer_account_id.clone().into_masked(), + )]; + header.append(&mut customer_account_header); + } + } + }); Ok(header) } @@ -1355,6 +1370,21 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); + + req.request + .charges + .as_ref() + .map(|charge| match &charge.charge_type { + api::enums::PaymentChargeType::Stripe(stripe_charge) => { + if stripe_charge == &api::enums::StripeChargeType::Direct { + let mut customer_account_header = vec![( + headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), + charge.transfer_account_id.clone().into_masked(), + )]; + header.append(&mut customer_account_header); + } + } + }); Ok(header) } @@ -1375,8 +1405,13 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = stripe::RefundRequest::try_from(req)?; - Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) + let request_body = match req.request.charges.as_ref() { + None => RequestContent::FormUrlEncoded(Box::new(stripe::RefundRequest::try_from(req)?)), + Some(_) => RequestContent::FormUrlEncoded(Box::new( + stripe::ChargeRefundRequest::try_from(req)?, + )), + }; + Ok(request_body) } fn build_request( diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index da524bea4c7..55b0d7f4675 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -157,6 +157,18 @@ pub struct PaymentIntentRequest { pub expand: Option<ExpandableObjects>, #[serde(flatten)] pub browser_info: Option<StripeBrowserInformation>, + #[serde(flatten)] + pub charges: Option<IntentCharges>, +} + +#[derive(Debug, Eq, PartialEq, Serialize)] +pub struct IntentCharges { + pub application_fee_amount: i64, + #[serde( + rename = "transfer_data[destination]", + skip_serializing_if = "Option::is_none" + )] + pub destination_account_id: Option<String>, } // Field rename is required only in case of serialization as it is passed in the request to the connector. @@ -1826,6 +1838,25 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { None }; + let (charges, customer) = match &item.request.charges { + Some(charges) => { + let charges = match &charges.charge_type { + api_enums::PaymentChargeType::Stripe(charge_type) => match charge_type { + api_enums::StripeChargeType::Direct => Some(IntentCharges { + application_fee_amount: charges.fees, + destination_account_id: None, + }), + api_enums::StripeChargeType::Destination => Some(IntentCharges { + application_fee_amount: charges.fees, + destination_account_id: Some(charges.transfer_account_id.clone()), + }), + }, + }; + (charges, None) + } + None => (None, item.connector_customer.to_owned().map(Secret::new)), + }; + Ok(Self { amount: item.request.amount, //hopefully we don't loose some cents here currency: item.request.currency.to_string(), //we need to copy the value and not transfer ownership @@ -1845,13 +1876,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { payment_data, payment_method_options, payment_method, - customer: item.connector_customer.to_owned().map(Secret::new), + customer, setup_mandate_details, off_session: item.request.off_session, setup_future_usage: item.request.setup_future_usage, payment_method_types, expand: Some(ExpandableObjects::LatestCharge), browser_info, + charges, }) } } @@ -2350,6 +2382,14 @@ impl<F, T> item.response.id.clone(), )) } else { + let charge_id = item + .response + .latest_charge + .as_ref() + .map(|charge| match charge { + StripeChargeEnum::ChargeId(charge_id) => charge_id.clone(), + StripeChargeEnum::ChargeObject(charge) => charge.id.clone(), + }); Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data, @@ -2358,6 +2398,7 @@ impl<F, T> network_txn_id, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, + charge_id, }) }; @@ -2533,6 +2574,14 @@ impl<F, T> }), _ => None, }; + let charge_id = item + .response + .latest_charge + .as_ref() + .map(|charge| match charge { + StripeChargeEnum::ChargeId(charge_id) => charge_id.clone(), + StripeChargeEnum::ChargeObject(charge) => charge.id.clone(), + }); Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data, @@ -2541,6 +2590,7 @@ impl<F, T> network_txn_id: network_transaction_id, connector_response_reference_id: Some(item.response.id.clone()), incremental_authorization_allowed: None, + charge_id, }) }; @@ -2614,6 +2664,7 @@ impl<F, T> network_txn_id: network_transaction_id, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, + charge_id: None, }) }; @@ -2817,6 +2868,50 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for RefundRequest { } } +#[derive(Debug, Serialize)] +pub struct ChargeRefundRequest { + pub charge: String, + pub refund_application_fee: Option<bool>, + pub reverse_transfer: Option<bool>, + pub amount: Option<i64>, //amount in cents, hence passed as integer + #[serde(flatten)] + pub meta_data: StripeMetadata, +} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for ChargeRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + let amount = item.request.refund_amount; + match item.request.charges.as_ref() { + None => Err(errors::ConnectorError::MissingRequiredField { + field_name: "charges", + } + .into()), + Some(charges) => { + let (refund_application_fee, reverse_transfer) = match charges.options { + types::ChargeRefundsOptions::Direct(types::DirectChargeRefund { + revert_platform_fee, + }) => (Some(revert_platform_fee), None), + types::ChargeRefundsOptions::Destination(types::DestinationChargeRefund { + revert_platform_fee, + revert_transfer, + }) => (Some(revert_platform_fee), Some(revert_transfer)), + }; + Ok(Self { + charge: charges.charge_id.clone(), + refund_application_fee, + reverse_transfer, + amount: Some(amount), + meta_data: StripeMetadata { + order_id: Some(item.request.refund_id.clone()), + is_refund_id_as_reference: Some("true".to_string()), + }, + }) + } + } + } +} + // Type definition for Stripe Refund Response #[derive(Default, Debug, Serialize, Deserialize, Clone)] @@ -3248,8 +3343,9 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, ChargesResponse, T, types::Payme mandate_reference: None, connector_metadata: Some(connector_metadata), network_txn_id: None, - connector_response_reference_id: Some(item.response.id), + connector_response_reference_id: Some(item.response.id.clone()), incremental_authorization_allowed: None, + charge_id: Some(item.response.id), }) }; diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index db225585f41..f6c494170f2 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -735,6 +735,7 @@ fn handle_cards_response( network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }; Ok((status, error, payment_response_data)) } @@ -764,6 +765,7 @@ fn handle_bank_redirects_response( network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }; Ok((status, error, payment_response_data)) } @@ -797,6 +799,7 @@ fn handle_bank_redirects_error_response( network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }; Ok((status, error, payment_response_data)) } @@ -857,6 +860,7 @@ fn handle_bank_redirects_sync_response( network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }; Ok((status, error, payment_response_data)) } @@ -904,6 +908,7 @@ pub fn handle_webhook_response( network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }; Ok((status, error, payment_response_data)) } diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs index dfc7e61c000..2febb9c72ec 100644 --- a/crates/router/src/connector/tsys/transformers.rs +++ b/crates/router/src/connector/tsys/transformers.rs @@ -218,6 +218,7 @@ fn get_payments_response(connector_response: TsysResponse) -> types::PaymentsRes network_txn_id: None, connector_response_reference_id: Some(connector_response.transaction_id), incremental_authorization_allowed: None, + charge_id: None, } } @@ -242,6 +243,7 @@ fn get_payments_sync_response( .clone(), ), incremental_authorization_allowed: None, + charge_id: None, } } diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs index 814eefaf5ff..a78ecc94443 100644 --- a/crates/router/src/connector/volt/transformers.rs +++ b/crates/router/src/connector/volt/transformers.rs @@ -283,6 +283,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -364,6 +365,7 @@ impl<F, T> .merchant_internal_reference .or(Some(payment_response.id)), incremental_authorization_allowed: None, + charge_id: None, }) }, ..item.data @@ -404,6 +406,7 @@ impl<F, T> .merchant_internal_reference .or(Some(webhook_response.payment)), incremental_authorization_allowed: None, + charge_id: None, }) }, ..item.data diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index 1966c65a0a5..06d608a172e 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -582,6 +582,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, PaymentsResponseData network_txn_id: None, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -636,6 +637,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, PaymentsResp network_txn_id: None, connector_response_reference_id: Some(item.response.payment.id), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs index af1a0787d9d..c44ae7afddf 100644 --- a/crates/router/src/connector/worldpay.rs +++ b/crates/router/src/connector/worldpay.rs @@ -233,6 +233,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..data.clone() }) @@ -337,6 +338,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..data.clone() }) @@ -400,6 +402,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..data.clone() }) diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index 5f0fd9f332f..8a61f0f693f 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -254,6 +254,7 @@ impl TryFrom<types::PaymentsResponseRouterData<WorldpayPaymentsResponse>> network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index 67538b819d5..0f067ab935c 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -946,6 +946,7 @@ fn get_zen_response( network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }; Ok((status, error, payment_response_data)) } @@ -989,6 +990,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, CheckoutResponse, T, types::Paym network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }), ..value.data }) diff --git a/crates/router/src/connector/zsl/transformers.rs b/crates/router/src/connector/zsl/transformers.rs index 58ff6ab2fab..ce1ae41fa49 100644 --- a/crates/router/src/connector/zsl/transformers.rs +++ b/crates/router/src/connector/zsl/transformers.rs @@ -336,6 +336,7 @@ impl<F, T> network_txn_id: None, connector_response_reference_id: Some(item.response.mer_ref.clone()), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) @@ -425,6 +426,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, ZslWebhookResponse, T, types::Pa network_txn_id: None, connector_response_reference_id: Some(item.response.mer_ref.clone()), incremental_authorization_allowed: None, + charge_id: None, }), ..item.data }) diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 06c8c7f2c94..81751e62f8b 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2972,6 +2972,7 @@ mod tests { .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)), ), request_external_three_ds_authentication: None, + charges: None, frm_metadata: None, }; let req_cs = Some("1".to_string()); @@ -3031,6 +3032,7 @@ mod tests { .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)), ), request_external_three_ds_authentication: None, + charges: None, frm_metadata: None, }; let req_cs = Some("1".to_string()); @@ -3089,6 +3091,7 @@ mod tests { .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)), ), request_external_three_ds_authentication: None, + charges: None, frm_metadata: None, }; let req_cs = Some("1".to_string()); @@ -3561,6 +3564,7 @@ impl AttemptType { // New payment method billing address can be passed for a retry payment_method_billing_address_id: None, fingerprint_id: None, + charge_id: None, client_source: None, client_version: None, } diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 5501dfe7caf..68f8b7056c0 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -14,7 +14,7 @@ use hyperswitch_domain_models::{ mandates::{MandateData, MandateDetails}, payments::payment_attempt::PaymentAttempt, }; -use masking::{ExposeInterface, PeekInterface}; +use masking::{ExposeInterface, PeekInterface, Secret}; use router_derive::PaymentOperation; use router_env::{instrument, logger, tracing}; use time::PrimitiveDateTime; @@ -933,6 +933,7 @@ impl PaymentCreate { fingerprint_id: None, authentication_connector: None, authentication_id: None, + charge_id: None, client_source: None, client_version: None, }, @@ -997,6 +998,19 @@ impl PaymentCreate { request.capture_method, )?; + let charges = request + .charges + .as_ref() + .map(|charges| { + charges.encode_to_value().map_err(|err| { + logger::warn!("Failed to serialize PaymentCharges - {}", err); + err + }) + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError)? + .map(Secret::new); + Ok(storage::PaymentIntentNew { payment_id: payment_id.to_string(), merchant_id: merchant_account.merchant_id.to_string(), @@ -1042,6 +1056,7 @@ impl PaymentCreate { session_expiry: Some(session_expiry), request_external_three_ds_authentication: request .request_external_three_ds_authentication, + charges, frm_metadata: request.frm_metadata.clone(), }) } diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 6723a2ee5af..047eb350378 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -870,6 +870,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( connector_metadata, connector_response_reference_id, incremental_authorization_allowed, + charge_id, .. } => { payment_data @@ -959,6 +960,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( authentication_data, encoded_data, payment_method_data: additional_payment_method_data, + charge_id, }), ), }; diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 7c6c6336fcb..3bafd777409 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -360,6 +360,7 @@ where resource_id, connector_metadata, redirection_data, + charge_id, .. }) => { let encoded_data = payment_data.payment_attempt.encoded_data.clone(); @@ -407,6 +408,7 @@ where unified_code: None, unified_message: None, payment_method_data: additional_payment_method_data, + charge_id, }, storage_scheme, ) diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index ca068f1d592..11ce9cd7ede 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1,13 +1,16 @@ use std::{fmt::Debug, marker::PhantomData, str::FromStr}; -use api_models::payments::{FrmMessage, GetAddressFromPaymentMethodData, RequestSurchargeDetails}; +use api_models::payments::{ + FrmMessage, GetAddressFromPaymentMethodData, PaymentChargeRequest, PaymentChargeResponse, + RequestSurchargeDetails, +}; #[cfg(feature = "payouts")] use api_models::payouts::PayoutAttemptResponse; use common_enums::RequestIncrementalAuthorization; use common_utils::{consts::X_HS_LATENCY, fp_utils, types::MinorUnit}; use diesel_models::ephemeral_key; use error_stack::{report, ResultExt}; -use masking::{Maskable, Secret}; +use masking::{Maskable, PeekInterface, Secret}; use router_env::{instrument, tracing}; use super::{flows::Feature, types::AuthenticationData, PaymentData}; @@ -86,6 +89,7 @@ where network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, + charge_id: None, }); let additional_data = PaymentAdditionalData { @@ -637,6 +641,28 @@ where ) }); + let charges_response = match payment_intent.charges { + None => None, + Some(charges) => { + let payment_charges: PaymentChargeRequest = charges + .peek() + .clone() + .parse_value("PaymentChargeRequest") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable(format!( + "Failed to parse PaymentChargeRequest for payment_intent {}", + payment_intent.payment_id + ))?; + + Some(PaymentChargeResponse { + charge_id: payment_attempt.charge_id, + charge_type: payment_charges.charge_type, + application_fees: payment_charges.fees, + transfer_account_id: payment_charges.transfer_account_id, + }) + } + }; + services::ApplicationResponse::JsonWithHeaders(( response .set_net_amount(payment_attempt.net_amount) @@ -788,6 +814,7 @@ where .set_customer(customer_details_response.clone()) .set_browser_info(payment_attempt.browser_info) .set_updated(Some(payment_intent.modified_at)) + .set_charges(charges_response) .set_frm_metadata(payment_intent.frm_metadata) .to_owned(), headers, @@ -1166,6 +1193,16 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz .map(|customer| customer.clone().into_inner()) }); + let charges = match payment_data.payment_intent.charges { + Some(charges) => charges + .peek() + .clone() + .parse_value("PaymentCharges") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse charges in to PaymentCharges")?, + None => None, + }; + Ok(Self { payment_method_data: From::from( payment_method_data.get_required_value("payment_method_data")?, @@ -1209,6 +1246,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz .map(AuthenticationData::foreign_try_from) .transpose()?, customer_acceptance: payment_data.customer_acceptance, + charges, }) } } diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs index e3a1daf39ac..eb3a711b5b9 100644 --- a/crates/router/src/core/payments/types.rs +++ b/crates/router/src/core/payments/types.rs @@ -374,3 +374,10 @@ impl ForeignTryFrom<&storage::Authentication> for AuthenticationData { } } } + +#[derive(Debug, serde::Deserialize, Clone)] +pub struct PaymentCharges { + pub charge_type: api_models::enums::PaymentChargeType, + pub fees: i64, + pub transfer_account_id: String, +} diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 987d627f568..b9861ea1f23 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -5,8 +5,9 @@ use std::collections::HashMap; #[cfg(feature = "olap")] use api_models::admin::MerchantConnectorInfo; -use common_utils::ext_traits::AsyncExt; +use common_utils::ext_traits::{AsyncExt, ValueExt}; use error_stack::{report, ResultExt}; +use masking::PeekInterface; use router_env::{instrument, tracing}; use scheduler::{consumer::types::process_data, utils as process_tracker_utils}; #[cfg(feature = "olap")] @@ -16,7 +17,7 @@ use crate::{ consts, core::{ errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt}, - payments::{self, access_token}, + payments::{self, access_token, types::PaymentCharges}, utils as core_utils, }, db, logger, @@ -28,6 +29,7 @@ use crate::{ domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto}, + ChargeRefunds, }, utils::{self, OptionExt}, workflows::payment_sync, @@ -128,6 +130,7 @@ pub async fn refund_create_core( .map(services::ApplicationResponse::Json) } +#[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn trigger_refund_to_gateway( state: &AppState, @@ -137,6 +140,7 @@ pub async fn trigger_refund_to_gateway( payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, creds_identifier: Option<String>, + charges: Option<ChargeRefunds>, ) -> RouterResult<storage::Refund> { let routed_through = payment_attempt .connector @@ -179,6 +183,7 @@ pub async fn trigger_refund_to_gateway( payment_attempt, refund, creds_identifier, + charges, ) .await?; @@ -458,6 +463,7 @@ pub async fn sync_refund_with_gateway( payment_attempt, refund, creds_identifier, + None, ) .await?; @@ -588,6 +594,39 @@ pub async fn validate_and_create_refund( ) -> RouterResult<refunds::RefundResponse> { let db = &*state.store; + // Validate charge_id and refund options + let charges = match ( + payment_intent.charges.as_ref(), + payment_attempt.charge_id.as_ref(), + ) { + (Some(charges), Some(charge_id)) => { + let refund_charge_request = req.charges.clone().get_required_value("charges")?; + utils::when(*charge_id != refund_charge_request.charge_id, || { + Err(report!(errors::ApiErrorResponse::InvalidDataValue { + field_name: "charges.charge_id" + })) + .attach_printable("charge_id sent in request mismatches with original charge_id") + })?; + let payment_charges: PaymentCharges = charges + .peek() + .clone() + .parse_value("PaymentCharges") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse charges in to PaymentCharges")?; + let options = validator::validate_charge_refund( + &refund_charge_request, + &payment_charges.charge_type, + )?; + Some(ChargeRefunds { + charge_id: charge_id.to_string(), + charge_type: payment_charges.charge_type, + transfer_account_id: payment_charges.transfer_account_id, + options, + }) + } + _ => None, + }; + // Only for initial dev and testing let refund_type = req.refund_type.unwrap_or_default(); @@ -678,6 +717,7 @@ pub async fn validate_and_create_refund( .set_refund_reason(req.reason) .set_profile_id(payment_intent.profile_id.clone()) .set_merchant_connector_id(payment_attempt.merchant_connector_id.clone()) + .set_charges(req.charges) .to_owned(); let refund = match db @@ -694,6 +734,7 @@ pub async fn validate_and_create_refund( payment_attempt, payment_intent, creds_identifier, + charges, ) .await? } @@ -832,6 +873,7 @@ pub async fn get_filters_for_refunds( impl ForeignFrom<storage::Refund> for api::RefundResponse { fn foreign_from(refund: storage::Refund) -> Self { let refund = refund; + Self { payment_id: refund.payment_id, refund_id: refund.refund_id, @@ -847,6 +889,7 @@ impl ForeignFrom<storage::Refund> for api::RefundResponse { updated_at: Some(refund.updated_at), connector: refund.connector, merchant_connector_id: refund.merchant_connector_id, + charges: refund.charges, } } } @@ -864,6 +907,7 @@ pub async fn schedule_refund_execution( payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, creds_identifier: Option<String>, + charges: Option<ChargeRefunds>, ) -> RouterResult<storage::Refund> { // refunds::RefundResponse> { let db = &*state.store; @@ -900,6 +944,7 @@ pub async fn schedule_refund_execution( payment_attempt, payment_intent, creds_identifier, + charges, ) .await } @@ -1079,6 +1124,41 @@ pub async fn trigger_refund_execute_workflow( .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + let charges = match ( + payment_intent.charges.as_ref(), + payment_attempt.charge_id.as_ref(), + ) { + (Some(charges), Some(charge_id)) => { + let refund_charge_request = + refund.charges.clone().get_required_value("charges")?; + utils::when(*charge_id != refund_charge_request.charge_id, || { + Err(report!(errors::ApiErrorResponse::InvalidDataValue { + field_name: "charges.charge_id" + })) + .attach_printable( + "charge_id sent in request mismatches with original charge_id", + ) + })?; + let payment_charges: PaymentCharges = charges + .peek() + .clone() + .parse_value("PaymentCharges") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse charges in to PaymentCharges")?; + let options = validator::validate_charge_refund( + &refund_charge_request, + &payment_charges.charge_type, + )?; + Some(ChargeRefunds { + charge_id: charge_id.to_string(), + charge_type: payment_charges.charge_type, + transfer_account_id: payment_charges.transfer_account_id, + options, + }) + } + _ => None, + }; + //trigger refund request to gateway let updated_refund = trigger_refund_to_gateway( state, @@ -1088,6 +1168,7 @@ pub async fn trigger_refund_execute_workflow( &payment_attempt, &payment_intent, None, + charges, ) .await?; add_refund_sync_task( diff --git a/crates/router/src/core/refunds/validator.rs b/crates/router/src/core/refunds/validator.rs index 49248ae4fea..3788b8ac26d 100644 --- a/crates/router/src/core/refunds/validator.rs +++ b/crates/router/src/core/refunds/validator.rs @@ -4,7 +4,11 @@ use time::PrimitiveDateTime; use crate::{ core::errors::{self, CustomResult, RouterResult}, - types::storage::{self, enums}, + types::{ + self, + api::enums as api_enums, + storage::{self, enums}, + }, utils::{self, OptionExt}, }; @@ -144,3 +148,28 @@ pub fn validate_for_valid_refunds( _ => Ok(()), } } + +pub fn validate_charge_refund( + charges: &common_utils::types::ChargeRefunds, + charge_type: &api_enums::PaymentChargeType, +) -> RouterResult<types::ChargeRefundsOptions> { + match charge_type { + api_enums::PaymentChargeType::Stripe(api_enums::StripeChargeType::Direct) => Ok( + types::ChargeRefundsOptions::Direct(types::DirectChargeRefund { + revert_platform_fee: charges + .revert_platform_fee + .get_required_value("revert_platform_fee")?, + }), + ), + api_enums::PaymentChargeType::Stripe(api_enums::StripeChargeType::Destination) => Ok( + types::ChargeRefundsOptions::Destination(types::DestinationChargeRefund { + revert_platform_fee: charges + .revert_platform_fee + .get_required_value("revert_platform_fee")?, + revert_transfer: charges + .revert_transfer + .get_required_value("revert_transfer")?, + }), + ), + } +} diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 237d8b62237..ca464cc6270 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -223,6 +223,7 @@ pub async fn construct_refund_router_data<'a, F>( payment_attempt: &storage::PaymentAttempt, refund: &'a storage::Refund, creds_identifier: Option<String>, + charges: Option<types::ChargeRefunds>, ) -> RouterResult<types::RefundsRouterData<F>> { let profile_id = get_profile_id_from_business_details( payment_intent.business_country, @@ -330,6 +331,7 @@ pub async fn construct_refund_router_data<'a, F>( reason: refund.refund_reason.clone(), connector_refund_id: refund.connector_refund_id.clone(), browser_info, + charges, }, response: Ok(types::RefundsResponseData { diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 3b24dd3960e..1b1bfed3871 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -394,6 +394,7 @@ mod storage { profile_id: new.profile_id.clone(), updated_by: new.updated_by.clone(), merchant_connector_id: new.merchant_connector_id.clone(), + charges: new.charges.clone(), }; let field = format!( @@ -848,6 +849,7 @@ impl RefundInterface for MockDb { profile_id: new.profile_id, updated_by: new.updated_by, merchant_connector_id: new.merchant_connector_id, + charges: new.charges, }; refunds.push(refund.clone()); Ok(refund) diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 7f2f0764b5f..e2f2f6c0b70 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -35,8 +35,9 @@ pub use hyperswitch_domain_models::{ PaymentMethodBalance, PaymentMethodToken, RecurringMandatePaymentData, RouterData, }, router_request_types::{ - AcceptDisputeRequestData, AccessTokenRequestData, BrowserInformation, - DefendDisputeRequestData, RefundsData, ResponseId, RetrieveFileRequestData, + AcceptDisputeRequestData, AccessTokenRequestData, BrowserInformation, ChargeRefunds, + ChargeRefundsOptions, DefendDisputeRequestData, DestinationChargeRefund, + DirectChargeRefund, RefundsData, ResponseId, RetrieveFileRequestData, SubmitEvidenceRequestData, UploadFileRequestData, VerifyWebhookSourceRequestData, }, }; @@ -349,6 +350,7 @@ pub struct PaymentsAuthorizeData { pub request_incremental_authorization: bool, pub metadata: Option<pii::SecretSerdeValue>, pub authentication_data: Option<AuthenticationData>, + pub charges: Option<types::PaymentCharges>, } #[derive(Debug, Clone, Default)] @@ -806,6 +808,7 @@ pub enum PaymentsResponseData { network_txn_id: Option<String>, connector_response_reference_id: Option<String>, incremental_authorization_allowed: Option<bool>, + charge_id: Option<String>, }, MultipleCaptureResponse { // pending_capture_id_list: Vec<String>, @@ -1169,6 +1172,7 @@ impl From<&SetupMandateRouterData> for PaymentsAuthorizeData { metadata: None, authentication_data: None, customer_acceptance: data.request.customer_acceptance.clone(), + charges: None, // TODO: allow charges on mandates? } } } diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index d35abd233f1..cf7ba2382a3 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -52,6 +52,7 @@ impl VerifyConnectorData { request_incremental_authorization: false, authentication_data: None, customer_acceptance: None, + charges: None, } } diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index ef39a5fca16..8936b2af67f 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -218,6 +218,7 @@ pub async fn generate_sample_data( fingerprint_id: None, session_expiry: Some(session_expiry), request_external_three_ds_authentication: None, + charges: None, frm_metadata: Default::default(), }; let payment_attempt = PaymentAttemptBatchNew { @@ -295,6 +296,7 @@ pub async fn generate_sample_data( profile_id: payment_intent.profile_id.clone(), updated_by: merchant_from_db.storage_scheme.to_string(), merchant_connector_id: payment_attempt.merchant_connector_id.clone(), + charges: None, }) } else { None diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 3548bc5e5bd..b4eafee4c83 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -75,6 +75,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { metadata: None, authentication_data: None, customer_acceptance: None, + ..utils::PaymentAuthorizeType::default().0 }, response: Err(types::ErrorResponse::default()), address: PaymentAddress::new( @@ -152,6 +153,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { reason: None, connector_refund_id: None, browser_info: None, + ..utils::PaymentRefundType::default().0 }, response: Err(types::ErrorResponse::default()), address: PaymentAddress::default(), diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index 4d4318064e2..ff703dd84ef 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -182,6 +182,7 @@ impl AdyenTest { metadata: None, authentication_data: None, customer_acceptance: None, + ..utils::PaymentAuthorizeType::default().0 }) } } diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs index 2dd90e704b9..85026c9c447 100644 --- a/crates/router/tests/connectors/bitpay.rs +++ b/crates/router/tests/connectors/bitpay.rs @@ -99,6 +99,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { metadata: None, authentication_data: None, customer_acceptance: None, + ..utils::PaymentAuthorizeType::default().0 }) } diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs index 60620d1b4c4..76887fa0441 100644 --- a/crates/router/tests/connectors/cashtocode.rs +++ b/crates/router/tests/connectors/cashtocode.rs @@ -72,6 +72,7 @@ impl CashtocodeTest { metadata: None, authentication_data: None, customer_acceptance: None, + ..utils::PaymentAuthorizeType::default().0 }) } diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs index 5dd42a2c97c..306255c94c5 100644 --- a/crates/router/tests/connectors/coinbase.rs +++ b/crates/router/tests/connectors/coinbase.rs @@ -101,6 +101,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { metadata: None, authentication_data: None, customer_acceptance: None, + ..utils::PaymentAuthorizeType::default().0 }) } diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs index c26bad8c567..6d52a174b58 100644 --- a/crates/router/tests/connectors/cryptopay.rs +++ b/crates/router/tests/connectors/cryptopay.rs @@ -99,6 +99,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { metadata: None, authentication_data: None, customer_acceptance: None, + ..utils::PaymentAuthorizeType::default().0 }) } diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs index 1e2cea554e9..91162b829e2 100644 --- a/crates/router/tests/connectors/opennode.rs +++ b/crates/router/tests/connectors/opennode.rs @@ -100,6 +100,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { metadata: None, authentication_data: None, customer_acceptance: None, + ..utils::PaymentAuthorizeType::default().0 }) } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index cd1a44a7022..6718611b0c8 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -423,6 +423,7 @@ pub trait ConnectorActions: Connector { reason: None, connector_refund_id: Some(refund_id), browser_info: None, + charges: None, }), payment_info, ); @@ -942,6 +943,7 @@ impl Default for PaymentAuthorizeType { metadata: None, authentication_data: None, customer_acceptance: None, + charges: None, }; Self(data) } @@ -1018,6 +1020,7 @@ impl Default for PaymentRefundType { reason: Some("Customer returned product".to_string()), connector_refund_id: None, browser_info: None, + charges: None, }; Self(data) } @@ -1081,6 +1084,7 @@ pub fn get_connector_metadata( network_txn_id: _, connector_response_reference_id: _, incremental_authorization_allowed: _, + charge_id: _, }) => connector_metadata, _ => None, } diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index 36d0bba6c46..e26ba15eb25 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -111,6 +111,7 @@ impl WorldlineTest { metadata: None, authentication_data: None, customer_acceptance: None, + ..utils::PaymentAuthorizeType::default().0 }) } } diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index cc2f2abc004..0e8df898f12 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -157,6 +157,7 @@ impl PaymentAttemptInterface for MockDb { mandate_data: payment_attempt.mandate_data, payment_method_billing_address_id: payment_attempt.payment_method_billing_address_id, fingerprint_id: payment_attempt.fingerprint_id, + charge_id: payment_attempt.charge_id, client_source: payment_attempt.client_source, client_version: payment_attempt.client_version, }; diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs index 8ad010be133..a12b06b2914 100644 --- a/crates/storage_impl/src/mock_db/payment_intent.rs +++ b/crates/storage_impl/src/mock_db/payment_intent.rs @@ -108,6 +108,7 @@ impl PaymentIntentInterface for MockDb { fingerprint_id: new.fingerprint_id, session_expiry: new.session_expiry, request_external_three_ds_authentication: new.request_external_three_ds_authentication, + charges: new.charges, frm_metadata: new.frm_metadata, }; payment_intents.push(payment_intent.clone()); diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index fb9a5882ee5..1e60c3e02f2 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -413,6 +413,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { .payment_method_billing_address_id .clone(), fingerprint_id: payment_attempt.fingerprint_id.clone(), + charge_id: payment_attempt.charge_id.clone(), client_source: payment_attempt.client_source.clone(), client_version: payment_attempt.client_version.clone(), }; @@ -1197,6 +1198,7 @@ impl DataModelExt for PaymentAttempt { mandate_data: self.mandate_data.map(|d| d.to_storage_model()), payment_method_billing_address_id: self.payment_method_billing_address_id, fingerprint_id: self.fingerprint_id, + charge_id: self.charge_id, client_source: self.client_source, client_version: self.client_version, } @@ -1263,6 +1265,7 @@ impl DataModelExt for PaymentAttempt { .map(MandateDetails::from_storage_model), payment_method_billing_address_id: storage_model.payment_method_billing_address_id, fingerprint_id: storage_model.fingerprint_id, + charge_id: storage_model.charge_id, client_source: storage_model.client_source, client_version: storage_model.client_version, } @@ -1333,6 +1336,7 @@ impl DataModelExt for PaymentAttemptNew { mandate_data: self.mandate_data.map(|d| d.to_storage_model()), payment_method_billing_address_id: self.payment_method_billing_address_id, fingerprint_id: self.fingerprint_id, + charge_id: self.charge_id, client_source: self.client_source, client_version: self.client_version, } @@ -1397,6 +1401,7 @@ impl DataModelExt for PaymentAttemptNew { .map(MandateDetails::from_storage_model), payment_method_billing_address_id: storage_model.payment_method_billing_address_id, fingerprint_id: storage_model.fingerprint_id, + charge_id: storage_model.charge_id, client_source: storage_model.client_source, client_version: storage_model.client_version, } @@ -1585,6 +1590,7 @@ impl DataModelExt for PaymentAttemptUpdate { unified_code, unified_message, payment_method_data, + charge_id, } => DieselPaymentAttemptUpdate::ResponseUpdate { status, connector, @@ -1606,6 +1612,7 @@ impl DataModelExt for PaymentAttemptUpdate { unified_code, unified_message, payment_method_data, + charge_id, }, Self::UnresolvedResponseUpdate { status, @@ -1709,12 +1716,14 @@ impl DataModelExt for PaymentAttemptUpdate { encoded_data, connector_transaction_id, connector, + charge_id, updated_by, } => DieselPaymentAttemptUpdate::ConnectorResponse { authentication_data, encoded_data, connector_transaction_id, connector, + charge_id, updated_by, }, Self::IncrementalAuthorizationAmountUpdate { @@ -1913,6 +1922,7 @@ impl DataModelExt for PaymentAttemptUpdate { unified_code, unified_message, payment_method_data, + charge_id, } => Self::ResponseUpdate { status, connector, @@ -1933,6 +1943,7 @@ impl DataModelExt for PaymentAttemptUpdate { unified_code, unified_message, payment_method_data, + charge_id, }, DieselPaymentAttemptUpdate::UnresolvedResponseUpdate { status, @@ -2034,12 +2045,14 @@ impl DataModelExt for PaymentAttemptUpdate { encoded_data, connector_transaction_id, connector, + charge_id, updated_by, } => Self::ConnectorResponse { authentication_data, encoded_data, connector_transaction_id, connector, + charge_id, updated_by, }, DieselPaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index 0ac963ae816..f40a9c3e2d4 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -118,6 +118,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { session_expiry: new.session_expiry, request_external_three_ds_authentication: new .request_external_three_ds_authentication, + charges: new.charges.clone(), }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { @@ -849,6 +850,7 @@ impl DataModelExt for PaymentIntentNew { fingerprint_id: self.fingerprint_id, session_expiry: self.session_expiry, request_external_three_ds_authentication: self.request_external_three_ds_authentication, + charges: self.charges, } } @@ -897,6 +899,7 @@ impl DataModelExt for PaymentIntentNew { session_expiry: storage_model.session_expiry, request_external_three_ds_authentication: storage_model .request_external_three_ds_authentication, + charges: storage_model.charges, } } } @@ -948,6 +951,7 @@ impl DataModelExt for PaymentIntent { fingerprint_id: self.fingerprint_id, session_expiry: self.session_expiry, request_external_three_ds_authentication: self.request_external_three_ds_authentication, + charges: self.charges, frm_metadata: self.frm_metadata, } } @@ -997,6 +1001,7 @@ impl DataModelExt for PaymentIntent { session_expiry: storage_model.session_expiry, request_external_three_ds_authentication: storage_model .request_external_three_ds_authentication, + charges: storage_model.charges, frm_metadata: storage_model.frm_metadata, } } diff --git a/migrations/2024-05-06-165401_add_charges_in_payment_intent/down.sql b/migrations/2024-05-06-165401_add_charges_in_payment_intent/down.sql new file mode 100644 index 00000000000..53c2368276e --- /dev/null +++ b/migrations/2024-05-06-165401_add_charges_in_payment_intent/down.sql @@ -0,0 +1,5 @@ +ALTER TABLE payment_intent DROP COLUMN IF EXISTS charges; + +ALTER TABLE payment_attempt DROP COLUMN IF EXISTS charge_id; + +ALTER TABLE refund DROP COLUMN IF EXISTS charges; diff --git a/migrations/2024-05-06-165401_add_charges_in_payment_intent/up.sql b/migrations/2024-05-06-165401_add_charges_in_payment_intent/up.sql new file mode 100644 index 00000000000..c2f1ce14d8b --- /dev/null +++ b/migrations/2024-05-06-165401_add_charges_in_payment_intent/up.sql @@ -0,0 +1,6 @@ +ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS charges jsonb; + +ALTER TABLE payment_attempt +ADD COLUMN IF NOT EXISTS charge_id VARCHAR(64); + +ALTER TABLE refund ADD COLUMN IF NOT EXISTS charges jsonb; diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 26eb8997c17..47da1ae1074 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -7317,6 +7317,29 @@ "CashappQr": { "type": "object" }, + "ChargeRefunds": { + "type": "object", + "description": "Charge object for refunds", + "required": [ + "charge_id" + ], + "properties": { + "charge_id": { + "type": "string", + "description": "Identifier for charge created for the payment" + }, + "revert_platform_fee": { + "type": "boolean", + "description": "Toggle for reverting the application fee that was collected for the payment.\nIf set to false, the funds are pulled from the destination account.", + "nullable": true + }, + "revert_transfer": { + "type": "boolean", + "description": "Toggle for reverting the transfer that was made during the charge.\nIf set to false, the funds are pulled from the main platform's account.", + "nullable": true + } + } + }, "Comparison": { "type": "object", "description": "Represents a single comparison condition.", @@ -12529,6 +12552,70 @@ } } }, + "PaymentChargeRequest": { + "type": "object", + "required": [ + "charge_type", + "fees", + "transfer_account_id" + ], + "properties": { + "charge_type": { + "$ref": "#/components/schemas/PaymentChargeType" + }, + "fees": { + "type": "integer", + "format": "int64", + "description": "Platform fees to be collected on the payment" + }, + "transfer_account_id": { + "type": "string", + "description": "Identifier for the reseller's account to send the funds to" + } + } + }, + "PaymentChargeResponse": { + "type": "object", + "required": [ + "charge_type", + "application_fees", + "transfer_account_id" + ], + "properties": { + "charge_id": { + "type": "string", + "description": "Identifier for charge created for the payment", + "nullable": true + }, + "charge_type": { + "$ref": "#/components/schemas/PaymentChargeType" + }, + "application_fees": { + "type": "integer", + "format": "int64", + "description": "Platform fees collected on the payment" + }, + "transfer_account_id": { + "type": "string", + "description": "Identifier for the reseller's account where the funds were transferred" + } + } + }, + "PaymentChargeType": { + "oneOf": [ + { + "type": "object", + "required": [ + "Stripe" + ], + "properties": { + "Stripe": { + "$ref": "#/components/schemas/StripeChargeType" + } + } + } + ] + }, "PaymentCreatePaymentLinkConfig": { "allOf": [ { @@ -13954,6 +14041,14 @@ } ], "nullable": true + }, + "charges": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentChargeRequest" + } + ], + "nullable": true } } }, @@ -14327,6 +14422,14 @@ } ], "nullable": true + }, + "charges": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentChargeRequest" + } + ], + "nullable": true } } }, @@ -14834,6 +14937,14 @@ } ], "nullable": true + }, + "charges": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentChargeRequest" + } + ], + "nullable": true } }, "additionalProperties": false @@ -15359,6 +15470,14 @@ "example": "2022-09-10T10:11:12Z", "nullable": true }, + "charges": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentChargeResponse" + } + ], + "nullable": true + }, "frm_metadata": { "type": "object", "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM.", @@ -15847,6 +15966,14 @@ } ], "nullable": true + }, + "charges": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentChargeRequest" + } + ], + "nullable": true } } }, @@ -17096,6 +17223,14 @@ } ], "nullable": true + }, + "charges": { + "allOf": [ + { + "$ref": "#/components/schemas/ChargeRefunds" + } + ], + "nullable": true } }, "additionalProperties": false @@ -17177,6 +17312,14 @@ "type": "string", "description": "The merchant_connector_id of the processor through which this payment went through", "nullable": true + }, + "charges": { + "allOf": [ + { + "$ref": "#/components/schemas/ChargeRefunds" + } + ], + "nullable": true } } }, @@ -18198,6 +18341,13 @@ "propertyName": "type" } }, + "StripeChargeType": { + "type": "string", + "enum": [ + "direct", + "destination" + ] + }, "SurchargeDetailsResponse": { "type": "object", "required": [
2024-05-13T11:13:35Z
## Description <!-- Describe your changes in detail --> Detailed description - https://github.com/juspay/hyperswitch/issues/4659 This PR adds functionality to create charges on payment intents using Stripe - create `charges` on payment_intent - store `charge_id` in payment_attempt - use `charge_id` for refunds - Direct ``` "charges": { "charge_id": "ch_3PJDz8Ihl7EEkW0O16Wetnl5", "revert_platform_fee": true } ``` - Destination ``` "charges": { "charge_id": "ch_3PJDz8Ihl7EEkW0O16Wetnl5", "revert_platform_fee": true, "revert_transfer": true } _Note_ - charges on mandates is not added in this PR. ### 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)? --> Tested locally using postman collection. **Steps for testing** - Make sure Stripe Connect is enabled on your Stripe account - Onboard a Standard user by initiating an account link from Stripe's dashboard - Make sure merchant account is created and Stripe is added as a payment connector - Create a direct charge on payment by adding below field in `/payment_intents` request ``` "charges": { "charge_type": "direct", "fees": 123, "transfer_account_id": "acct_1PDftAIhl7EEkW0O" } ``` - Create a destination charge on payment by adding below field in `/payment_intents` request ``` "charges": { "charge_type": "destination", "fees": 123, "transfer_account_id": "acct_1PDftAIhl7EEkW0O" } ``` ### Direct charges - ref - https://docs.stripe.com/connect/direct-charges - these help in directly creating charges when customer is paying to the connected account - charges are created, money is split (Stripe fees + reseller’s fees) and the remaining amount is transferred to connected account’s balance ### Destination charges - ref - https://docs.stripe.com/connect/destination-charges - charges are created on the reseller’s account - reseller decides whether some of all of those funds are to be transferred to the connected account - reseller’s account is used for debiting the cost of Stripe fees, refunds and chargebacks - only supported when both reseller and connected accounts belong to the same country
ae77373b4cac63979673fdac37c55986d954358e
Tested locally using postman collection. **Steps for testing** - Make sure Stripe Connect is enabled on your Stripe account - Onboard a Standard user by initiating an account link from Stripe's dashboard - Make sure merchant account is created and Stripe is added as a payment connector - Create a direct charge on payment by adding below field in `/payment_intents` request ``` "charges": { "charge_type": "direct", "fees": 123, "transfer_account_id": "acct_1PDftAIhl7EEkW0O" } ``` - Create a destination charge on payment by adding below field in `/payment_intents` request ``` "charges": { "charge_type": "destination", "fees": 123, "transfer_account_id": "acct_1PDftAIhl7EEkW0O" } ``` ### Direct charges - ref - https://docs.stripe.com/connect/direct-charges - these help in directly creating charges when customer is paying to the connected account - charges are created, money is split (Stripe fees + reseller’s fees) and the remaining amount is transferred to connected account’s balance ### Destination charges - ref - https://docs.stripe.com/connect/destination-charges - charges are created on the reseller’s account - reseller decides whether some of all of those funds are to be transferred to the connected account - reseller’s account is used for debiting the cost of Stripe fees, refunds and chargebacks - only supported when both reseller and connected accounts belong to the same country
[ "connector-template/transformers.rs", "crates/api_models/src/enums.rs", "crates/api_models/src/payments.rs", "crates/api_models/src/refunds.rs", "crates/common_utils/Cargo.toml", "crates/common_utils/src/types.rs", "crates/diesel_models/src/payment_attempt.rs", "crates/diesel_models/src/payment_intent...
juspay/hyperswitch
juspay__hyperswitch-4627
Bug: ci: use git diff to add `M-database-changes` label for pr that contains migrations and schema changes Use git diff to add `M-database-changes` label for pr that contains migrations and schema changes. This helps to identify the pr that has db migrations.
2024-05-13T07:00:48Z
## Description <!-- Describe your changes in detail --> This ps uses git diff to add `M-database-changes` label for pr that contains migrations and schema changes. ### 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)? --> We can see that `M-database-changes` was added for on of the below commits which contained migration changes. <img width="1050" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/959f47f3-622b-40ef-a28d-2ba76dd51d9f">
7085a46271791ca3f1c7b86afa7c8b199b93c0cd
We can see that `M-database-changes` was added for on of the below commits which contained migration changes. <img width="1050" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/959f47f3-622b-40ef-a28d-2ba76dd51d9f">
[]
juspay/hyperswitch
juspay__hyperswitch-4612
Bug: [BUG] : QR Code Image Generation Failure ### Bug Description The QR code generation function, 'new_from_data', is not working as expected. It is returning an empty string instead of the encoded image URL , leading to the failure of PIX QR code generation. ### Expected Behavior Fix QR code into image generation function ### Actual Behavior Generate QR code image URL ### 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 ![image (6)](https://github.com/juspay/hyperswitch/assets/131388445/37e6a8a5-4961-47f5-8233-dc62bb028027) ### 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? None
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index 87cd95364d5..059278a1b1c 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -185,7 +185,7 @@ impl QrImage { let image_data_source = format!( "{},{}", consts::QR_IMAGE_DATA_SOURCE_STRING, - consts::BASE64_ENGINE.encode(image_bytes.get_ref().get_ref()) + consts::BASE64_ENGINE.encode(image_bytes.buffer()) ); Ok(Self { data: image_data_source,
2024-05-10T06:44:48Z
## Description <!-- Describe your changes in detail --> The QR code generation function, 'new_from_data', is not working as expected. It is returning an empty string instead of the encoded image URL , leading to the failure of PIX QR code generation. Earlier <img width="339" alt="Screenshot 2024-05-10 at 12 18 52 PM" src="https://github.com/juspay/hyperswitch/assets/131388445/b9d78dd5-ec62-4a79-9587-b6b359f9d122"> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a PIX payment with Adyen. In response we must get a valid base64 encoded QR Code data ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Q1XJ407yuiyLeM1BwpMrGJos9JzwwHHztSVIypS3zsMkIYQqf1W7HA2NZhFpZyL4' \ --data-raw '{ "amount": 6540, "currency": "BRL", "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://hs-payments-test.netlify.app/payments/", "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_data": { "bank_transfer": { "pix": {} } } }' ``` Response ``` { "payment_id": "pay_pES0gbesSS9LXecyuhd6", "merchant_id": "merchant_1715279316", "status": "requires_customer_action", "amount": 6540, "net_amount": 6540, "amount_capturable": 6540, "amount_received": null, "connector": "adyen", "client_secret": "pay_pES0gbesSS9LXecyuhd6_secret_Q3ma2x34cOKMp9h6OTRm", "created": "2024-05-10T06:20:26.315Z", "currency": "BRL", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_transfer", "payment_method_data": { "bank_transfer": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://hs-payments-test.netlify.app/payments/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "qr_code_information", "image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg**********", "display_to_timestamp": 1715325628000, "qr_code_url": "https://test.adyen.com/hpp/generateQRCodeImage.shtml?url=*********" }, "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": 1715322026, "expires": 1715325626, "secret": "epk_eea7fdbbbeb645d28e1e0bd4a0905631" }, "manual_retry_allowed": null, "connector_transaction_id": "MQ9886QMBZNKWPT5", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "MQ9886QMBZNKWPT5", "payment_link": null, "profile_id": "pro_10opqc1gzSgRKhUq7O1H", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_mbTo85IbSKeh3xAG84jr", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-10T06:35:26.315Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-10T06:20:28.525Z" } ```
ecdac814d802cfc260a956a77a99f22c5d899ba3
1. Create a PIX payment with Adyen. In response we must get a valid base64 encoded QR Code data ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Q1XJ407yuiyLeM1BwpMrGJos9JzwwHHztSVIypS3zsMkIYQqf1W7HA2NZhFpZyL4' \ --data-raw '{ "amount": 6540, "currency": "BRL", "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://hs-payments-test.netlify.app/payments/", "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_data": { "bank_transfer": { "pix": {} } } }' ``` Response ``` { "payment_id": "pay_pES0gbesSS9LXecyuhd6", "merchant_id": "merchant_1715279316", "status": "requires_customer_action", "amount": 6540, "net_amount": 6540, "amount_capturable": 6540, "amount_received": null, "connector": "adyen", "client_secret": "pay_pES0gbesSS9LXecyuhd6_secret_Q3ma2x34cOKMp9h6OTRm", "created": "2024-05-10T06:20:26.315Z", "currency": "BRL", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_transfer", "payment_method_data": { "bank_transfer": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://hs-payments-test.netlify.app/payments/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "qr_code_information", "image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg**********", "display_to_timestamp": 1715325628000, "qr_code_url": "https://test.adyen.com/hpp/generateQRCodeImage.shtml?url=*********" }, "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": 1715322026, "expires": 1715325626, "secret": "epk_eea7fdbbbeb645d28e1e0bd4a0905631" }, "manual_retry_allowed": null, "connector_transaction_id": "MQ9886QMBZNKWPT5", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "MQ9886QMBZNKWPT5", "payment_link": null, "profile_id": "pro_10opqc1gzSgRKhUq7O1H", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_mbTo85IbSKeh3xAG84jr", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-10T06:35:26.315Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-10T06:20:28.525Z" } ```
[ "crates/router/src/utils.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4463
Bug: [REFACTOR]: handle network delays with expiry of access token It may so happen that there might be a slight delay in the network to receive the access token from connector. So when we store the access token with expiry already few seconds would have elapsed. So the key might expire few seconds before than the actual expiry at hyperswitch. **Note** - This affects only to those connectors which provide relative expiry i.e expires in 300s. In order to account for this, when storing the redis expiry key, it can be set by subtracting few seconds from the actual expiry in order to account for the network delays. **Note** - This can be done in the core level for all access token in order to be safe. There might also be some network delays when using this access token to create the payment. The token might have not been expired when the request is sent, but once it reaches the processor, it might have been expired.
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 0c9e9443ac9..6d9da8f7bb5 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -118,6 +118,8 @@ pub const POLL_ID_TTL: i64 = 900; pub const DEFAULT_POLL_DELAY_IN_SECS: i8 = 2; pub const DEFAULT_POLL_FREQUENCY: i8 = 5; +// Number of seconds to subtract from access token expiry +pub(crate) const REDUCE_ACCESS_TOKEN_EXPIRY_TIME: u8 = 15; pub const CONNECTOR_CREDS_TOKEN_TTL: i64 = 900; //max_amount allowed is 999999999 in minor units diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs index 2d4ed2b6e1b..0c5aa13eb2f 100644 --- a/crates/router/src/core/payments/access_token.rs +++ b/crates/router/src/core/payments/access_token.rs @@ -91,9 +91,26 @@ pub async fn add_access_token< connector.connector_name, access_token.expires ); + metrics::ACCESS_TOKEN_CACHE_HIT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes( + "connector", + connector.connector_name.to_string(), + )], + ); Ok(Some(access_token)) } None => { + metrics::ACCESS_TOKEN_CACHE_MISS.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes( + "connector", + connector.connector_name.to_string(), + )], + ); + let cloned_router_data = router_data.clone(); let refresh_token_request_data = types::AccessTokenRequestData::try_from( router_data.connector_auth_type.clone(), @@ -123,15 +140,31 @@ pub async fn add_access_token< &refresh_token_router_data, ) .await? - .async_map(|access_token| async { - // Store the access token in redis with expiry - // The expiry should be adjusted for network delays from the connector + .async_map(|access_token| async move { let store = &*state.store; + + // The expiry should be adjusted for network delays from the connector + // The access token might not have been expired when request is sent + // But once it reaches the connector, it might expire because of the network delay + // Subtract few seconds from the expiry in order to account for these network delays + // This will reduce the expiry time by `REDUCE_ACCESS_TOKEN_EXPIRY_TIME` seconds + let modified_access_token_with_expiry = types::AccessToken { + expires: access_token + .expires + .saturating_sub(consts::REDUCE_ACCESS_TOKEN_EXPIRY_TIME.into()), + ..access_token + }; + + logger::debug!( + access_token_expiry_after_modification = + modified_access_token_with_expiry.expires + ); + if let Err(access_token_set_error) = store .set_access_token( merchant_id, &merchant_connector_id_or_connector_name, - access_token.clone(), + modified_access_token_with_expiry.clone(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -142,7 +175,7 @@ pub async fn add_access_token< // The next request will create new access token, if required logger::error!(access_token_set_error=?access_token_set_error); } - Some(access_token) + Some(modified_access_token_with_expiry) }) .await } diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 780dd51bbde..1123be1a874 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -52,7 +52,6 @@ counter_metric!(MCA_CREATE, GLOBAL_METER); // Flow Specific Metrics -counter_metric!(ACCESS_TOKEN_CREATION, GLOBAL_METER); histogram_metric!(CONNECTOR_REQUEST_TIME, GLOBAL_METER); counter_metric!(SESSION_TOKEN_CREATED, GLOBAL_METER); @@ -123,5 +122,16 @@ counter_metric!(TASKS_ADDED_COUNT, GLOBAL_METER); // Tasks added to process trac counter_metric!(TASK_ADDITION_FAILURES_COUNT, GLOBAL_METER); // Failures in task addition to process tracker counter_metric!(TASKS_RESET_COUNT, GLOBAL_METER); // Tasks reset in process tracker for requeue flow +// Access token metrics +// +// A counter to indicate the number of new access tokens created +counter_metric!(ACCESS_TOKEN_CREATION, GLOBAL_METER); + +// A counter to indicate the access token cache hits +counter_metric!(ACCESS_TOKEN_CACHE_HIT, GLOBAL_METER); + +// A counter to indicate the access token cache miss +counter_metric!(ACCESS_TOKEN_CACHE_MISS, GLOBAL_METER); + pub mod request; pub mod utils;
2024-05-09T18:56:17Z
## Description <!-- Describe your changes in detail --> There might be some delay in network due to which the access token which was not expired locally, might have expired when it reaches the connector. This PR reduces the expiry of access token in order to account for such delays <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Create a payment with any connector which supports access token and then check the ttl in redis. <img width="2052" alt="Screenshot 2024-05-10 at 12 24 52 AM" src="https://github.com/juspay/hyperswitch/assets/48803246/1ef1d233-d0c0-4f6d-a511-b80e61805513"> - The below log can also be checked <img width="1284" alt="Screenshot 2024-05-10 at 12 25 58 AM" src="https://github.com/juspay/hyperswitch/assets/48803246/b69f742f-9f22-4960-a446-12e77ac03769"> ## IMPACT - airwallex - globalpay - paypal - payu - trustpay - bank redirect - iatapay - volt
4b5b558dae8d2fefb66b8b16c486f07e3e800758
- Create a payment with any connector which supports access token and then check the ttl in redis. <img width="2052" alt="Screenshot 2024-05-10 at 12 24 52 AM" src="https://github.com/juspay/hyperswitch/assets/48803246/1ef1d233-d0c0-4f6d-a511-b80e61805513"> - The below log can also be checked <img width="1284" alt="Screenshot 2024-05-10 at 12 25 58 AM" src="https://github.com/juspay/hyperswitch/assets/48803246/b69f742f-9f22-4960-a446-12e77ac03769">
[ "crates/router/src/consts.rs", "crates/router/src/core/payments/access_token.rs", "crates/router/src/routes/metrics.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4615
Bug: Pass `required_shipping_contact_fields` field in apple pay session call based on `business_profile` config This change is required as part of the one click checkout where in which we expect apple pay to collect the shipping details from the customer and pass it in the confirm call with the payment_data. In order for apple pay to collect the shipping details from customer we need to pass `"requiredShippingContactFields": ["postalAddress", "phone", "email"]` in the `/session` call. Hence we need to have a validation in the backend that checks for the business profile config (`collect_shipping_details_from_wallet_connector`) fields and pass the `required_shipping_contact_fields` to sdk. Similarly for google pay we need to pass the below mentioned fields for the shipping details. ``` "shipping_address_required": true, "email_required": true, "shipping_address_parameters": { "phone_number_required": true }, ```
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 25de8821263..93cf7574d98 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -916,6 +916,9 @@ pub struct BusinessProfileCreate { /// Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, + + /// A boolean value to indicate if cusomter shipping details needs to be sent for wallets payments + pub collect_shipping_details_from_wallet_connector: Option<bool>, } #[derive(Clone, Debug, ToSchema, Serialize)] @@ -1055,6 +1058,9 @@ pub struct BusinessProfileUpdate { // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, + + /// A boolean value to indicate if cusomter shipping details needs to be sent for wallets payments + pub collect_shipping_details_from_wallet_connector: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 37d17dcff17..866db8cc18d 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -422,6 +422,13 @@ pub enum FieldType { UserAddressPincode, UserAddressState, UserAddressCountry { options: Vec<String> }, + UserShippingName, + UserShippingAddressLine1, + UserShippingAddressLine2, + UserShippingAddressCity, + UserShippingAddressPincode, + UserShippingAddressState, + UserShippingAddressCountry { options: Vec<String> }, UserBlikCode, UserBank, Text, @@ -440,6 +447,18 @@ impl FieldType { Self::UserAddressCountry { options: vec![] }, ] } + + pub fn get_shipping_variants() -> Vec<Self> { + vec![ + Self::UserShippingName, + Self::UserShippingAddressLine1, + Self::UserShippingAddressLine2, + Self::UserShippingAddressCity, + Self::UserShippingAddressPincode, + Self::UserShippingAddressState, + Self::UserShippingAddressCountry { options: vec![] }, + ] + } } /// This implementatiobn is to ignore the inner value of UserAddressCountry enum while comparing @@ -477,6 +496,15 @@ impl PartialEq for FieldType { (Self::UserAddressPincode, Self::UserAddressPincode) => true, (Self::UserAddressState, Self::UserAddressState) => true, (Self::UserAddressCountry { .. }, Self::UserAddressCountry { .. }) => true, + (Self::UserShippingName, Self::UserShippingName) => true, + (Self::UserShippingAddressLine1, Self::UserShippingAddressLine1) => true, + (Self::UserShippingAddressLine2, Self::UserShippingAddressLine2) => true, + (Self::UserShippingAddressCity, Self::UserShippingAddressCity) => true, + (Self::UserShippingAddressPincode, Self::UserShippingAddressPincode) => true, + (Self::UserShippingAddressState, Self::UserShippingAddressState) => true, + (Self::UserShippingAddressCountry { .. }, Self::UserShippingAddressCountry { .. }) => { + true + } (Self::UserBlikCode, Self::UserBlikCode) => true, (Self::UserBank, Self::UserBank) => true, (Self::Text, Self::Text) => true, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 20b94811ab2..343763321da 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4098,6 +4098,12 @@ pub struct GooglePayThirdPartySdk { pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, + /// Is shipping address required + pub shipping_address_required: bool, + /// Is email required + pub email_required: bool, + /// Shipping address parameters + pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires @@ -4112,6 +4118,13 @@ pub struct GooglePaySessionResponse { pub secrets: Option<SecretInfoToInitiateSdk>, } +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[serde(rename_all = "lowercase")] +pub struct GpayShippingAddressParameters { + /// Is shipping phone number required + pub phone_number_required: bool, +} + #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { @@ -4234,7 +4247,22 @@ pub struct ApplePayPaymentRequest { pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector - pub required_billing_contact_fields: Option<Vec<String>>, + pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, + /// The required shipping contacht fields for connector + pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] +pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] +pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); + +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ApplePayAddressParameters { + PostalAddress, + Phone, + Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 41a938d83ed..fb1b62e5436 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -39,6 +39,7 @@ pub struct BusinessProfile { pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, + pub collect_shipping_details_from_wallet_connector: Option<bool>, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -69,6 +70,7 @@ pub struct BusinessProfileNew { pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, + pub collect_shipping_details_from_wallet_connector: Option<bool>, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] @@ -96,6 +98,7 @@ pub struct BusinessProfileUpdateInternal { pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, + pub collect_shipping_details_from_wallet_connector: Option<bool>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -120,6 +123,7 @@ pub enum BusinessProfileUpdate { authentication_connector_details: Option<serde_json::Value>, extended_card_info_config: Option<pii::SecretSerdeValue>, use_billing_as_payment_method_billing: Option<bool>, + collect_shipping_details_from_wallet_connector: Option<bool>, }, ExtendedCardInfoUpdate { is_extended_card_info_enabled: Option<bool>, @@ -152,6 +156,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { authentication_connector_details, extended_card_info_config, use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector, } => Self { profile_name, modified_at, @@ -172,6 +177,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { authentication_connector_details, extended_card_info_config, use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector, ..Default::default() }, BusinessProfileUpdate::ExtendedCardInfoUpdate { @@ -217,6 +223,8 @@ impl From<BusinessProfileNew> for BusinessProfile { is_extended_card_info_enabled: new.is_extended_card_info_enabled, extended_card_info_config: new.extended_card_info_config, use_billing_as_payment_method_billing: new.use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector: new + .collect_shipping_details_from_wallet_connector, } } } @@ -245,6 +253,7 @@ impl BusinessProfileUpdate { extended_card_info_config, is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector, } = self.into(); BusinessProfile { profile_name: profile_name.unwrap_or(source.profile_name), @@ -270,6 +279,7 @@ impl BusinessProfileUpdate { is_connector_agnostic_mit_enabled, extended_card_info_config, use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector, ..source } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index a81c240e8b0..e63c14eef15 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -195,6 +195,7 @@ diesel::table! { extended_card_info_config -> Nullable<Jsonb>, is_connector_agnostic_mit_enabled -> Nullable<Bool>, use_billing_as_payment_method_billing -> Nullable<Bool>, + collect_shipping_details_from_wallet_connector -> Nullable<Bool>, } } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 12a507ffed9..5f5597387b1 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -344,6 +344,9 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::NoThirdPartySdkSessionResponse, api_models::payments::SecretInfoToInitiateSdk, api_models::payments::ApplePayPaymentRequest, + api_models::payments::ApplePayBillingContactFields, + api_models::payments::ApplePayShippingContactFields, + api_models::payments::ApplePayAddressParameters, api_models::payments::AmountInfo, api_models::payments::ProductType, api_models::payments::GooglePayWalletData, @@ -388,6 +391,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::GooglePayRedirectData, api_models::payments::GooglePayThirdPartySdk, api_models::payments::GooglePaySessionResponse, + api_models::payments::GpayShippingAddressParameters, api_models::payments::GpayBillingAddressParameters, api_models::payments::GpayBillingAddressFormat, api_models::payments::SepaBankTransferInstructions, diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 4fcdd76992e..667bc90fe45 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -6995,6 +6995,73 @@ impl Default for super::settings::RequiredFields { value: None, } ), + ( + "shipping.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.first_name".to_string(), + display_name: "shipping_first_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.last_name".to_string(), + display_name: "shipping_last_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.city".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::UserShippingAddressCity, + value: None, + } + ), + ( + "shipping.address.state".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.state".to_string(), + display_name: "state".to_string(), + field_type: enums::FieldType::UserShippingAddressState, + value: None, + } + ), + ( + "shipping.address.zip".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::UserShippingAddressPincode, + value: None, + } + ), + ( + "shipping.address.country".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserShippingAddressCountry{ + options: vec![ + "ALL".to_string(), + ] + }, + value: None, + } + ), + ( + "shipping.address.line1".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::UserShippingAddressLine1, + value: None, + } + ), ] ), common: HashMap::new(), @@ -7082,6 +7149,73 @@ impl Default for super::settings::RequiredFields { value: None, } ), + ( + "shipping.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.first_name".to_string(), + display_name: "shipping_first_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.last_name".to_string(), + display_name: "shipping_last_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.city".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::UserShippingAddressCity, + value: None, + } + ), + ( + "shipping.address.state".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.state".to_string(), + display_name: "state".to_string(), + field_type: enums::FieldType::UserShippingAddressState, + value: None, + } + ), + ( + "shipping.address.zip".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::UserShippingAddressPincode, + value: None, + } + ), + ( + "shipping.address.country".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserShippingAddressCountry{ + options: vec![ + "ALL".to_string(), + ] + }, + value: None, + } + ), + ( + "shipping.address.line1".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::UserShippingAddressLine1, + value: None, + } + ), ] ), common: HashMap::new(), @@ -7184,6 +7318,73 @@ impl Default for super::settings::RequiredFields { value: None, } ), + ( + "shipping.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.first_name".to_string(), + display_name: "shipping_first_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.last_name".to_string(), + display_name: "shipping_last_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.city".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::UserShippingAddressCity, + value: None, + } + ), + ( + "shipping.address.state".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.state".to_string(), + display_name: "state".to_string(), + field_type: enums::FieldType::UserShippingAddressState, + value: None, + } + ), + ( + "shipping.address.zip".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::UserShippingAddressPincode, + value: None, + } + ), + ( + "shipping.address.country".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserShippingAddressCountry{ + options: vec![ + "ALL".to_string(), + ] + }, + value: None, + } + ), + ( + "shipping.address.line1".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::UserShippingAddressLine1, + value: None, + } + ), ] ), common: HashMap::new(), @@ -7411,6 +7612,73 @@ impl Default for super::settings::RequiredFields { value: None, } ), + ( + "shipping.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.first_name".to_string(), + display_name: "shipping_first_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.last_name".to_string(), + display_name: "shipping_last_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.city".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::UserShippingAddressCity, + value: None, + } + ), + ( + "shipping.address.state".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.state".to_string(), + display_name: "state".to_string(), + field_type: enums::FieldType::UserShippingAddressState, + value: None, + } + ), + ( + "shipping.address.zip".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::UserShippingAddressPincode, + value: None, + } + ), + ( + "shipping.address.country".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserShippingAddressCountry{ + options: vec![ + "ALL".to_string(), + ] + }, + value: None, + } + ), + ( + "shipping.address.line1".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::UserShippingAddressLine1, + value: None, + } + ), ] ), common: HashMap::new(), @@ -7436,7 +7704,77 @@ impl Default for super::settings::RequiredFields { enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), - non_mandate: HashMap::new(), + non_mandate: HashMap::from( + [ + ( + "shipping.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.first_name".to_string(), + display_name: "shipping_first_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.last_name".to_string(), + display_name: "shipping_last_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.city".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::UserShippingAddressCity, + value: None, + } + ), + ( + "shipping.address.state".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.state".to_string(), + display_name: "state".to_string(), + field_type: enums::FieldType::UserShippingAddressState, + value: None, + } + ), + ( + "shipping.address.zip".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::UserShippingAddressPincode, + value: None, + } + ), + ( + "shipping.address.country".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserShippingAddressCountry{ + options: vec![ + "ALL".to_string(), + ] + }, + value: None, + } + ), + ( + "shipping.address.line1".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::UserShippingAddressLine1, + value: None, + } + ), + ] + ), common: HashMap::new(), } ), diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 251a928c09e..d1dbb9d92e7 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -539,6 +539,7 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<BluesnapWalletTokenRespons supported_networks: Some(payment_request_data.supported_networks), merchant_identifier: Some(session_token_data.merchant_identifier), required_billing_contact_fields: None, + required_shipping_contact_fields: None, }), connector: "bluesnap".to_string(), delayed_session_token: false, diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index 686858008b6..b04b8cb4745 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -551,6 +551,7 @@ impl<F> supported_networks: None, merchant_identifier: None, required_billing_contact_fields: None, + required_shipping_contact_fields: None, }, ), connector: "payme".to_string(), diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 7f84e301916..db225585f41 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -1224,6 +1224,7 @@ pub fn get_apple_pay_session<F, T>( total: apple_pay_init_result.total.into(), merchant_identifier: None, required_billing_contact_fields: None, + required_shipping_contact_fields: None, }), connector: "trustpay".to_string(), delayed_session_token: true, @@ -1281,6 +1282,12 @@ pub fn get_google_pay_session<F, T>( .collect(), transaction_info: google_pay_init_result.transaction_info.into(), secrets: Some((*secrets).clone().into()), + shipping_address_required: false, + email_required: false, + shipping_address_parameters: + api_models::payments::GpayShippingAddressParameters { + phone_number_required: false, + }, }, ), ))), diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 422b88ee9ef..288de66de07 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -441,6 +441,7 @@ pub async fn update_business_profile_cascade( authentication_connector_details: None, extended_card_info_config: None, use_billing_as_payment_method_billing: None, + collect_shipping_details_from_wallet_connector: None, }; let update_futures = business_profiles.iter().map(|business_profile| async { @@ -1693,6 +1694,8 @@ pub async fn update_business_profile( })?, extended_card_info_config, use_billing_as_payment_method_billing: request.use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector: request + .collect_shipping_details_from_wallet_connector, }; let updated_business_profile = db diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 8c946630c8a..833f18f6afd 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2192,6 +2192,7 @@ pub async fn list_payment_methods( let mut bank_transfer_consolidated_hm = HashMap::<api_enums::PaymentMethodType, Vec<String>>::new(); + // All the required fields will be stored here and later filtered out based on business profile config let mut required_fields_hm = HashMap::< api_enums::PaymentMethod, HashMap<api_enums::PaymentMethodType, HashMap<String, RequiredFieldInfo>>, @@ -2230,6 +2231,31 @@ pub async fn list_payment_methods( } } + let should_send_shipping_details = + business_profile.clone().and_then(|business_profile| { + business_profile + .collect_shipping_details_from_wallet_connector + }); + + // Remove shipping fields from required fields based on business profile configuration + if should_send_shipping_details != Some(true) { + let shipping_variants = + api_enums::FieldType::get_shipping_variants(); + + let keys_to_be_removed = required_fields_hs + .iter() + .filter(|(_key, value)| { + shipping_variants.contains(&value.field_type) + }) + .map(|(key, _value)| key.to_string()) + .collect::<Vec<_>>(); + + keys_to_be_removed.iter().for_each(|key_to_be_removed| { + required_fields_hs.remove(key_to_be_removed); + }); + } + + // get the config, check the enums while adding { for (key, val) in &mut required_fields_hs { let temp = req_val diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 578b8d80302..af286984d61 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -298,6 +298,7 @@ where frm_info.as_ref().and_then(|fi| fi.suggested_action), #[cfg(not(feature = "frm"))] None, + &business_profile, ) .await?; @@ -367,6 +368,7 @@ where frm_info.as_ref().and_then(|fi| fi.suggested_action), #[cfg(not(feature = "frm"))] None, + &business_profile, ) .await?; @@ -399,6 +401,7 @@ where frm_info.as_ref().and_then(|fi| fi.suggested_action), #[cfg(not(feature = "frm"))] None, + &business_profile, ) .await?; }; @@ -452,6 +455,7 @@ where payment_data, &customer, session_surcharge_details, + &business_profile, )) .await? } @@ -1400,6 +1404,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, Ctx>( schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, + business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, @@ -1598,7 +1603,13 @@ where // and rely on previous status set in router_data router_data.status = payment_data.payment_attempt.status; router_data - .decide_flows(state, &connector, call_connector_action, connector_request) + .decide_flows( + state, + &connector, + call_connector_action, + connector_request, + business_profile, + ) .await } else { Ok(router_data) @@ -1660,6 +1671,7 @@ pub async fn call_multiple_connectors_service<F, Op, Req, Ctx>( mut payment_data: PaymentData<F>, customer: &Option<domain::Customer>, session_surcharge_details: Option<api::SessionSurchargeDetails>, + business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<PaymentData<F>> where Op: Debug, @@ -1723,6 +1735,7 @@ where &session_connector_data.connector, CallConnectorAction::Trigger, None, + business_profile, ); join_handlers.push(res); diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index e1bd785830e..a8425896dd7 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -21,7 +21,7 @@ use crate::{ }, routes::AppState, services, - types::{self, api, domain}, + types::{self, api, domain, storage}, }; #[async_trait] @@ -46,6 +46,7 @@ pub trait Feature<F, T> { connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, + business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<Self> where Self: Sized, diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rs index ffa11fdb0f5..92f815f6b5f 100644 --- a/crates/router/src/core/payments/flows/approve_flow.rs +++ b/crates/router/src/core/payments/flows/approve_flow.rs @@ -8,7 +8,7 @@ use crate::{ }, routes::AppState, services, - types::{self, api, domain}, + types::{self, api, domain, storage}, }; #[async_trait] @@ -51,6 +51,7 @@ impl Feature<api::Approve, types::PaymentsApproveData> _connector: &api::ConnectorData, _call_connector_action: payments::CallConnectorAction, _connector_request: Option<services::Request>, + _business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<Self> { Err(ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Reason("Flow not supported".to_string()), diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index b2773ea9aaf..a770454b204 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -14,7 +14,7 @@ use crate::{ logger, routes::{metrics, AppState}, services, - types::{self, api, domain}, + types::{self, api, domain, storage}, }; #[async_trait] @@ -63,6 +63,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, + _business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<Self> { let connector_integration: services::BoxedConnectorIntegration< '_, diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index 5f802a0bbe8..0e90ab40b69 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -8,7 +8,7 @@ use crate::{ }, routes::{metrics, AppState}, services, - types::{self, api, domain}, + types::{self, api, domain, storage}, }; #[async_trait] @@ -50,6 +50,7 @@ impl Feature<api::Void, types::PaymentsCancelData> connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, + _business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<Self> { metrics::PAYMENT_CANCEL_COUNT.add( &metrics::CONTEXT, diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index 56ae6500c35..b979eb2a337 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -8,7 +8,7 @@ use crate::{ }, routes::AppState, services, - types::{self, api, domain}, + types::{self, api, domain, storage}, }; #[async_trait] @@ -51,6 +51,7 @@ impl Feature<api::Capture, types::PaymentsCaptureData> connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, + _business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<Self> { let connector_integration: services::BoxedConnectorIntegration< '_, 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 667fa3feed0..4e9bf47232f 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -8,7 +8,7 @@ use crate::{ }, routes::{metrics, AppState}, services, - types::{self, api, domain}, + types::{self, api, domain, storage}, utils::OptionExt, }; @@ -65,6 +65,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData> connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, + _business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<Self> { let connector_integration: services::BoxedConnectorIntegration< '_, 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 e702483022c..716228d73f7 100644 --- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs +++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs @@ -8,7 +8,7 @@ use crate::{ }, routes::AppState, services, - types::{self, api, domain}, + types::{self, api, domain, storage}, }; #[async_trait] @@ -58,6 +58,7 @@ impl Feature<api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizat connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, + _business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<Self> { let connector_integration: services::BoxedConnectorIntegration< '_, diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index f410b65f076..d1e2e4b0abe 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -10,7 +10,7 @@ use crate::{ }, routes::AppState, services::{self, logger}, - types::{self, api, domain}, + types::{self, api, domain, storage}, }; #[async_trait] @@ -54,6 +54,7 @@ impl Feature<api::PSync, types::PaymentsSyncData> connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, + _business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<Self> { let connector_integration: services::BoxedConnectorIntegration< '_, diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rs index 89c1585fca1..726993aa7fa 100644 --- a/crates/router/src/core/payments/flows/reject_flow.rs +++ b/crates/router/src/core/payments/flows/reject_flow.rs @@ -8,7 +8,7 @@ use crate::{ }, routes::AppState, services, - types::{self, api, domain}, + types::{self, api, domain, storage}, }; #[async_trait] @@ -50,6 +50,7 @@ impl Feature<api::Reject, types::PaymentsRejectData> _connector: &api::ConnectorData, _call_connector_action: payments::CallConnectorAction, _connector_request: Option<services::Request>, + _business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<Self> { Err(ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Reason("Flow not supported".to_string()), diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index c83c73f7624..e0837be2512 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -16,7 +16,7 @@ use crate::{ types::{ self, api::{self, enums}, - domain, + domain, storage, }, utils::OptionExt, }; @@ -59,6 +59,7 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, _connector_request: Option<services::Request>, + business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<Self> { metrics::SESSION_TOKEN_CREATED.add( &metrics::CONTEXT, @@ -68,8 +69,14 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio connector.connector_name.to_string(), )], ); - self.decide_flow(state, connector, Some(true), call_connector_action) - .await + self.decide_flow( + state, + connector, + Some(true), + call_connector_action, + business_profile, + ) + .await } async fn add_access_token<'a>( @@ -173,6 +180,7 @@ async fn create_applepay_session_token( state: &routes::AppState, router_data: &types::PaymentsSessionRouterData, connector: &api::ConnectorData, + business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<types::PaymentsSessionRouterData> { let delayed_response = is_session_response_delayed(state, connector); if delayed_response { @@ -286,17 +294,36 @@ async fn create_applepay_session_token( let billing_variants = enums::FieldType::get_billing_variants(); - let required_billing_contact_fields = if is_dynamic_fields_required( + let required_billing_contact_fields = is_dynamic_fields_required( &state.conf.required_fields, enums::PaymentMethod::Wallet, enums::PaymentMethodType::ApplePay, &connector.connector_name, billing_variants, - ) { - Some(vec!["postalAddress".to_string()]) - } else { - None - }; + ) + .then_some(payment_types::ApplePayBillingContactFields(vec![ + payment_types::ApplePayAddressParameters::PostalAddress, + ])); + + let required_shipping_contact_fields = + if business_profile.collect_shipping_details_from_wallet_connector == Some(true) { + let shipping_variants = enums::FieldType::get_shipping_variants(); + + is_dynamic_fields_required( + &state.conf.required_fields, + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::ApplePay, + &connector.connector_name, + shipping_variants, + ) + .then_some(payment_types::ApplePayShippingContactFields(vec![ + payment_types::ApplePayAddressParameters::PostalAddress, + payment_types::ApplePayAddressParameters::Phone, + payment_types::ApplePayAddressParameters::Email, + ])) + } else { + None + }; // Get apple pay payment request let applepay_payment_request = get_apple_pay_payment_request( @@ -306,6 +333,7 @@ async fn create_applepay_session_token( apple_pay_session_request.merchant_identifier.as_str(), merchant_business_country, required_billing_contact_fields, + required_shipping_contact_fields, )?; let applepay_session_request = build_apple_pay_session_request( @@ -406,7 +434,8 @@ fn get_apple_pay_payment_request( session_data: types::PaymentsSessionData, merchant_identifier: &str, merchant_business_country: Option<api_models::enums::CountryAlpha2>, - required_billing_contact_fields: Option<Vec<String>>, + required_billing_contact_fields: Option<payment_types::ApplePayBillingContactFields>, + required_shipping_contact_fields: Option<payment_types::ApplePayShippingContactFields>, ) -> RouterResult<payment_types::ApplePayPaymentRequest> { let applepay_payment_request = payment_types::ApplePayPaymentRequest { country_code: merchant_business_country.or(session_data.country).ok_or( @@ -420,6 +449,7 @@ fn get_apple_pay_payment_request( supported_networks: Some(payment_request_data.supported_networks), merchant_identifier: Some(merchant_identifier.to_string()), required_billing_contact_fields, + required_shipping_contact_fields, }; Ok(applepay_payment_request) } @@ -463,6 +493,7 @@ fn create_gpay_session_token( state: &routes::AppState, router_data: &types::PaymentsSessionRouterData, connector: &api::ConnectorData, + business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<types::PaymentsSessionRouterData> { let connector_metadata = router_data.connector_meta_data.clone(); let delayed_response = is_session_response_delayed(state, connector); @@ -546,6 +577,21 @@ fn create_gpay_session_token( })?, }; + let required_shipping_contact_fields = + if business_profile.collect_shipping_details_from_wallet_connector == Some(true) { + let shipping_variants = enums::FieldType::get_shipping_variants(); + + is_dynamic_fields_required( + &state.conf.required_fields, + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::GooglePay, + &connector.connector_name, + shipping_variants, + ) + } else { + false + }; + Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::GooglePay(Box::new( @@ -560,6 +606,12 @@ fn create_gpay_session_token( }, delayed_session_token: false, secrets: None, + shipping_address_required: required_shipping_contact_fields, + email_required: required_shipping_contact_fields, + shipping_address_parameters: + api_models::payments::GpayShippingAddressParameters { + phone_number_required: required_shipping_contact_fields, + }, }, ), )), @@ -597,11 +649,14 @@ impl types::PaymentsSessionRouterData { connector: &api::ConnectorData, _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, + business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<Self> { match connector.get_token { - api::GetToken::GpayMetadata => create_gpay_session_token(state, self, connector), + api::GetToken::GpayMetadata => { + create_gpay_session_token(state, self, connector, business_profile) + } api::GetToken::ApplePayMetadata => { - create_applepay_session_token(state, self, connector).await + create_applepay_session_token(state, self, connector, business_profile).await } api::GetToken::Connector => { let connector_integration: services::BoxedConnectorIntegration< 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 59f7ee17551..cdadb355d4a 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -11,7 +11,7 @@ use crate::{ }, routes::AppState, services, - types::{self, api, domain}, + types::{self, api, domain, storage}, }; #[async_trait] @@ -55,6 +55,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, + _business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<Self> { let connector_integration: services::BoxedConnectorIntegration< '_, diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 58c58ffaef8..489580e5b7f 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -45,6 +45,7 @@ pub async fn do_gsm_actions<F, ApiRequest, FData, Ctx>( validate_result: &operations::ValidateResult<'_>, schedule_time: Option<time::PrimitiveDateTime>, frm_suggestion: Option<storage_enums::FrmSuggestion>, + business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> where F: Clone + Send + Sync, @@ -97,6 +98,7 @@ where schedule_time, true, frm_suggestion, + business_profile, ) .await?; } @@ -142,6 +144,7 @@ where //this is an auto retry payment, but not step-up false, frm_suggestion, + business_profile, ) .await?; @@ -281,6 +284,7 @@ pub async fn do_retry<F, ApiRequest, FData, Ctx>( schedule_time: Option<time::PrimitiveDateTime>, is_step_up: bool, frm_suggestion: Option<storage_enums::FrmSuggestion>, + business_profile: &storage::business_profile::BusinessProfile, ) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> where F: Clone + Send + Sync, @@ -318,6 +322,7 @@ where schedule_time, api::HeaderPayload::default(), frm_suggestion, + business_profile, ) .await } diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 3449838164b..894e09ab60e 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -265,6 +265,7 @@ pub async fn update_business_profile_active_algorithm_ref( authentication_connector_details: None, extended_card_info_config: None, use_billing_as_payment_method_billing: None, + collect_shipping_details_from_wallet_connector: None, }; db.update_business_profile_by_profile_id(current_business_profile, business_profile_update) diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 262999af949..fcbd97d5cb1 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -182,6 +182,8 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)> use_billing_as_payment_method_billing: request .use_billing_as_payment_method_billing .or(Some(true)), + collect_shipping_details_from_wallet_connector: request + .collect_shipping_details_from_wallet_connector, }) } } diff --git a/migrations/2024-05-09-130152_collect_shipping_details_from_wallet_connector/down.sql b/migrations/2024-05-09-130152_collect_shipping_details_from_wallet_connector/down.sql new file mode 100644 index 00000000000..c2ffc7cff85 --- /dev/null +++ b/migrations/2024-05-09-130152_collect_shipping_details_from_wallet_connector/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` + +ALTER TABLE business_profile DROP COLUMN IF EXISTS collect_shipping_details_from_wallet_connector; \ No newline at end of file diff --git a/migrations/2024-05-09-130152_collect_shipping_details_from_wallet_connector/up.sql b/migrations/2024-05-09-130152_collect_shipping_details_from_wallet_connector/up.sql new file mode 100644 index 00000000000..f949c81213c --- /dev/null +++ b/migrations/2024-05-09-130152_collect_shipping_details_from_wallet_connector/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here + +ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS collect_shipping_details_from_wallet_connector BOOLEAN DEFAULT FALSE; \ No newline at end of file diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index d9061baebb3..b5c453c2397 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4963,6 +4963,20 @@ } ] }, + "ApplePayAddressParameters": { + "type": "string", + "enum": [ + "postalAddress", + "phone", + "email" + ] + }, + "ApplePayBillingContactFields": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ApplePayAddressParameters" + } + }, "ApplePayPaymentRequest": { "type": "object", "required": [ @@ -5001,11 +5015,19 @@ "nullable": true }, "required_billing_contact_fields": { - "type": "array", - "items": { - "type": "string" - }, - "description": "The required billing contact fields for connector", + "allOf": [ + { + "$ref": "#/components/schemas/ApplePayBillingContactFields" + } + ], + "nullable": true + }, + "required_shipping_contact_fields": { + "allOf": [ + { + "$ref": "#/components/schemas/ApplePayShippingContactFields" + } + ], "nullable": true } } @@ -5028,6 +5050,12 @@ } ] }, + "ApplePayShippingContactFields": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ApplePayAddressParameters" + } + }, "ApplePayThirdPartySdkData": { "type": "object" }, @@ -6735,6 +6763,11 @@ "type": "boolean", "description": "Whether to use the billing details passed when creating the intent as payment method billing", "nullable": true + }, + "collect_shipping_details_from_wallet_connector": { + "type": "boolean", + "description": "A boolean value to indicate if cusomter shipping details needs to be sent for wallets payments", + "nullable": true } }, "additionalProperties": false @@ -9094,6 +9127,64 @@ } } }, + { + "type": "string", + "enum": [ + "user_shipping_name" + ] + }, + { + "type": "string", + "enum": [ + "user_shipping_address_line1" + ] + }, + { + "type": "string", + "enum": [ + "user_shipping_address_line2" + ] + }, + { + "type": "string", + "enum": [ + "user_shipping_address_city" + ] + }, + { + "type": "string", + "enum": [ + "user_shipping_address_pincode" + ] + }, + { + "type": "string", + "enum": [ + "user_shipping_address_state" + ] + }, + { + "type": "object", + "required": [ + "user_shipping_address_country" + ], + "properties": { + "user_shipping_address_country": { + "type": "object", + "required": [ + "options" + ], + "properties": { + "options": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + } + }, { "type": "string", "enum": [ @@ -9335,6 +9426,9 @@ "type": "object", "required": [ "merchant_info", + "shipping_address_required", + "email_required", + "shipping_address_parameters", "allowed_payment_methods", "transaction_info", "delayed_session_token", @@ -9345,6 +9439,17 @@ "merchant_info": { "$ref": "#/components/schemas/GpayMerchantInfo" }, + "shipping_address_required": { + "type": "boolean", + "description": "Is shipping address required" + }, + "email_required": { + "type": "boolean", + "description": "Is email required" + }, + "shipping_address_parameters": { + "$ref": "#/components/schemas/GpayShippingAddressParameters" + }, "allowed_payment_methods": { "type": "array", "items": { @@ -9531,6 +9636,18 @@ } ] }, + "GpayShippingAddressParameters": { + "type": "object", + "required": [ + "phone_number_required" + ], + "properties": { + "phone_number_required": { + "type": "boolean", + "description": "Is shipping phone number required" + } + } + }, "GpayTokenParameters": { "type": "object", "required": [
2024-05-09T18:15:24Z
## Description <!-- Describe your changes in detail --> This change is required as part of the one click checkout where in which we expect apple pay to collect the shipping details from the customer and pass it in the confirm call with the payment_data. In order for apple pay to collect the shipping details from customer we need to pass `"requiredShippingContactFields": ["postalAddress", "phone", "email"]` in the `/session` call. Hence we need to have a validation in the backend that checks for the business profile config (`collect_shipping_details_from_wallet_connector`) fields and pass the `required_shipping_contact_fields` to sdk. Similarly for google_pay we need to pass the below fields for shipping details. ``` "shipping_address_required": true, "email_required": true, "shipping_address_parameters": { "phone_number_required": true }, ``` ### 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` --> -> Create a MCA for cybersource enable `google_pay` and `apple_pay` -> Update a field in `business_profile` ``` curl --location 'http://localhost:8080/account/merchant_1715276947/business_profile/pro_DnFkGi1RPLPSmJKy54Ib' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "collect_shipping_details_from_wallet_connector": true }' ``` -> Apple pay payment create with confirm false ``` { "amount": 650, "currency": "USD", "confirm": false, "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", "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":"eyJkYXRhIjoiQ1ZoTGd5RGU3TzZjdFlhWHFiVWFONFZvRjBCQjhTbDZsenlXYUdCKzhKcXlic2hYVGxoNEFEcTZYb0t6ZWVSVGwvcUp6NDIvUFMwcmMxMCtqSyt5Z1F5NnlkT25EcnVDeVpkaVU4SWFGOEtOS2hJMFFKOU9JTk9aWFlYR0VzZEczNXlVNzcrQ0k1dk5lUjJiK1gyUXZTVTMzSjlOczJuTFRXZHpwb1VUSHJKU1RiSmFmTTlxYjlZOHZuZS9vZUdHQkV1ZU9DQWQxcFhjRE54SEl2dlc5Z0x3WXRPVldKZUEvUnh5MEdsb0VISng3VEhqUEVQUGJwMkVVZjRMQXZQOGlJSEpmUjM0THdEUVBIdmNSeW9nalRJSzJqOXZjUGRqS2xBSG1LUm5wZlhvWkY4VE16ZUJ6eWhGb0dKY3ZRa3JMc216OEcxTXowZGxlV2VmU2V0TkYxT1NMaldCdExrUXpvWG5xdU1ZeExMenU2SkxPZ1E5ejN1OStFNGQ2NHRZS1NYYlZBWGRKNXRMNTdvbSIsInNpZ25hdHVyZSI6Ik1JQUdDU3FHU0liM0RRRUhBcUNBTUlBQ0FRRXhEVEFMQmdsZ2hrZ0JaUU1FQWdFd2dBWUpLb1pJaHZjTkFRY0JBQUNnZ0RDQ0ErTXdnZ09Jb0FNQ0FRSUNDRXd3UVVsUm5WUTJNQW9HQ0NxR1NNNDlCQU1DTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekFlRncweE9UQTFNVGd3TVRNeU5UZGFGdzB5TkRBMU1UWXdNVE15TlRkYU1GOHhKVEFqQmdOVkJBTU1IR1ZqWXkxemJYQXRZbkp2YTJWeUxYTnBaMjVmVlVNMExWQlNUMFF4RkRBU0JnTlZCQXNNQzJsUFV5QlRlWE4wWlcxek1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpCWk1CTUdCeXFHU000OUFnRUdDQ3FHU000OUF3RUhBMElBQk1JVmQrM3Ixc2V5SVk5bzNYQ1FvU0dOeDdDOWJ5d29QWVJnbGRsSzlLVkJHNE5DRHRnUjgwQitnek1mSEZURDkrc3lJTmE2MWRUdjlKS0ppVDU4RHhPamdnSVJNSUlDRFRBTUJnTlZIUk1CQWY4RUFqQUFNQjhHQTFVZEl3UVlNQmFBRkNQeVNjUlBrK1R2SitiRTlpaHNQNks3L1M1TE1FVUdDQ3NHQVFVRkJ3RUJCRGt3TnpBMUJnZ3JCZ0VGQlFjd0FZWXBhSFIwY0RvdkwyOWpjM0F1WVhCd2JHVXVZMjl0TDI5amMzQXdOQzFoY0hCc1pXRnBZMkV6TURJd2dnRWRCZ05WSFNBRWdnRVVNSUlCRURDQ0FRd0dDU3FHU0liM1kyUUZBVENCL2pDQnd3WUlLd1lCQlFVSEFnSXdnYllNZ2JOU1pXeHBZVzVqWlNCdmJpQjBhR2x6SUdObGNuUnBabWxqWVhSbElHSjVJR0Z1ZVNCd1lYSjBlU0JoYzNOMWJXVnpJR0ZqWTJWd2RHRnVZMlVnYjJZZ2RHaGxJSFJvWlc0Z1lYQndiR2xqWVdKc1pTQnpkR0Z1WkdGeVpDQjBaWEp0Y3lCaGJtUWdZMjl1WkdsMGFXOXVjeUJ2WmlCMWMyVXNJR05sY25ScFptbGpZWFJsSUhCdmJHbGplU0JoYm1RZ1kyVnlkR2xtYVdOaGRHbHZiaUJ3Y21GamRHbGpaU0J6ZEdGMFpXMWxiblJ6TGpBMkJnZ3JCZ0VGQlFjQ0FSWXFhSFIwY0RvdkwzZDNkeTVoY0hCc1pTNWpiMjB2WTJWeWRHbG1hV05oZEdWaGRYUm9iM0pwZEhrdk1EUUdBMVVkSHdRdE1Dc3dLYUFub0NXR0kyaDBkSEE2THk5amNtd3VZWEJ3YkdVdVkyOXRMMkZ3Y0d4bFlXbGpZVE11WTNKc01CMEdBMVVkRGdRV0JCU1VWOXR2MVhTQmhvbUpkaTkrVjRVSDU1dFlKREFPQmdOVkhROEJBZjhFQkFNQ0I0QXdEd1lKS29aSWh2ZGpaQVlkQkFJRkFEQUtCZ2dxaGtqT1BRUURBZ05KQURCR0FpRUF2Z2xYSCtjZUhuTmJWZVd2ckxUSEwrdEVYekFZVWlMSEpSQUN0aDY5YjFVQ0lRRFJpelVLWGRiZGJyRjBZRFd4SHJMT2g4K2o1cTlzdllPQWlRM0lMTjJxWXpDQ0F1NHdnZ0oxb0FNQ0FRSUNDRWx0TDc4Nm1OcVhNQW9HQ0NxR1NNNDlCQU1DTUdjeEd6QVpCZ05WQkFNTUVrRndjR3hsSUZKdmIzUWdRMEVnTFNCSE16RW1NQ1FHQTFVRUN3d2RRWEJ3YkdVZ1EyVnlkR2xtYVdOaGRHbHZiaUJCZFhSb2IzSnBkSGt4RXpBUkJnTlZCQW9NQ2tGd2NHeGxJRWx1WXk0eEN6QUpCZ05WQkFZVEFsVlRNQjRYRFRFME1EVXdOakl6TkRZek1Gb1hEVEk1TURVd05qSXpORFl6TUZvd2VqRXVNQ3dHQTFVRUF3d2xRWEJ3YkdVZ1FYQndiR2xqWVhScGIyNGdTVzUwWldkeVlYUnBiMjRnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFOEJjUmhCblhaSVhWR2w0bGdRZDI2SUNpNzk1N3JrM2dqZnhMaytFelZ0Vm1Xeld1SXRDWGRnMGlUbnU2Q1AxMkY4Nkl5M2E3Wm5DK3lPZ3BoUDlVUmFPQjl6Q0I5REJHQmdnckJnRUZCUWNCQVFRNk1EZ3dOZ1lJS3dZQkJRVUhNQUdHS21oMGRIQTZMeTl2WTNOd0xtRndjR3hsTG1OdmJTOXZZM053TURRdFlYQndiR1Z5YjI5MFkyRm5NekFkQmdOVkhRNEVGZ1FVSS9KSnhFK1Q1TzhuNXNUMktHdy9vcnY5TGtzd0R3WURWUjBUQVFIL0JBVXdBd0VCL3pBZkJnTlZIU01FR0RBV2dCUzdzTjZoV0RPSW1xU0ttZDYrdmV1djJzc2txekEzQmdOVkhSOEVNREF1TUN5Z0txQW9oaVpvZEhSd09pOHZZM0pzTG1Gd2NHeGxMbU52YlM5aGNIQnNaWEp2YjNSallXY3pMbU55YkRBT0JnTlZIUThCQWY4RUJBTUNBUVl3RUFZS0tvWklodmRqWkFZQ0RnUUNCUUF3Q2dZSUtvWkl6ajBFQXdJRFp3QXdaQUl3T3M5eWcxRVdtYkdHK3pYRFZzcGl2L1FYN2RrUGRVMmlqcjd4bklGZVFyZUorSmozbTFtZm1OVkJEWStkNmNMK0FqQXlMZFZFSWJDakJYZHNYZk00TzVCbi9SZDhMQ0Z0bGsvR2NtbUNFbTlVK0hwOUc1bkxtd21KSVdFR21ROEpraDBBQURHQ0FZZ3dnZ0dFQWdFQk1JR0dNSG94TGpBc0JnTlZCQU1NSlVGd2NHeGxJRUZ3Y0d4cFkyRjBhVzl1SUVsdWRHVm5jbUYwYVc5dUlFTkJJQzBnUnpNeEpqQWtCZ05WQkFzTUhVRndjR3hsSUVObGNuUnBabWxqWVhScGIyNGdRWFYwYUc5eWFYUjVNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV3SUlUREJCU1ZHZFZEWXdDd1lKWUlaSUFXVURCQUlCb0lHVE1CZ0dDU3FHU0liM0RRRUpBekVMQmdrcWhraUc5dzBCQndFd0hBWUpLb1pJaHZjTkFRa0ZNUThYRFRJME1ETXhOREE1TkRNeU0xb3dLQVlKS29aSWh2Y05BUWswTVJzdNTdMRElUVUQwcVI3RHd5SGx1VG0xMjJCejA5c2FzMkJVWitFRTlVPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXBoMkNUKytubXZpYjU3YWNJZmVKTjFCQmJyZUEveG84N2p1b0xETDFnS1IvYy9wRDZYK0xKSGRYUGJnMFBIT3pYYjJFYm5RR1ZWYmZIWHRkQzBYTTdBPT0iLCJ0cmFuc2FjdGlvbklkIjoiMjBlYzhlM2I2N2YyYmNmMDExMDVmODAwNmEwNWFmNTRiNjBkZDIwMzgyOTdlMmExMmI0Y2FlNDY0ODhjYjZhOSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } } ``` -> Make a `/session` call ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: api_key' \ --data '{ "payment_id": "pay_oit9SUYrdsYlI0WvCh1L", "wallets": [], "client_secret": "pay_oit9SUYrdsYlI0WvCh1L_secret_N61PV7OLGKa7PI0dv2Wo" }' ``` Required shipping details set for `apple_pay` in the session call <img width="1146" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/37e47236-0d72-4a5b-9c29-22bb64c049c1"> Required shipping details set for `google_pay` in the session call <img width="1180" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/160df64f-17ed-46a1-b258-912fdf940a59"> List payment method list for merchant ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_vJbV82f2bSFHZyTTex4X_secret_sSognYwAhzqMANozUw34' \ --header 'Accept: application/json' \ --header 'api-key: api_key' ``` <img width="1170" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/bada5464-7c09-4868-a4d2-57141af19608"> ## 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)? -->
f5d1201ac9e99ba5f8af7bb44504d6392744eb10
[ "crates/api_models/src/admin.rs", "crates/api_models/src/enums.rs", "crates/api_models/src/payments.rs", "crates/diesel_models/src/business_profile.rs", "crates/diesel_models/src/schema.rs", "crates/openapi/src/openapi.rs", "crates/router/src/configs/defaults.rs", "crates/router/src/connector/bluesnap...
juspay/hyperswitch
juspay__hyperswitch-4606
Bug: fix: Fix bugs caused by token only flows - Password without special characters is not throwing parsing failed error. - Signup is not populating the `last_password_modified_at`. - Verify email is blacklisting all email tokens. - If the SPT token time is less than JWT time, some SPTs issued after that blacklist are not working.
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index c40d284ee3a..610d8ef8b1f 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -70,7 +70,9 @@ pub const LOCKER_REDIS_EXPIRY_SECONDS: u32 = 60 * 15; // 15 minutes pub const JWT_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days -pub const SINGLE_PURPOSE_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day +// This should be one day, but it is causing issue while checking token in blacklist. +// TODO: This should be fixed in future. +pub const SINGLE_PURPOSE_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days pub const JWT_TOKEN_COOKIE_NAME: &str = "login_token"; diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 83cdd1d318b..bfe01863550 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1421,9 +1421,13 @@ pub async fn verify_email_token_only_flow( .change_context(UserErrors::InternalServerError)? .into(); - let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) - .await - .map_err(|e| logger::error!(?e)); + if matches!(user_token.origin, domain::Origin::VerifyEmail) + || matches!(user_token.origin, domain::Origin::MagicLink) + { + let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) + .await + .map_err(|e| logger::error!(?e)); + } let current_flow = domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::VerifyEmail.into())?; diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 45f5d74d6f6..051e6ccf38e 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -1,4 +1,8 @@ -use std::{collections::HashSet, ops, str::FromStr}; +use std::{ + collections::HashSet, + ops::{self, Not}, + str::FromStr, +}; use api_models::{ admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api, @@ -172,8 +176,7 @@ impl UserPassword { has_upper_case = has_upper_case || c.is_uppercase(); has_lower_case = has_lower_case || c.is_lowercase(); has_numeric_value = has_numeric_value || c.is_numeric(); - has_special_character = - has_special_character || !(c.is_alphanumeric() && c.is_whitespace()); + has_special_character = has_special_character || !c.is_alphanumeric(); has_whitespace = has_whitespace || c.is_whitespace(); } @@ -510,6 +513,7 @@ pub struct NewUser { email: UserEmail, password: UserPassword, new_merchant: NewUserMerchant, + is_temporary_password: bool, } impl NewUser { @@ -614,12 +618,20 @@ impl TryFrom<NewUser> for storage_user::UserNew { fn try_from(value: NewUser) -> UserResult<Self> { let hashed_password = password::generate_password_hash(value.password.get_secret())?; + let now = common_utils::date_time::now(); Ok(Self { user_id: value.get_user_id(), name: value.get_name(), email: value.get_email().into_inner(), password: hashed_password, - ..Default::default() + is_verified: false, + created_at: Some(now), + last_modified_at: Some(now), + preferred_merchant_id: None, + totp_status: TotpStatus::NotSet, + totp_secret: None, + totp_recovery_codes: None, + last_password_modified_at: value.is_temporary_password.not().then_some(now), }) } } @@ -640,6 +652,7 @@ impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUser { password, user_id, new_merchant, + is_temporary_password: false, }) } } @@ -660,6 +673,7 @@ impl TryFrom<user_api::SignUpRequest> for NewUser { email, password, new_merchant, + is_temporary_password: false, }) } } @@ -680,6 +694,7 @@ impl TryFrom<user_api::ConnectAccountRequest> for NewUser { email, password, new_merchant, + is_temporary_password: true, }) } } @@ -700,6 +715,7 @@ impl TryFrom<user_api::CreateInternalUserRequest> for NewUser { email, password, new_merchant, + is_temporary_password: false, }) } } @@ -717,6 +733,9 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUser { email: user.0.email.clone().try_into()?, password: UserPassword::new_password_without_validation(user.0.password)?, new_merchant, + // This is true because we are not creating a user with this request. And if it is set + // to false, last_password_modified_at will be overwritten if this user is inserted. + is_temporary_password: true, }) } } @@ -736,6 +755,7 @@ impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser { email, password, new_merchant, + is_temporary_password: true, }) } }
2024-05-09T12:46:43Z
## Description <!-- Describe your changes in detail --> This PR fixes the following bugs: - Password without special characters is not throwing parsing failed error. - Signup is not populating the `last_password_modified_at`. - Verify email is blacklisting all email tokens. - If the SPT token time is less than JWT time, some SPTs issued after that blacklist are not working. ### 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 #4606. ## 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)? --> > [!NOTE] > This only works when email feature flag is disabled. - To check the password validation ``` curl --location 'http://localhost:8080/user/signup' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "unregistered email", "password": "password" }' ``` - If the password is valid, then you will get the following response ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiM2MwOTBiMDYtYWY2ZS00MDk0LTgwYzktMWEzOTlkOTQ2MjBjIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwiZXhwIjoxNzE1MzMzNTE1fQ.v3fBLoTdf01RDWs24ukphvNFuVQ9AsqaVBuUfjviEuQ", "token_type": "totp" } ```
f386f423c0e5fac55a24756d7ee7a3ce1c20fb13
> [!NOTE] > This only works when email feature flag is disabled. - To check the password validation ``` curl --location 'http://localhost:8080/user/signup' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "unregistered email", "password": "password" }' ``` - If the password is valid, then you will get the following response ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiM2MwOTBiMDYtYWY2ZS00MDk0LTgwYzktMWEzOTlkOTQ2MjBjIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwiZXhwIjoxNzE1MzMzNTE1fQ.v3fBLoTdf01RDWs24ukphvNFuVQ9AsqaVBuUfjviEuQ", "token_type": "totp" } ```
[ "crates/router/src/consts.rs", "crates/router/src/core/user.rs", "crates/router/src/types/domain/user.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4605
Bug: [FEATURE] [BAMBORA] Audit Fixes for connector Bambora ### Feature Description Following code improvements need to be done for connector Bambora: - Optional fields that are being passed for payments request need to be removed - 2XX and 4XX Error response should be handled properly - Separate try_from should be used for all the flows - Unwanted configs need to be removed - Default case handling needs to be removed ### Possible Implementation Following code improvements need to be done for connector Bambora: - Optional fields that are being passed for payments request need to be removed - 2XX and 4XX Error response should be handled properly - Separate try_from should be used for all the flows - Unwanted configs need to be removed - Default case handling needs to be removed ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 61d74863422..d9e7ec58f75 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -398,26 +398,9 @@ merchant_secret="Source verification key" payment_method_type = "CartesBancaires" [[bambora.debit]] payment_method_type = "UnionPay" -[[bambora.wallet]] - payment_method_type = "apple_pay" -[[bambora.wallet]] - payment_method_type = "paypal" [bambora.connector_auth.BodyKey] api_key="Passcode" key1="Merchant Id" -[bambora.connector_webhook_details] -merchant_secret="Source verification key" -[bambora.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="Domain" -initiative_context="Domain Name" -[bambora.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" [bankofamerica] [[bankofamerica.credit]] diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 10cd9d6f7cf..202bce64c1f 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -416,27 +416,9 @@ merchant_config_currency="Currency" payment_method_type = "CartesBancaires" [[bambora.debit]] payment_method_type = "UnionPay" -[[bambora.wallet]] - payment_method_type = "apple_pay" -[[bambora.wallet]] - payment_method_type = "paypal" [bambora.connector_auth.BodyKey] api_key="Passcode" key1="Merchant Id" -[bambora.connector_webhook_details] -merchant_secret="Source verification key" - -[bambora.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="Domain" -initiative_context="Domain Name" -[bambora.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" [bankofamerica] [[bankofamerica.credit]] diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 7f4935d4887..450e14d1080 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -398,26 +398,9 @@ merchant_secret="Source verification key" payment_method_type = "CartesBancaires" [[bambora.debit]] payment_method_type = "UnionPay" -[[bambora.wallet]] - payment_method_type = "apple_pay" -[[bambora.wallet]] - payment_method_type = "paypal" [bambora.connector_auth.BodyKey] api_key="Passcode" key1="Merchant Id" -[bambora.connector_webhook_details] -merchant_secret="Source verification key" -[bambora.metadata.apple_pay.session_token_data] -certificate="Merchant Certificate (Base64 Encoded)" -certificate_keys="Merchant PrivateKey (Base64 Encoded)" -merchant_identifier="Apple Merchant Identifier" -display_name="Display Name" -initiative="Domain" -initiative_context="Domain Name" -[bambora.metadata.apple_pay.payment_request_data] -supported_networks=["visa","masterCard","amex","discover"] -merchant_capabilities=["supports3DS"] -label="apple" [bankofamerica] [[bankofamerica.credit]] diff --git a/crates/router/src/connector/bambora.rs b/crates/router/src/connector/bambora.rs index 7ff352416cd..684c5ddc1ce 100644 --- a/crates/router/src/connector/bambora.rs +++ b/crates/router/src/connector/bambora.rs @@ -10,10 +10,7 @@ use transformers as bambora; use super::utils::RefundsRequestData; use crate::{ configs::settings, - connector::{ - utils as connector_utils, - utils::{to_connector_meta, PaymentsAuthorizeRequestData, PaymentsSyncRequestData}, - }, + connector::{utils as connector_utils, utils::to_connector_meta}, core::{ errors::{self, CustomResult}, payments, @@ -36,6 +33,20 @@ use crate::{ #[derive(Debug, Clone)] pub struct Bambora; +impl api::Payment for Bambora {} +impl api::PaymentToken for Bambora {} +impl api::PaymentAuthorize for Bambora {} +impl api::PaymentVoid for Bambora {} +impl api::MandateSetup for Bambora {} +impl api::ConnectorAccessToken for Bambora {} +impl api::PaymentSync for Bambora {} +impl api::PaymentCapture for Bambora {} +impl api::PaymentSession for Bambora {} +impl api::Refund for Bambora {} +impl api::RefundExecute for Bambora {} +impl api::RefundSync for Bambora {} +impl api::PaymentsCompleteAuthorize for Bambora {} + impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Bambora where Self: ConnectorIntegration<Flow, Request, Response>, @@ -102,8 +113,9 @@ impl ConnectorCommon for Bambora { Ok(ErrorResponse { status_code: res.status_code, code: response.code.to_string(), - message: response.message, - reason: Some(serde_json::to_string(&response.details).unwrap_or_default()), + message: serde_json::to_string(&response.details) + .unwrap_or(crate::consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(response.message), attempt_status: None, connector_transaction_id: None, }) @@ -126,10 +138,6 @@ impl ConnectorValidation for Bambora { } } -impl api::Payment for Bambora {} - -impl api::PaymentToken for Bambora {} - impl ConnectorIntegration< api::PaymentMethodToken, @@ -140,7 +148,17 @@ impl // Not Implemented (R) } -impl api::MandateSetup for Bambora {} +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Bambora +{ +} + +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Bambora +{ + //TODO: implement sessions flow +} + impl ConnectorIntegration< api::SetupMandate, @@ -164,14 +182,12 @@ impl } } -impl api::PaymentVoid for Bambora {} - -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Bambora { fn get_headers( &self, - req: &types::PaymentsCancelRouterData, + req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) @@ -183,82 +199,68 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_url( &self, - req: &types::PaymentsCancelRouterData, + _req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - let connector_payment_id = req.request.connector_transaction_id.clone(); - Ok(format!( - "{}/v1/payments/{}{}", - self.base_url(connectors), - connector_payment_id, - "/void" - )) + Ok(format!("{}{}", self.base_url(connectors), "/v1/payments")) } fn get_request_body( &self, - req: &types::PaymentsCancelRouterData, + req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = bambora::BamboraRouterData::try_from(( &self.get_currency_unit(), - req.request - .currency - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "Currency", - })?, - req.request - .amount - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "Amount", - })?, + req.request.currency, + req.request.amount, req, ))?; - let connector_req = bambora::BamboraVoidRequest::try_from(connector_router_data)?; - + let connector_req = bambora::BamboraPaymentsRequest::try_from(connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, - req: &types::PaymentsCancelRouterData, + req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) - .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) .attach_default_headers() - .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) - .set_body(self.get_request_body(req, connectors)?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsCancelRouterData, + data: &types::PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: bambora::BamboraResponse = res .response - .parse_struct("bambora PaymentsResponse") + .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, - }, - bambora::PaymentFlow::Void, - )) - .change_context(errors::ConnectorError::ResponseHandlingFailed) + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) } fn get_error_response( @@ -270,14 +272,99 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR } } -impl api::ConnectorAccessToken for Bambora {} - -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Bambora +impl + ConnectorIntegration< + api::CompleteAuthorize, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + > for Bambora { + fn get_headers( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + 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::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let meta: bambora::BamboraMeta = to_connector_meta(req.request.connector_meta.clone())?; + Ok(format!( + "{}/v1/payments/{}{}", + self.base_url(connectors), + meta.three_d_session_data, + "/continue" + )) + } + + fn get_request_body( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = bambora::BamboraThreedsContinueRequest::try_from(&req.request)?; + + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCompleteAuthorizeType::get_url( + self, req, connectors, + )?) + .headers(types::PaymentsCompleteAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { + let response: bambora::BamboraPaymentsResponse = res + .response + .parse_struct("BamboraPaymentsResponse") + .change_context(errors::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, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } -impl api::PaymentSync for Bambora {} impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Bambora { @@ -304,10 +391,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; Ok(format!( - "{}{}{}", + "{}/v1/payments/{connector_payment_id}", self.base_url(connectors), - "/v1/payments/", - connector_payment_id )) } @@ -340,7 +425,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - let response: bambora::BamboraResponse = res + let response: bambora::BamboraPaymentsResponse = res .response .parse_struct("bambora PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -348,19 +433,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(( - types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }, - get_payment_flow(data.request.is_auto_capture()?), - )) + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } } -impl api::PaymentCapture for Bambora {} impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> for Bambora { @@ -382,11 +463,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( - "{}{}{}{}", + "{}/v1/payments/{}/completions", self.base_url(connectors), - "/v1/payments/", req.request.connector_transaction_id, - "/completions" )) } @@ -431,7 +510,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { - let response: bambora::BamboraResponse = res + let response: bambora::BamboraPaymentsResponse = res .response .parse_struct("Bambora PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -439,14 +518,11 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(( - types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }, - bambora::PaymentFlow::Capture, - )) + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } @@ -459,22 +535,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme } } -impl api::PaymentSession for Bambora {} - -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Bambora -{ - //TODO: implement sessions flow -} - -impl api::PaymentAuthorize for Bambora {} - -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Bambora { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, + req: &types::PaymentsCancelRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) @@ -486,72 +552,77 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, + req: &types::PaymentsCancelRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}{}", self.base_url(connectors), "/v1/payments")) + let connector_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}/v1/payments/{}/void", + self.base_url(connectors), + connector_payment_id, + )) } fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, + req: &types::PaymentsCancelRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = bambora::BamboraRouterData::try_from(( &self.get_currency_unit(), - req.request.currency, - req.request.amount, + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "Currency", + })?, + req.request + .amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "Amount", + })?, req, ))?; - let connector_req = bambora::BamboraPaymentsRequest::try_from(connector_router_data)?; + let connector_req = bambora::BamboraVoidRequest::try_from(connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, + req: &types::PaymentsCancelRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( - self, req, connectors, - )?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .set_body(self.get_request_body(req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &types::PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: bambora::BamboraResponse = res + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + let response: bambora::BamboraPaymentsResponse = res .response - .parse_struct("PaymentIntentResponse") + .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, - data: data.clone(), - http_code: res.status_code, - }, - get_payment_flow(data.request.is_auto_capture()?), - )) + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } @@ -564,9 +635,22 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } -impl api::Refund for Bambora {} -impl api::RefundExecute for Bambora {} -impl api::RefundSync for Bambora {} +impl services::ConnectorRedirectResponse for Bambora { + fn get_flow_type( + &self, + _query_params: &str, + _json_payload: Option<serde_json::Value>, + action: services::PaymentAction, + ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { + match action { + services::PaymentAction::PSync + | services::PaymentAction::CompleteAuthorize + | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => { + Ok(payments::CallConnectorAction::Trigger) + } + } + } +} impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Bambora @@ -590,11 +674,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( - "{}{}{}{}", + "{}/v1/payments/{}/returns", self.base_url(connectors), - "/v1/payments/", connector_payment_id, - "/returns" )) } @@ -684,9 +766,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse let _connector_payment_id = req.request.connector_transaction_id.clone(); let connector_refund_id = req.request.get_connector_refund_id()?; Ok(format!( - "{}{}{}", + "{}/v1/payments/{}", self.base_url(connectors), - "/v1/payments/", connector_refund_id )) } @@ -760,126 +841,3 @@ impl api::IncomingWebhook for Bambora { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } - -pub fn get_payment_flow(is_auto_capture: bool) -> bambora::PaymentFlow { - if is_auto_capture { - bambora::PaymentFlow::Capture - } else { - bambora::PaymentFlow::Authorize - } -} - -impl services::ConnectorRedirectResponse for Bambora { - fn get_flow_type( - &self, - _query_params: &str, - _json_payload: Option<serde_json::Value>, - action: services::PaymentAction, - ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { - match action { - services::PaymentAction::PSync - | services::PaymentAction::CompleteAuthorize - | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => { - Ok(payments::CallConnectorAction::Trigger) - } - } - } -} - -impl api::PaymentsCompleteAuthorize for Bambora {} - -impl - ConnectorIntegration< - api::CompleteAuthorize, - types::CompleteAuthorizeData, - types::PaymentsResponseData, - > for Bambora -{ - fn get_headers( - &self, - req: &types::PaymentsCompleteAuthorizeRouterData, - 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::PaymentsCompleteAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - let meta: bambora::BamboraMeta = to_connector_meta(req.request.connector_meta.clone())?; - Ok(format!( - "{}/v1/payments/{}{}", - self.base_url(connectors), - meta.three_d_session_data, - "/continue" - )) - } - - fn get_request_body( - &self, - req: &types::PaymentsCompleteAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = bambora::BamboraThreedsContinueRequest::try_from(&req.request)?; - - Ok(RequestContent::Json(Box::new(connector_req))) - } - - fn build_request( - &self, - req: &types::PaymentsCompleteAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsCompleteAuthorizeType::get_url( - self, req, connectors, - )?) - .headers(types::PaymentsCompleteAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( - self, req, connectors, - )?) - .build(); - Ok(Some(request)) - } - - 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)?; - event_builder.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, - }, - bambora::PaymentFlow::Capture, - )) - .change_context(errors::ConnectorError::ResponseHandlingFailed) - } - - 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/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index 77c91af709d..61ed8bd1ee4 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -7,7 +7,8 @@ use serde::{Deserialize, Deserializer, Serialize}; use crate::{ connector::utils::{ AddressDetailsData, BrowserInformationData, CardData as OtherCardData, - PaymentsAuthorizeRequestData, RouterData, + PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, + PaymentsSyncRequestData, RouterData, }, consts, core::errors, @@ -135,16 +136,24 @@ impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for Bambora ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { domain::PaymentMethodData::Card(req_card) => { - let three_ds = match item.router_data.auth_type { - enums::AuthenticationType::ThreeDs => Some(ThreeDSecure { - enabled: true, - browser: get_browser_info(item.router_data)?, - version: Some(2), - auth_required: Some(true), - }), - enums::AuthenticationType::NoThreeDs => None, + let (three_ds, customer_ip) = match item.router_data.auth_type { + enums::AuthenticationType::ThreeDs => ( + Some(ThreeDSecure { + enabled: true, + browser: get_browser_info(item.router_data)?, + version: Some(2), + auth_required: Some(true), + }), + Some( + item.router_data + .request + .get_browser_info()? + .get_ip_address()?, + ), + ), + enums::AuthenticationType::NoThreeDs => (None, None), }; - let bambora_card = BamboraCard { + let card = BamboraCard { name: item.router_data.get_billing_address()?.get_full_name()?, expiry_year: req_card.get_card_expiry_year_2_digit()?, number: req_card.card_number, @@ -153,19 +162,31 @@ impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for Bambora three_d_secure: three_ds, complete: item.router_data.request.is_auto_capture()?, }; - let browser_info = item.router_data.request.get_browser_info()?; + Ok(Self { order_number: item.router_data.connector_request_reference_id.clone(), amount: item.amount, payment_method: PaymentMethod::Card, - card: bambora_card, - customer_ip: browser_info - .ip_address - .map(|ip_address| Secret::new(format!("{ip_address}"))), + card, + customer_ip, term_url: item.router_data.request.complete_authorize_url.clone(), }) } - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + domain::PaymentMethodData::CardRedirect(_) + | domain::PaymentMethodData::Wallet(_) + | domain::PaymentMethodData::PayLater(_) + | domain::PaymentMethodData::BankRedirect(_) + | domain::PaymentMethodData::BankDebit(_) + | domain::PaymentMethodData::BankTransfer(_) + | domain::PaymentMethodData::Crypto(_) + | domain::PaymentMethodData::MandatePayment + | domain::PaymentMethodData::Reward + | domain::PaymentMethodData::Upi(_) + | domain::PaymentMethodData::Voucher(_) + | domain::PaymentMethodData::GiftCard(_) + | domain::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()) + } } } } @@ -200,87 +221,6 @@ impl TryFrom<&types::ConnectorAuthType> for BamboraAuthType { } } -pub enum PaymentFlow { - Authorize, - Capture, - Void, -} - -// PaymentsResponse -impl<F, T> - TryFrom<( - types::ResponseRouterData<F, BamboraResponse, T, types::PaymentsResponseData>, - PaymentFlow, - )> for types::RouterData<F, T, types::PaymentsResponseData> -{ - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - data: ( - types::ResponseRouterData<F, BamboraResponse, T, types::PaymentsResponseData>, - PaymentFlow, - ), - ) -> Result<Self, Self::Error> { - let flow = data.1; - let item = data.0; - match item.response { - BamboraResponse::NormalTransaction(pg_response) => Ok(Self { - status: match pg_response.approved.as_str() { - "0" => match flow { - PaymentFlow::Authorize => enums::AttemptStatus::AuthorizationFailed, - PaymentFlow::Capture => enums::AttemptStatus::Failure, - PaymentFlow::Void => enums::AttemptStatus::VoidFailed, - }, - "1" => match flow { - PaymentFlow::Authorize => enums::AttemptStatus::Authorized, - PaymentFlow::Capture => enums::AttemptStatus::Charged, - PaymentFlow::Void => enums::AttemptStatus::Voided, - }, - &_ => Err(errors::ConnectorError::ResponseDeserializationFailed)?, - }, - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - pg_response.id.to_string(), - ), - redirection_data: None, - mandate_reference: None, - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: Some(pg_response.order_number.to_string()), - incremental_authorization_allowed: None, - }), - ..item.data - }), - - BamboraResponse::ThreeDsResponse(response) => { - let value = url::form_urlencoded::parse(response.contents.as_bytes()) - .map(|(key, val)| [key, val].concat()) - .collect(); - let redirection_data = Some(services::RedirectForm::Html { html_data: value }); - Ok(Self { - status: enums::AttemptStatus::AuthenticationPending, - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::NoResponseId, - redirection_data, - mandate_reference: None, - connector_metadata: Some( - serde_json::to_value(BamboraMeta { - three_d_session_data: response.three_d_session_data.expose(), - }) - .change_context(errors::ConnectorError::ResponseHandlingFailed)?, - ), - network_txn_id: None, - connector_response_reference_id: Some( - item.data.connector_request_reference_id.to_string(), - ), - incremental_authorization_allowed: None, - }), - ..item.data - }) - } - } - } -} - fn str_or_i32<'de, D>(deserializer: D) -> Result<String, D::Error> where D: Deserializer<'de>, @@ -444,7 +384,7 @@ pub enum PaymentMethod { // Capture #[derive(Default, Debug, Clone, Serialize, PartialEq)] pub struct BamboraPaymentsCaptureRequest { - amount: Option<f64>, + amount: f64, payment_method: PaymentMethod, } @@ -456,12 +396,269 @@ impl TryFrom<BamboraRouterData<&types::PaymentsCaptureRouterData>> item: BamboraRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { Ok(Self { - amount: Some(item.amount), + amount: item.amount, payment_method: PaymentMethod::Card, }) } } +impl<F> + TryFrom< + types::ResponseRouterData< + F, + BamboraResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BamboraResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + BamboraResponse::NormalTransaction(pg_response) => Ok(Self { + status: if pg_response.approved.as_str() == "1" { + match item.data.request.is_auto_capture()? { + true => enums::AttemptStatus::Charged, + false => enums::AttemptStatus::Authorized, + } + } else { + match item.data.request.is_auto_capture()? { + true => enums::AttemptStatus::Failure, + false => enums::AttemptStatus::AuthorizationFailed, + } + }, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + pg_response.id.to_string(), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(pg_response.order_number.to_string()), + incremental_authorization_allowed: None, + }), + ..item.data + }), + + BamboraResponse::ThreeDsResponse(response) => { + let value = url::form_urlencoded::parse(response.contents.as_bytes()) + .map(|(key, val)| [key, val].concat()) + .collect(); + let redirection_data = Some(services::RedirectForm::Html { html_data: value }); + Ok(Self { + status: enums::AttemptStatus::AuthenticationPending, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data, + mandate_reference: None, + connector_metadata: Some( + serde_json::to_value(BamboraMeta { + three_d_session_data: response.three_d_session_data.expose(), + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed)?, + ), + network_txn_id: None, + connector_response_reference_id: Some( + item.data.connector_request_reference_id.to_string(), + ), + incremental_authorization_allowed: None, + }), + ..item.data + }) + } + } + } +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + BamboraPaymentsResponse, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BamboraPaymentsResponse, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: if item.response.approved.as_str() == "1" { + match item.data.request.is_auto_capture()? { + true => enums::AttemptStatus::Charged, + false => enums::AttemptStatus::Authorized, + } + } else { + match item.data.request.is_auto_capture()? { + true => enums::AttemptStatus::Failure, + false => enums::AttemptStatus::AuthorizationFailed, + } + }, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.id.to_string(), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(item.response.order_number.to_string()), + incremental_authorization_allowed: None, + }), + ..item.data + }) + } +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + BamboraPaymentsResponse, + types::PaymentsSyncData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BamboraPaymentsResponse, + types::PaymentsSyncData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: match item.data.request.is_auto_capture()? { + true => { + if item.response.approved.as_str() == "1" { + enums::AttemptStatus::Charged + } else { + enums::AttemptStatus::Failure + } + } + false => { + if item.response.approved.as_str() == "1" { + enums::AttemptStatus::Authorized + } else { + enums::AttemptStatus::AuthorizationFailed + } + } + }, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.id.to_string(), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(item.response.order_number.to_string()), + incremental_authorization_allowed: None, + }), + ..item.data + }) + } +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + BamboraPaymentsResponse, + types::PaymentsCaptureData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BamboraPaymentsResponse, + types::PaymentsCaptureData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: if item.response.approved.as_str() == "1" { + enums::AttemptStatus::Charged + } else { + enums::AttemptStatus::Failure + }, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.id.to_string(), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(item.response.order_number.to_string()), + incremental_authorization_allowed: None, + }), + ..item.data + }) + } +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + BamboraPaymentsResponse, + types::PaymentsCancelData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BamboraPaymentsResponse, + types::PaymentsCancelData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: if item.response.approved.as_str() == "1" { + enums::AttemptStatus::Voided + } else { + enums::AttemptStatus::VoidFailed + }, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.id.to_string(), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(item.response.order_number.to_string()), + incremental_authorization_allowed: None, + }), + ..item.data + }) + } +} + // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] @@ -537,10 +734,10 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> fn try_from( item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, ) -> Result<Self, Self::Error> { - let refund_status = match item.response.approved.as_str() { - "0" => enums::RefundStatus::Failure, - "1" => enums::RefundStatus::Success, - &_ => Err(errors::ConnectorError::ResponseDeserializationFailed)?, + let refund_status = if item.response.approved.as_str() == "1" { + enums::RefundStatus::Success + } else { + enums::RefundStatus::Failure }; Ok(Self { response: Ok(types::RefundsResponseData { @@ -559,10 +756,10 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> fn try_from( item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, ) -> Result<Self, Self::Error> { - let refund_status = match item.response.approved.as_str() { - "0" => enums::RefundStatus::Failure, - "1" => enums::RefundStatus::Success, - &_ => Err(errors::ConnectorError::ResponseDeserializationFailed)?, + let refund_status = if item.response.approved.as_str() == "1" { + enums::RefundStatus::Success + } else { + enums::RefundStatus::Failure }; Ok(Self { response: Ok(types::RefundsResponseData {
2024-05-09T11:01:36Z
## Description <!-- Describe your changes in detail --> Following code improvements are done for connector Bambora: - Optional fields that are being passed for payments request are removed - 2XX and 4XX Error response are now handled properly - Separate try_from are now used for all the flows - Unwanted configs are removed - Default case handling is removed ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables Following are the paths where you can find config files which have been updated: 1. `crates/connector_configs/toml/development.toml` 2. `crates/connector_configs/toml/sandbox.toml` 3. `crates/connector_configs/toml/production.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). --> https://github.com/juspay/hyperswitch/issues/4605 ## 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 payment flows need to be tested(except void) for cards(Non-3DS) via Bambora. 1. Payments (Automatic): Request - ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 2000, "currency": "USD", "confirm": true, "customer_id": "assdre1v", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4030000010001234", "card_exp_month": "10", "card_exp_year": "2024", "card_holder_name": "Sundari KK", "card_cvc": "123" } } }' ``` Response - ``` { "payment_id": "pay_WLq2W1Lf6nDlkSVsTfXH", "merchant_id": "merchant_1714730521", "status": "succeeded", "amount": 2000, "net_amount": 2000, "amount_capturable": 0, "amount_received": 2000, "connector": "bambora", "client_secret": "pay_WLq2W1Lf6nDlkSVsTfXH_secret_AGkc7on7LPYnS4tzNDrh", "created": "2024-05-09T11:29:26.243Z", "currency": "USD", "customer_id": "assdre1v", "customer": { "id": "assdre1v", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1234", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "403000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "2024", "card_holder_name": "Sundari KK", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "assdre1v", "created_at": 1715254166, "expires": 1715257766, "secret": "epk_1b0a796b1c1d4f2ebac92c20ba7f2381" }, "manual_retry_allowed": false, "connector_transaction_id": "10004856", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_WLq2W1Lf6nDlkSVsTfXH_1", "payment_link": null, "profile_id": "pro_l8ERwD92l71RbPpGZZz9", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_ybl21De1o5q31x82RpEj", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-09T11:44:26.243Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-09T11:29:28.588Z" } ``` 2. Payments (Manual): Request - ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 2000, "currency": "USD", "confirm": true, "customer_id": "assdre1v", "capture_method": "manual", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4030000010001234", "card_exp_month": "10", "card_exp_year": "2024", "card_holder_name": "Sundari KK", "card_cvc": "123" } } }' ``` Response - ``` { "payment_id": "pay_xHfLlrcSjSKeOPaw1GGz", "merchant_id": "merchant_1714730521", "status": "requires_capture", "amount": 2000, "net_amount": 2000, "amount_capturable": 2000, "amount_received": null, "connector": "bambora", "client_secret": "pay_xHfLlrcSjSKeOPaw1GGz_secret_wTB68iFSUs9LuEiSJy6O", "created": "2024-05-09T11:29:40.405Z", "currency": "USD", "customer_id": "assdre1v", "customer": { "id": "assdre1v", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "1234", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "403000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "2024", "card_holder_name": "Sundari KK", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "assdre1v", "created_at": 1715254180, "expires": 1715257780, "secret": "epk_28013d1f51344818865586555d178f34" }, "manual_retry_allowed": false, "connector_transaction_id": "10004857", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_xHfLlrcSjSKeOPaw1GGz_1", "payment_link": null, "profile_id": "pro_l8ERwD92l71RbPpGZZz9", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_ybl21De1o5q31x82RpEj", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-09T11:44:40.405Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-09T11:29:42.247Z" } ``` 3. Payments (Capture): Request - ``` curl --location 'http://localhost:8080/payments/pay_Qjbk8kB5wduiuuBOvI2Y/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount_to_capture": 2000, "statement_descriptor_name": "Joseph", "statement_descriptor_suffix": "JS" }' ``` Response - ``` { "payment_id": "pay_xHfLlrcSjSKeOPaw1GGz", "merchant_id": "merchant_1714730521", "status": "succeeded", "amount": 2000, "net_amount": 2000, "amount_capturable": 0, "amount_received": 2000, "connector": "bambora", "client_secret": "pay_xHfLlrcSjSKeOPaw1GGz_secret_wTB68iFSUs9LuEiSJy6O", "created": "2024-05-09T11:29:40.405Z", "currency": "USD", "customer_id": "assdre1v", "customer": { "id": "assdre1v", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "1234", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "403000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "2024", "card_holder_name": "Sundari KK", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "10004858", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_xHfLlrcSjSKeOPaw1GGz_1", "payment_link": null, "profile_id": "pro_l8ERwD92l71RbPpGZZz9", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_ybl21De1o5q31x82RpEj", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-09T11:44:40.405Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-09T11:30:15.379Z" } ``` 4. Refunds: Request - ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 100, "payment_id": "pay_xHfLlrcSjSKeOPaw1GGz", "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response: ``` { "refund_id": "ref_i2J7zKX1kzvU00IPSW2m", "payment_id": "pay_xHfLlrcSjSKeOPaw1GGz", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "created_at": "2024-05-09T11:33:37.772Z", "updated_at": "2024-05-09T11:33:37.772Z", "connector": "bambora", "profile_id": "pro_l8ERwD92l71RbPpGZZz9", "merchant_connector_id": "mca_ybl21De1o5q31x82RpEj" } ```
f386f423c0e5fac55a24756d7ee7a3ce1c20fb13
All the payment flows need to be tested(except void) for cards(Non-3DS) via Bambora. 1. Payments (Automatic): Request - ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 2000, "currency": "USD", "confirm": true, "customer_id": "assdre1v", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4030000010001234", "card_exp_month": "10", "card_exp_year": "2024", "card_holder_name": "Sundari KK", "card_cvc": "123" } } }' ``` Response - ``` { "payment_id": "pay_WLq2W1Lf6nDlkSVsTfXH", "merchant_id": "merchant_1714730521", "status": "succeeded", "amount": 2000, "net_amount": 2000, "amount_capturable": 0, "amount_received": 2000, "connector": "bambora", "client_secret": "pay_WLq2W1Lf6nDlkSVsTfXH_secret_AGkc7on7LPYnS4tzNDrh", "created": "2024-05-09T11:29:26.243Z", "currency": "USD", "customer_id": "assdre1v", "customer": { "id": "assdre1v", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1234", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "403000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "2024", "card_holder_name": "Sundari KK", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "assdre1v", "created_at": 1715254166, "expires": 1715257766, "secret": "epk_1b0a796b1c1d4f2ebac92c20ba7f2381" }, "manual_retry_allowed": false, "connector_transaction_id": "10004856", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_WLq2W1Lf6nDlkSVsTfXH_1", "payment_link": null, "profile_id": "pro_l8ERwD92l71RbPpGZZz9", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_ybl21De1o5q31x82RpEj", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-09T11:44:26.243Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-09T11:29:28.588Z" } ``` 2. Payments (Manual): Request - ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 2000, "currency": "USD", "confirm": true, "customer_id": "assdre1v", "capture_method": "manual", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4030000010001234", "card_exp_month": "10", "card_exp_year": "2024", "card_holder_name": "Sundari KK", "card_cvc": "123" } } }' ``` Response - ``` { "payment_id": "pay_xHfLlrcSjSKeOPaw1GGz", "merchant_id": "merchant_1714730521", "status": "requires_capture", "amount": 2000, "net_amount": 2000, "amount_capturable": 2000, "amount_received": null, "connector": "bambora", "client_secret": "pay_xHfLlrcSjSKeOPaw1GGz_secret_wTB68iFSUs9LuEiSJy6O", "created": "2024-05-09T11:29:40.405Z", "currency": "USD", "customer_id": "assdre1v", "customer": { "id": "assdre1v", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "1234", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "403000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "2024", "card_holder_name": "Sundari KK", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "assdre1v", "created_at": 1715254180, "expires": 1715257780, "secret": "epk_28013d1f51344818865586555d178f34" }, "manual_retry_allowed": false, "connector_transaction_id": "10004857", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_xHfLlrcSjSKeOPaw1GGz_1", "payment_link": null, "profile_id": "pro_l8ERwD92l71RbPpGZZz9", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_ybl21De1o5q31x82RpEj", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-09T11:44:40.405Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-09T11:29:42.247Z" } ``` 3. Payments (Capture): Request - ``` curl --location 'http://localhost:8080/payments/pay_Qjbk8kB5wduiuuBOvI2Y/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount_to_capture": 2000, "statement_descriptor_name": "Joseph", "statement_descriptor_suffix": "JS" }' ``` Response - ``` { "payment_id": "pay_xHfLlrcSjSKeOPaw1GGz", "merchant_id": "merchant_1714730521", "status": "succeeded", "amount": 2000, "net_amount": 2000, "amount_capturable": 0, "amount_received": 2000, "connector": "bambora", "client_secret": "pay_xHfLlrcSjSKeOPaw1GGz_secret_wTB68iFSUs9LuEiSJy6O", "created": "2024-05-09T11:29:40.405Z", "currency": "USD", "customer_id": "assdre1v", "customer": { "id": "assdre1v", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "1234", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "403000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "2024", "card_holder_name": "Sundari KK", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "10004858", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_xHfLlrcSjSKeOPaw1GGz_1", "payment_link": null, "profile_id": "pro_l8ERwD92l71RbPpGZZz9", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_ybl21De1o5q31x82RpEj", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-05-09T11:44:40.405Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-05-09T11:30:15.379Z" } ``` 4. Refunds: Request - ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 100, "payment_id": "pay_xHfLlrcSjSKeOPaw1GGz", "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response: ``` { "refund_id": "ref_i2J7zKX1kzvU00IPSW2m", "payment_id": "pay_xHfLlrcSjSKeOPaw1GGz", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "created_at": "2024-05-09T11:33:37.772Z", "updated_at": "2024-05-09T11:33:37.772Z", "connector": "bambora", "profile_id": "pro_l8ERwD92l71RbPpGZZz9", "merchant_connector_id": "mca_ybl21De1o5q31x82RpEj" } ```
[ "crates/connector_configs/toml/development.toml", "crates/connector_configs/toml/production.toml", "crates/connector_configs/toml/sandbox.toml", "crates/router/src/connector/bambora.rs", "crates/router/src/connector/bambora/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4602
Bug: Pass `required_billing_contact_fields` field in apple pay session call based on dynamic fields This change is required as part of the one click checkout where in which we expect apple pay to collect the billing details from the customer and pass it in the confirm call with the `payment_data`. In order for apple pay to collect the billing details from customer we need to pass``"requiredBillingContactFields": ["postalAddress"]`` in the `/session` call. Hence we need to have a validation in the backend that checks for the dynamic fields for a specific connector and pass the `required_billing_contact_fields` to sdk.
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 884e0fd82f8..37d17dcff17 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -396,13 +396,11 @@ pub struct UnresolvedResponseReason { Clone, Debug, Eq, - PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, - Hash, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] @@ -430,6 +428,89 @@ pub enum FieldType { DropDown { options: Vec<String> }, } +impl FieldType { + pub fn get_billing_variants() -> Vec<Self> { + vec![ + Self::UserBillingName, + Self::UserAddressLine1, + Self::UserAddressLine2, + Self::UserAddressCity, + Self::UserAddressPincode, + Self::UserAddressState, + Self::UserAddressCountry { options: vec![] }, + ] + } +} + +/// This implementatiobn is to ignore the inner value of UserAddressCountry enum while comparing +impl PartialEq for FieldType { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Self::UserCardNumber, Self::UserCardNumber) => true, + (Self::UserCardExpiryMonth, Self::UserCardExpiryMonth) => true, + (Self::UserCardExpiryYear, Self::UserCardExpiryYear) => true, + (Self::UserCardCvc, Self::UserCardCvc) => true, + (Self::UserFullName, Self::UserFullName) => true, + (Self::UserEmailAddress, Self::UserEmailAddress) => true, + (Self::UserPhoneNumber, Self::UserPhoneNumber) => true, + (Self::UserCountryCode, Self::UserCountryCode) => true, + ( + Self::UserCountry { + options: options_self, + }, + Self::UserCountry { + options: options_other, + }, + ) => options_self.eq(options_other), + ( + Self::UserCurrency { + options: options_self, + }, + Self::UserCurrency { + options: options_other, + }, + ) => options_self.eq(options_other), + (Self::UserBillingName, Self::UserBillingName) => true, + (Self::UserAddressLine1, Self::UserAddressLine1) => true, + (Self::UserAddressLine2, Self::UserAddressLine2) => true, + (Self::UserAddressCity, Self::UserAddressCity) => true, + (Self::UserAddressPincode, Self::UserAddressPincode) => true, + (Self::UserAddressState, Self::UserAddressState) => true, + (Self::UserAddressCountry { .. }, Self::UserAddressCountry { .. }) => true, + (Self::UserBlikCode, Self::UserBlikCode) => true, + (Self::UserBank, Self::UserBank) => true, + (Self::Text, Self::Text) => true, + ( + Self::DropDown { + options: options_self, + }, + Self::DropDown { + options: options_other, + }, + ) => options_self.eq(options_other), + _unused => false, + } + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_partialeq_for_field_type() { + let user_address_country_is_us = FieldType::UserAddressCountry { + options: vec!["US".to_string()], + }; + + let user_address_country_is_all = FieldType::UserAddressCountry { + options: vec!["ALL".to_string()], + }; + + assert!(user_address_country_is_us.eq(&user_address_country_is_all)) + } +} + #[derive( Debug, serde::Deserialize, diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 96136d69370..b7a58b3b5b6 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -537,7 +537,7 @@ impl From<Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>> for SurchargePercen } } /// Required fields info used while listing the payment_method_data -#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq, ToSchema, Hash)] +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq, ToSchema)] pub struct RequiredFieldInfo { /// Required field for a payment_method through a payment_method_type pub required_field: String, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index f1ce53580aa..ad5c02f6baa 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -3867,6 +3867,24 @@ pub struct GpayAllowedMethodsParameters { pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, + /// Is billing address required + pub billing_address_required: Option<bool>, + /// Billing address parameters + pub billing_address_parameters: Option<GpayBillingAddressParameters>, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct GpayBillingAddressParameters { + /// Is billing phone number required + pub phone_number_required: bool, + /// Billing address format + pub format: GpayBillingAddressFormat, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] +pub enum GpayBillingAddressFormat { + FULL, + MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] @@ -4213,6 +4231,8 @@ pub struct ApplePayPaymentRequest { /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, + /// The required billing contact fields for connector + pub required_billing_contact_fields: Option<Vec<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs index f89c2e5921b..01332c9d29e 100644 --- a/crates/connector_configs/src/transformer.rs +++ b/crates/connector_configs/src/transformer.rs @@ -291,6 +291,8 @@ impl DashboardRequestPayload { "MASTERCARD".to_string(), "VISA".to_string(), ], + billing_address_required: None, + billing_address_parameters: None, }; let allowed_payment_methods = payments::GpayAllowedPaymentMethods { payment_method_type: String::from("CARD"), diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 7abbc3b77e4..66e951af7b2 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -388,6 +388,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::GooglePayRedirectData, api_models::payments::GooglePayThirdPartySdk, api_models::payments::GooglePaySessionResponse, + api_models::payments::GpayBillingAddressParameters, + api_models::payments::GpayBillingAddressFormat, api_models::payments::SepaBankTransferInstructions, api_models::payments::BacsBankTransferInstructions, api_models::payments::RedirectResponse, diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 0630fef2748..251a928c09e 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -538,6 +538,7 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<BluesnapWalletTokenRespons merchant_capabilities: Some(payment_request_data.merchant_capabilities), supported_networks: Some(payment_request_data.supported_networks), merchant_identifier: Some(session_token_data.merchant_identifier), + required_billing_contact_fields: None, }), connector: "bluesnap".to_string(), delayed_session_token: false, diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index 0b3f4fb48ce..686858008b6 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -550,6 +550,7 @@ impl<F> merchant_capabilities: None, supported_networks: None, merchant_identifier: None, + required_billing_contact_fields: None, }, ), connector: "payme".to_string(), diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 5a318e5e440..7f84e301916 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -1223,6 +1223,7 @@ pub fn get_apple_pay_session<F, T>( ), total: apple_pay_init_result.total.into(), merchant_identifier: None, + required_billing_contact_fields: None, }), connector: "trustpay".to_string(), delayed_session_token: true, @@ -1326,6 +1327,8 @@ impl From<GpayAllowedMethodsParameters> for api_models::payments::GpayAllowedMet Self { allowed_auth_methods: value.allowed_auth_methods, allowed_card_networks: value.allowed_card_networks, + billing_address_required: None, + billing_address_parameters: None, } } } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 66e0f144807..c83c73f7624 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -11,9 +11,13 @@ use crate::{ payments::{self, access_token, helpers, transformers, PaymentData}, }, headers, logger, - routes::{self, metrics}, + routes::{self, app::settings, metrics}, services, - types::{self, api, domain}, + types::{ + self, + api::{self, enums}, + domain, + }, utils::OptionExt, }; @@ -78,6 +82,39 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio } } +/// This function checks if for a given connector, payment_method and payment_method_type, +/// the list of required_field_type is present in dynamic fields +fn is_dynamic_fields_required( + required_fields: &settings::RequiredFields, + payment_method: enums::PaymentMethod, + payment_method_type: enums::PaymentMethodType, + connector: &types::Connector, + required_field_type: Vec<enums::FieldType>, +) -> bool { + required_fields + .0 + .get(&payment_method) + .and_then(|pm_type| pm_type.0.get(&payment_method_type)) + .and_then(|required_fields_for_connector| { + required_fields_for_connector.fields.get(connector) + }) + .map(|required_fields_final| { + required_fields_final + .non_mandate + .iter() + .any(|(_, val)| required_field_type.contains(&val.field_type)) + || required_fields_final + .mandate + .iter() + .any(|(_, val)| required_field_type.contains(&val.field_type)) + || required_fields_final + .common + .iter() + .any(|(_, val)| required_field_type.contains(&val.field_type)) + }) + .unwrap_or(false) +} + fn get_applepay_metadata( connector_metadata: Option<common_utils::pii::SecretSerdeValue>, ) -> RouterResult<payment_types::ApplepaySessionTokenMetadata> { @@ -247,6 +284,20 @@ async fn create_applepay_session_token( router_data.request.to_owned(), )?; + let billing_variants = enums::FieldType::get_billing_variants(); + + let required_billing_contact_fields = if is_dynamic_fields_required( + &state.conf.required_fields, + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::ApplePay, + &connector.connector_name, + billing_variants, + ) { + Some(vec!["postalAddress".to_string()]) + } else { + None + }; + // Get apple pay payment request let applepay_payment_request = get_apple_pay_payment_request( amount_info, @@ -254,6 +305,7 @@ async fn create_applepay_session_token( router_data.request.to_owned(), apple_pay_session_request.merchant_identifier.as_str(), merchant_business_country, + required_billing_contact_fields, )?; let applepay_session_request = build_apple_pay_session_request( @@ -354,6 +406,7 @@ fn get_apple_pay_payment_request( session_data: types::PaymentsSessionData, merchant_identifier: &str, merchant_business_country: Option<api_models::enums::CountryAlpha2>, + required_billing_contact_fields: Option<Vec<String>>, ) -> RouterResult<payment_types::ApplePayPaymentRequest> { let applepay_payment_request = payment_types::ApplePayPaymentRequest { country_code: merchant_business_country.or(session_data.country).ok_or( @@ -366,6 +419,7 @@ fn get_apple_pay_payment_request( merchant_capabilities: Some(payment_request_data.merchant_capabilities), supported_networks: Some(payment_request_data.supported_networks), merchant_identifier: Some(merchant_identifier.to_string()), + required_billing_contact_fields, }; Ok(applepay_payment_request) } @@ -443,6 +497,38 @@ fn create_gpay_session_token( expected_format: "gpay_metadata_format".to_string(), })?; + let billing_variants = enums::FieldType::get_billing_variants(); + + let is_billing_details_required = is_dynamic_fields_required( + &state.conf.required_fields, + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::GooglePay, + &connector.connector_name, + billing_variants, + ); + + let billing_address_parameters = + is_billing_details_required.then_some(payment_types::GpayBillingAddressParameters { + phone_number_required: is_billing_details_required, + format: payment_types::GpayBillingAddressFormat::FULL, + }); + + let gpay_allowed_payment_methods = gpay_data + .data + .allowed_payment_methods + .into_iter() + .map( + |allowed_payment_methods| payment_types::GpayAllowedPaymentMethods { + parameters: payment_types::GpayAllowedMethodsParameters { + billing_address_required: Some(is_billing_details_required), + billing_address_parameters: billing_address_parameters.clone(), + ..allowed_payment_methods.parameters + }, + ..allowed_payment_methods + }, + ) + .collect(); + let session_data = router_data.request.clone(); let transaction_info = payment_types::GpayTransactionInfo { country_code: session_data.country.unwrap_or_default(), @@ -466,7 +552,7 @@ fn create_gpay_session_token( payment_types::GpaySessionTokenResponse::GooglePaySession( payment_types::GooglePaySessionResponse { merchant_info: gpay_data.data.merchant_info, - allowed_payment_methods: gpay_data.data.allowed_payment_methods, + allowed_payment_methods: gpay_allowed_payment_methods, transaction_info, connector: connector.connector_name.to_string(), sdk_next_action: payment_types::SdkNextAction { diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 259d1669523..63f102268c1 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4982,6 +4982,14 @@ "merchant_identifier": { "type": "string", "nullable": true + }, + "required_billing_contact_fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The required billing contact fields for connector", + "nullable": true } } }, @@ -9420,6 +9428,19 @@ "type": "string" }, "description": "The list of allowed card networks (ex: AMEX,JCB etc)" + }, + "billing_address_required": { + "type": "boolean", + "description": "Is billing address required", + "nullable": true + }, + "billing_address_parameters": { + "allOf": [ + { + "$ref": "#/components/schemas/GpayBillingAddressParameters" + } + ], + "nullable": true } } }, @@ -9443,6 +9464,29 @@ } } }, + "GpayBillingAddressFormat": { + "type": "string", + "enum": [ + "FULL", + "MIN" + ] + }, + "GpayBillingAddressParameters": { + "type": "object", + "required": [ + "phone_number_required", + "format" + ], + "properties": { + "phone_number_required": { + "type": "boolean", + "description": "Is billing phone number required" + }, + "format": { + "$ref": "#/components/schemas/GpayBillingAddressFormat" + } + } + }, "GpayMerchantInfo": { "type": "object", "required": [
2024-05-09T07:48:31Z
## Description <!-- Describe your changes in detail --> This change is required as part of the one click checkout where in which we expect apple pay to collect the billing details from the customer and pass it in the confirm call with the `payment_data`. In order for apple pay to collect the billing details from customer we need to pass``"requiredBillingContactFields": ["postalAddress"]`` in the `/session` call. Hence we need to have a validation in the backend that checks for the dynamic fields for a specific connector and pass the `required_billing_contact_fields` to sdk. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a MCA for stripe -> Apple pay payment create with confirm false ``` { "amount": 650, "currency": "USD", "confirm": false, "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", "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":"eyJkYXRhIjoiQ1ZoTGd5RGU3TzZjdFlhWHFiVWFONFZvRjBCQjhTbDZsenlXYUdCKzhKcXlic2hYVGxoNEFEcTZYb0t6ZWVSVGwvcUp6NDIvUFMwcmMxMCtqSyt5Z1F5NnlkT25EcnVDeVpkaVU4SWFGOEtOS2hJMFFKOU9JTk9aWFlYR0VzZEczNXlVNzcrQ0k1dk5lUjJiK1gyUXZTVTMzSjlOczJuTFRXZHpwb1VUSHJKU1RiSmFmTTlxYjlZOHZuZS9vZUdHQkV1ZU9DQWQxcFhjRE54SEl2dlc5Z0x3WXRPVldKZUEvUnh5MEdsb0VISng3VEhqUEVQUGJwMkVVZjRMQXZQOGlJSEpmUjM0THdEUVBIdmNSeW9nalRJSzJqOXZjUGRqS2xBSG1LUm5wZlhvWkY4VE16ZUJ6eWhGb0dKY3ZRa3JMc216OEcxTXowZGxlV2VmU2V0TkYxT1NMaldCdExrUXpvWG5xdU1ZeExMenU2SkxPZ1E5ejN1OStFNGQ2NHRZS1NYYlZBWGRKNXRMNTdvbSIsInNpZ25hdHVyZSI6Ik1JQUdDU3FHU0liM0RRRUhBcUNBTUlBQ0FRRXhEVEFMQmdsZ2hrZ0JaUU1FQWdFd2dBWUpLb1pJaHZjTkFRY0JBQUNnZ0RDQ0ErTXdnZ09Jb0FNQ0FRSUNDRXd3UVVsUm5WUTJNQW9HQ0NxR1NNNDlCQU1DTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekFlRncweE9UQTFNVGd3TVRNeU5UZGFGdzB5TkRBMU1UWXdNVE15TlRkYU1GOHhKVEFqQmdOVkJBTU1IR1ZqWXkxemJYQXRZbkp2YTJWeUxYTnBaMjVmVlVNMExWQlNUMFF4RkRBU0JnTlZCQXNNQzJsUFV5QlRlWE4wWlcxek1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpCWk1CTUdCeXFHU000OUFnRUdDQ3FHU000OUF3RUhBMElBQk1JVmQrM3Ixc2V5SVk5bzNYQ1FvU0dOeDdDOWJ5d29QWVJnbGRsSzlLVkJHNE5DRHRnUjgwQitnek1mSEZURDkrc3lJTmE2MWRUdjlKS0ppVDU4RHhPamdnSVJNSUlDRFRBTUJnTlZIUk1CQWY4RUFqQUFNQjhHQTFVZEl3UVlNQmFBRkNQeVNjUlBrK1R2SitiRTlpaHNQNks3L1M1TE1FVUdDQ3NHQVFVRkJ3RUJCRGt3TnpBMUJnZ3JCZ0VGQlFjd0FZWXBhSFIwY0RvdkwyOWpjM0F1WVhCd2JHVXVZMjl0TDI5amMzQXdOQzFoY0hCc1pXRnBZMkV6TURJd2dnRWRCZ05WSFNBRWdnRVVNSUlCRURDQ0FRd0dDU3FHU0liM1kyUUZBVENCL2pDQnd3WUlLd1lCQlFVSEFnSXdnYllNZ2JOU1pXeHBZVzVqWlNCdmJpQjBhR2x6SUdObGNuUnBabWxqWVhSbElHSjVJR0Z1ZVNCd1lYSjBlU0JoYzNOMWJXVnpJR0ZqWTJWd2RHRnVZMlVnYjJZZ2RHaGxJSFJvWlc0Z1lYQndiR2xqWVdKc1pTQnpkR0Z1WkdGeVpDQjBaWEp0Y3lCaGJtUWdZMjl1WkdsMGFXOXVjeUJ2WmlCMWMyVXNJR05sY25ScFptbGpZWFJsSUhCdmJHbGplU0JoYm1RZ1kyVnlkR2xtYVdOaGRHbHZiaUJ3Y21GamRHbGpaU0J6ZEdGMFpXMWxiblJ6TGpBMkJnZ3JCZ0VGQlFjQ0FSWXFhSFIwY0RvdkwzZDNkeTVoY0hCc1pTNWpiMjB2WTJWeWRHbG1hV05oZEdWaGRYUm9iM0pwZEhrdk1EUUdBMVVkSHdRdE1Dc3dLYUFub0NXR0kyaDBkSEE2THk5amNtd3VZWEJ3YkdVdVkyOXRMMkZ3Y0d4bFlXbGpZVE11WTNKc01CMEdBMVVkRGdRV0JCU1VWOXR2MVhTQmhvbUpkaTkrVjRVSDU1dFlKREFPQmdOVkhROEJBZjhFQkFNQ0I0QXdEd1lKS29aSWh2ZGpaQVlkQkFJRkFEQUtCZ2dxaGtqT1BRUURBZ05KQURCR0FpRUF2Z2xYSCtjZUhuTmJWZVd2ckxUSEwrdEVYekFZVWlMSEpSQUN0aDY5YjFVQ0lRRFJpelVLWGRiZGJyRjBZRFd4SHJMT2g4K2o1cTlzdllPQWlRM0lMTjJxWXpDQ0F1NHdnZ0oxb0FNQ0FRSUNDRWx0TDc4Nm1OcVhNQW9HQ0NxR1NNNDlCQU1DTUdjeEd6QVpCZ05WQkFNTUVrRndjR3hsSUZKdmIzUWdRMEVnTFNCSE16RW1NQ1FHQTFVRUN3d2RRWEJ3YkdVZ1EyVnlkR2xtYVdOaGRHbHZiaUJCZFhSb2IzSnBkSGt4RXpBUkJnTlZCQW9NQ2tGd2NHeGxJRWx1WXk0eEN6QUpCZ05WQkFZVEFsVlRNQjRYRFRFME1EVXdOakl6TkRZek1Gb1hEVEk1TURVd05qSXpORFl6TUZvd2VqRXVNQ3dHQTFVRUF3d2xRWEJ3YkdVZ1FYQndiR2xqWVhScGIyNGdTVzUwWldkeVlYUnBiMjRnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFOEJjUmhCblhaSVhWR2w0bGdRZDI2SUNpNzk1N3JrM2dqZnhMaytFelZ0Vm1Xeld1SXRDWGRnMGlUbnU2Q1AxMkY4Nkl5M2E3Wm5DK3lPZ3BoUDlVUmFPQjl6Q0I5REJHQmdnckJnRUZCUWNCQVFRNk1EZ3dOZ1lJS3dZQkJRVUhNQUdHS21oMGRIQTZMeTl2WTNOd0xtRndjR3hsTG1OdmJTOXZZM053TURRdFlYQndiR1Z5YjI5MFkyRm5NekFkQmdOVkhRNEVGZ1FVSS9KSnhFK1Q1TzhuNXNUMktHdy9vcnY5TGtzd0R3WURWUjBUQVFIL0JBVXdBd0VCL3pBZkJnTlZIU01FR0RBV2dCUzdzTjZoV0RPSW1xU0ttZDYrdmV1djJzc2txekEzQmdOVkhSOEVNREF1TUN5Z0txQW9oaVpvZEhSd09pOHZZM0pzTG1Gd2NHeGxMbU52YlM5aGNIQnNaWEp2YjNSallXY3pMbU55YkRBT0JnTlZIUThCQWY4RUJBTUNBUVl3RUFZS0tvWklodmRqWkFZQ0RnUUNCUUF3Q2dZSUtvWkl6ajBFQXdJRFp3QXdaQUl3T3M5eWcxRVdtYkdHK3pYRFZzcGl2L1FYN2RrUGRVMmlqcjd4bklGZVFyZUorSmozbTFtZm1OVkJEWStkNmNMK0FqQXlMZFZFSWJDakJYZHNYZk00TzVCbi9SZDhMQ0Z0bGsvR2NtbUNFbTlVK0hwOUc1bkxtd21KSVdFR21ROEpraDBBQURHQ0FZZ3dnZ0dFQWdFQk1JR0dNSG94TGpBc0JnTlZCQU1NSlVGd2NHeGxJRUZ3Y0d4cFkyRjBhVzl1SUVsdWRHVm5jbUYwYVc5dUlFTkJJQzBnUnpNeEpqQWtCZ05WQkFzTUhVRndjR3hsSUVObGNuUnBabWxqWVhScGIyNGdRWFYwYUc5eWFYUjVNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV3SUlUREJCU1ZHZFZEWXdDd1lKWUlaSUFXVURCQUlCb0lHVE1CZ0dDU3FHU0liM0RRRUpBekVMQmdrcWhraUc5dzBCQndFd0hBWUpLb1pJaHZjTkFRa0ZNUThYRFRJME1ETXhOREE1TkRNeU0xb3dLQVlKS29aSWh2Y05BUWswTVJzdNTdMRElUVUQwcVI3RHd5SGx1VG0xMjJCejA5c2FzMkJVWitFRTlVPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXBoMkNUKytubXZpYjU3YWNJZmVKTjFCQmJyZUEveG84N2p1b0xETDFnS1IvYy9wRDZYK0xKSGRYUGJnMFBIT3pYYjJFYm5RR1ZWYmZIWHRkQzBYTTdBPT0iLCJ0cmFuc2FjdGlvbklkIjoiMjBlYzhlM2I2N2YyYmNmMDExMDVmODAwNmEwNWFmNTRiNjBkZDIwMzgyOTdlMmExMmI0Y2FlNDY0ODhjYjZhOSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } } ``` -> Since no dynamic fields was not added for stripe the `required_billing_contact_fields` is `null` <img width="1133" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/e4708058-ca0f-4d9c-8cc9-032097d9a5f1"> -> Create MCA create for cybersource -> Apple pay payment create with confirm false ``` { "amount": 650, "currency": "USD", "confirm": false, "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", "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":"eyJkYXRhIjoiQ1ZoTGd5RGU3TzZjdFlhWHFiVWFONFZvRjBCQjhTbDZsenlXYUdCKzhKcXlic2hYVGxoNEFEcTZYb0t6ZWVSVGwvcUp6NDIvUFMwcmMxMCtqSyt5Z1F5NnlkT25EcnVDeVpkaVU4SWFGOEtOS2hJMFFKOU9JTk9aWFlYR0VzZEczNXlVNzcrQ0k1dk5lUjJiK1gyUXZTVTMzSjlOczJuTFRXZHpwb1VUSHJKU1RiSmFmTTlxYjlZOHZuZS9vZUdHQkV1ZU9DQWQxcFhjRE54SEl2dlc5Z0x3WXRPVldKZUEvUnh5MEdsb0VISng3VEhqUEVQUGJwMkVVZjRMQXZQOGlJSEpmUjM0THdEUVBIdmNSeW9nalRJSzJqOXZjUGRqS2xBSG1LUm5wZlhvWkY4VE16ZUJ6eWhGb0dKY3ZRa3JMc216OEcxTXowZGxlV2VmU2V0TkYxT1NMaldCdExrUXpvWG5xdU1ZeExMenU2SkxPZ1E5ejN1OStFNGQ2NHRZS1NYYlZBWGRKNXRMNTdvbSIsInNpZ25hdHVyZSI6Ik1JQUdDU3FHU0liM0RRRUhBcUNBTUlBQ0FRRXhEVEFMQmdsZ2hrZ0JaUU1FQWdFd2dBWUpLb1pJaHZjTkFRY0JBQUNnZ0RDQ0ErTXdnZ09Jb0FNQ0FRSUNDRXd3UVVsUm5WUTJNQW9HQ0NxR1NNNDlCQU1DTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekFlRncweE9UQTFNVGd3TVRNeU5UZGFGdzB5TkRBMU1UWXdNVE15TlRkYU1GOHhKVEFqQmdOVkJBTU1IR1ZqWXkxemJYQXRZbkp2YTJWeUxYTnBaMjVmVlVNMExWQlNUMFF4RkRBU0JnTlZCQXNNQzJsUFV5QlRlWE4wWlcxek1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpCWk1CTUdCeXFHU000OUFnRUdDQ3FHU000OUF3RUhBMElBQk1JVmQrM3Ixc2V5SVk5bzNYQ1FvU0dOeDdDOWJ5d29QWVJnbGRsSzlLVkJHNE5DRHRnUjgwQitnek1mSEZURDkrc3lJTmE2MWRUdjlKS0ppVDU4RHhPamdnSVJNSUlDRFRBTUJnTlZIUk1CQWY4RUFqQUFNQjhHQTFVZEl3UVlNQmFBRkNQeVNjUlBrK1R2SitiRTlpaHNQNks3L1M1TE1FVUdDQ3NHQVFVRkJ3RUJCRGt3TnpBMUJnZ3JCZ0VGQlFjd0FZWXBhSFIwY0RvdkwyOWpjM0F1WVhCd2JHVXVZMjl0TDI5amMzQXdOQzFoY0hCc1pXRnBZMkV6TURJd2dnRWRCZ05WSFNBRWdnRVVNSUlCRURDQ0FRd0dDU3FHU0liM1kyUUZBVENCL2pDQnd3WUlLd1lCQlFVSEFnSXdnYllNZ2JOU1pXeHBZVzVqWlNCdmJpQjBhR2x6SUdObGNuUnBabWxqWVhSbElHSjVJR0Z1ZVNCd1lYSjBlU0JoYzNOMWJXVnpJR0ZqWTJWd2RHRnVZMlVnYjJZZ2RHaGxJSFJvWlc0Z1lYQndiR2xqWVdKc1pTQnpkR0Z1WkdGeVpDQjBaWEp0Y3lCaGJtUWdZMjl1WkdsMGFXOXVjeUJ2WmlCMWMyVXNJR05sY25ScFptbGpZWFJsSUhCdmJHbGplU0JoYm1RZ1kyVnlkR2xtYVdOaGRHbHZiaUJ3Y21GamRHbGpaU0J6ZEdGMFpXMWxiblJ6TGpBMkJnZ3JCZ0VGQlFjQ0FSWXFhSFIwY0RvdkwzZDNkeTVoY0hCc1pTNWpiMjB2WTJWeWRHbG1hV05oZEdWaGRYUm9iM0pwZEhrdk1EUUdBMVVkSHdRdE1Dc3dLYUFub0NXR0kyaDBkSEE2THk5amNtd3VZWEJ3YkdVdVkyOXRMMkZ3Y0d4bFlXbGpZVE11WTNKc01CMEdBMVVkRGdRV0JCU1VWOXR2MVhTQmhvbUpkaTkrVjRVSDU1dFlKREFPQmdOVkhROEJBZjhFQkFNQ0I0QXdEd1lKS29aSWh2ZGpaQVlkQkFJRkFEQUtCZ2dxaGtqT1BRUURBZ05KQURCR0FpRUF2Z2xYSCtjZUhuTmJWZVd2ckxUSEwrdEVYekFZVWlMSEpSQUN0aDY5YjFVQ0lRRFJpelVLWGRiZGJyRjBZRFd4SHJMT2g4K2o1cTlzdllPQWlRM0lMTjJxWXpDQ0F1NHdnZ0oxb0FNQ0FRSUNDRWx0TDc4Nm1OcVhNQW9HQ0NxR1NNNDlCQU1DTUdjeEd6QVpCZ05WQkFNTUVrRndjR3hsSUZKdmIzUWdRMEVnTFNCSE16RW1NQ1FHQTFVRUN3d2RRWEJ3YkdVZ1EyVnlkR2xtYVdOaGRHbHZiaUJCZFhSb2IzSnBkSGt4RXpBUkJnTlZCQW9NQ2tGd2NHeGxJRWx1WXk0eEN6QUpCZ05WQkFZVEFsVlRNQjRYRFRFME1EVXdOakl6TkRZek1Gb1hEVEk1TURVd05qSXpORFl6TUZvd2VqRXVNQ3dHQTFVRUF3d2xRWEJ3YkdVZ1FYQndiR2xqWVhScGIyNGdTVzUwWldkeVlYUnBiMjRnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFOEJjUmhCblhaSVhWR2w0bGdRZDI2SUNpNzk1N3JrM2dqZnhMaytFelZ0Vm1Xeld1SXRDWGRnMGlUbnU2Q1AxMkY4Nkl5M2E3Wm5DK3lPZ3BoUDlVUmFPQjl6Q0I5REJHQmdnckJnRUZCUWNCQVFRNk1EZ3dOZ1lJS3dZQkJRVUhNQUdHS21oMGRFCQmJyZUEveG84N2p1b0xETDFnS1IvYy9wRDZYK0xKSGRYUGJnMFBIT3pYYjJFYm5RR1ZWYmZIWHRkQzBYTTdBPT0iLCJ0cmFuc2FjdGlvbklkIjoiMjBlYzhlM2I2N2YyYmNmMDExMDVmODAwNmEwNWFmNTRiNjBkZDIwMzgyOTdlMmExMmI0Y2FlNDY0ODhjYjZhOSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } } ``` <img width="1109" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/36aec432-6c2b-4bcf-a9ed-d5849fe96b19"> -> Session call having the `required_billing_contact_fields` being passed as the dynamic fields are present <img width="1140" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/e9d7a960-7d79-42a7-bbb6-4776cadc8fd5">
2a302eb5973c64d8b77f8110fdbeb536ccbe1488
-> Create a MCA for stripe -> Apple pay payment create with confirm false ``` { "amount": 650, "currency": "USD", "confirm": false, "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", "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":"eyJkYXRhIjoiQ1ZoTGd5RGU3TzZjdFlhWHFiVWFONFZvRjBCQjhTbDZsenlXYUdCKzhKcXlic2hYVGxoNEFEcTZYb0t6ZWVSVGwvcUp6NDIvUFMwcmMxMCtqSyt5Z1F5NnlkT25EcnVDeVpkaVU4SWFGOEtOS2hJMFFKOU9JTk9aWFlYR0VzZEczNXlVNzcrQ0k1dk5lUjJiK1gyUXZTVTMzSjlOczJuTFRXZHpwb1VUSHJKU1RiSmFmTTlxYjlZOHZuZS9vZUdHQkV1ZU9DQWQxcFhjRE54SEl2dlc5Z0x3WXRPVldKZUEvUnh5MEdsb0VISng3VEhqUEVQUGJwMkVVZjRMQXZQOGlJSEpmUjM0THdEUVBIdmNSeW9nalRJSzJqOXZjUGRqS2xBSG1LUm5wZlhvWkY4VE16ZUJ6eWhGb0dKY3ZRa3JMc216OEcxTXowZGxlV2VmU2V0TkYxT1NMaldCdExrUXpvWG5xdU1ZeExMenU2SkxPZ1E5ejN1OStFNGQ2NHRZS1NYYlZBWGRKNXRMNTdvbSIsInNpZ25hdHVyZSI6Ik1JQUdDU3FHU0liM0RRRUhBcUNBTUlBQ0FRRXhEVEFMQmdsZ2hrZ0JaUU1FQWdFd2dBWUpLb1pJaHZjTkFRY0JBQUNnZ0RDQ0ErTXdnZ09Jb0FNQ0FRSUNDRXd3UVVsUm5WUTJNQW9HQ0NxR1NNNDlCQU1DTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekFlRncweE9UQTFNVGd3TVRNeU5UZGFGdzB5TkRBMU1UWXdNVE15TlRkYU1GOHhKVEFqQmdOVkJBTU1IR1ZqWXkxemJYQXRZbkp2YTJWeUxYTnBaMjVmVlVNMExWQlNUMFF4RkRBU0JnTlZCQXNNQzJsUFV5QlRlWE4wWlcxek1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpCWk1CTUdCeXFHU000OUFnRUdDQ3FHU000OUF3RUhBMElBQk1JVmQrM3Ixc2V5SVk5bzNYQ1FvU0dOeDdDOWJ5d29QWVJnbGRsSzlLVkJHNE5DRHRnUjgwQitnek1mSEZURDkrc3lJTmE2MWRUdjlKS0ppVDU4RHhPamdnSVJNSUlDRFRBTUJnTlZIUk1CQWY4RUFqQUFNQjhHQTFVZEl3UVlNQmFBRkNQeVNjUlBrK1R2SitiRTlpaHNQNks3L1M1TE1FVUdDQ3NHQVFVRkJ3RUJCRGt3TnpBMUJnZ3JCZ0VGQlFjd0FZWXBhSFIwY0RvdkwyOWpjM0F1WVhCd2JHVXVZMjl0TDI5amMzQXdOQzFoY0hCc1pXRnBZMkV6TURJd2dnRWRCZ05WSFNBRWdnRVVNSUlCRURDQ0FRd0dDU3FHU0liM1kyUUZBVENCL2pDQnd3WUlLd1lCQlFVSEFnSXdnYllNZ2JOU1pXeHBZVzVqWlNCdmJpQjBhR2x6SUdObGNuUnBabWxqWVhSbElHSjVJR0Z1ZVNCd1lYSjBlU0JoYzNOMWJXVnpJR0ZqWTJWd2RHRnVZMlVnYjJZZ2RHaGxJSFJvWlc0Z1lYQndiR2xqWVdKc1pTQnpkR0Z1WkdGeVpDQjBaWEp0Y3lCaGJtUWdZMjl1WkdsMGFXOXVjeUJ2WmlCMWMyVXNJR05sY25ScFptbGpZWFJsSUhCdmJHbGplU0JoYm1RZ1kyVnlkR2xtYVdOaGRHbHZiaUJ3Y21GamRHbGpaU0J6ZEdGMFpXMWxiblJ6TGpBMkJnZ3JCZ0VGQlFjQ0FSWXFhSFIwY0RvdkwzZDNkeTVoY0hCc1pTNWpiMjB2WTJWeWRHbG1hV05oZEdWaGRYUm9iM0pwZEhrdk1EUUdBMVVkSHdRdE1Dc3dLYUFub0NXR0kyaDBkSEE2THk5amNtd3VZWEJ3YkdVdVkyOXRMMkZ3Y0d4bFlXbGpZVE11WTNKc01CMEdBMVVkRGdRV0JCU1VWOXR2MVhTQmhvbUpkaTkrVjRVSDU1dFlKREFPQmdOVkhROEJBZjhFQkFNQ0I0QXdEd1lKS29aSWh2ZGpaQVlkQkFJRkFEQUtCZ2dxaGtqT1BRUURBZ05KQURCR0FpRUF2Z2xYSCtjZUhuTmJWZVd2ckxUSEwrdEVYekFZVWlMSEpSQUN0aDY5YjFVQ0lRRFJpelVLWGRiZGJyRjBZRFd4SHJMT2g4K2o1cTlzdllPQWlRM0lMTjJxWXpDQ0F1NHdnZ0oxb0FNQ0FRSUNDRWx0TDc4Nm1OcVhNQW9HQ0NxR1NNNDlCQU1DTUdjeEd6QVpCZ05WQkFNTUVrRndjR3hsSUZKdmIzUWdRMEVnTFNCSE16RW1NQ1FHQTFVRUN3d2RRWEJ3YkdVZ1EyVnlkR2xtYVdOaGRHbHZiaUJCZFhSb2IzSnBkSGt4RXpBUkJnTlZCQW9NQ2tGd2NHeGxJRWx1WXk0eEN6QUpCZ05WQkFZVEFsVlRNQjRYRFRFME1EVXdOakl6TkRZek1Gb1hEVEk1TURVd05qSXpORFl6TUZvd2VqRXVNQ3dHQTFVRUF3d2xRWEJ3YkdVZ1FYQndiR2xqWVhScGIyNGdTVzUwWldkeVlYUnBiMjRnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFOEJjUmhCblhaSVhWR2w0bGdRZDI2SUNpNzk1N3JrM2dqZnhMaytFelZ0Vm1Xeld1SXRDWGRnMGlUbnU2Q1AxMkY4Nkl5M2E3Wm5DK3lPZ3BoUDlVUmFPQjl6Q0I5REJHQmdnckJnRUZCUWNCQVFRNk1EZ3dOZ1lJS3dZQkJRVUhNQUdHS21oMGRIQTZMeTl2WTNOd0xtRndjR3hsTG1OdmJTOXZZM053TURRdFlYQndiR1Z5YjI5MFkyRm5NekFkQmdOVkhRNEVGZ1FVSS9KSnhFK1Q1TzhuNXNUMktHdy9vcnY5TGtzd0R3WURWUjBUQVFIL0JBVXdBd0VCL3pBZkJnTlZIU01FR0RBV2dCUzdzTjZoV0RPSW1xU0ttZDYrdmV1djJzc2txekEzQmdOVkhSOEVNREF1TUN5Z0txQW9oaVpvZEhSd09pOHZZM0pzTG1Gd2NHeGxMbU52YlM5aGNIQnNaWEp2YjNSallXY3pMbU55YkRBT0JnTlZIUThCQWY4RUJBTUNBUVl3RUFZS0tvWklodmRqWkFZQ0RnUUNCUUF3Q2dZSUtvWkl6ajBFQXdJRFp3QXdaQUl3T3M5eWcxRVdtYkdHK3pYRFZzcGl2L1FYN2RrUGRVMmlqcjd4bklGZVFyZUorSmozbTFtZm1OVkJEWStkNmNMK0FqQXlMZFZFSWJDakJYZHNYZk00TzVCbi9SZDhMQ0Z0bGsvR2NtbUNFbTlVK0hwOUc1bkxtd21KSVdFR21ROEpraDBBQURHQ0FZZ3dnZ0dFQWdFQk1JR0dNSG94TGpBc0JnTlZCQU1NSlVGd2NHeGxJRUZ3Y0d4cFkyRjBhVzl1SUVsdWRHVm5jbUYwYVc5dUlFTkJJQzBnUnpNeEpqQWtCZ05WQkFzTUhVRndjR3hsSUVObGNuUnBabWxqWVhScGIyNGdRWFYwYUc5eWFYUjVNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV3SUlUREJCU1ZHZFZEWXdDd1lKWUlaSUFXVURCQUlCb0lHVE1CZ0dDU3FHU0liM0RRRUpBekVMQmdrcWhraUc5dzBCQndFd0hBWUpLb1pJaHZjTkFRa0ZNUThYRFRJME1ETXhOREE1TkRNeU0xb3dLQVlKS29aSWh2Y05BUWswTVJzdNTdMRElUVUQwcVI3RHd5SGx1VG0xMjJCejA5c2FzMkJVWitFRTlVPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXBoMkNUKytubXZpYjU3YWNJZmVKTjFCQmJyZUEveG84N2p1b0xETDFnS1IvYy9wRDZYK0xKSGRYUGJnMFBIT3pYYjJFYm5RR1ZWYmZIWHRkQzBYTTdBPT0iLCJ0cmFuc2FjdGlvbklkIjoiMjBlYzhlM2I2N2YyYmNmMDExMDVmODAwNmEwNWFmNTRiNjBkZDIwMzgyOTdlMmExMmI0Y2FlNDY0ODhjYjZhOSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } } ``` -> Since no dynamic fields was not added for stripe the `required_billing_contact_fields` is `null` <img width="1133" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/e4708058-ca0f-4d9c-8cc9-032097d9a5f1"> -> Create MCA create for cybersource -> Apple pay payment create with confirm false ``` { "amount": 650, "currency": "USD", "confirm": false, "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", "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":"eyJkYXRhIjoiQ1ZoTGd5RGU3TzZjdFlhWHFiVWFONFZvRjBCQjhTbDZsenlXYUdCKzhKcXlic2hYVGxoNEFEcTZYb0t6ZWVSVGwvcUp6NDIvUFMwcmMxMCtqSyt5Z1F5NnlkT25EcnVDeVpkaVU4SWFGOEtOS2hJMFFKOU9JTk9aWFlYR0VzZEczNXlVNzcrQ0k1dk5lUjJiK1gyUXZTVTMzSjlOczJuTFRXZHpwb1VUSHJKU1RiSmFmTTlxYjlZOHZuZS9vZUdHQkV1ZU9DQWQxcFhjRE54SEl2dlc5Z0x3WXRPVldKZUEvUnh5MEdsb0VISng3VEhqUEVQUGJwMkVVZjRMQXZQOGlJSEpmUjM0THdEUVBIdmNSeW9nalRJSzJqOXZjUGRqS2xBSG1LUm5wZlhvWkY4VE16ZUJ6eWhGb0dKY3ZRa3JMc216OEcxTXowZGxlV2VmU2V0TkYxT1NMaldCdExrUXpvWG5xdU1ZeExMenU2SkxPZ1E5ejN1OStFNGQ2NHRZS1NYYlZBWGRKNXRMNTdvbSIsInNpZ25hdHVyZSI6Ik1JQUdDU3FHU0liM0RRRUhBcUNBTUlBQ0FRRXhEVEFMQmdsZ2hrZ0JaUU1FQWdFd2dBWUpLb1pJaHZjTkFRY0JBQUNnZ0RDQ0ErTXdnZ09Jb0FNQ0FRSUNDRXd3UVVsUm5WUTJNQW9HQ0NxR1NNNDlCQU1DTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekFlRncweE9UQTFNVGd3TVRNeU5UZGFGdzB5TkRBMU1UWXdNVE15TlRkYU1GOHhKVEFqQmdOVkJBTU1IR1ZqWXkxemJYQXRZbkp2YTJWeUxYTnBaMjVmVlVNMExWQlNUMFF4RkRBU0JnTlZCQXNNQzJsUFV5QlRlWE4wWlcxek1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpCWk1CTUdCeXFHU000OUFnRUdDQ3FHU000OUF3RUhBMElBQk1JVmQrM3Ixc2V5SVk5bzNYQ1FvU0dOeDdDOWJ5d29QWVJnbGRsSzlLVkJHNE5DRHRnUjgwQitnek1mSEZURDkrc3lJTmE2MWRUdjlKS0ppVDU4RHhPamdnSVJNSUlDRFRBTUJnTlZIUk1CQWY4RUFqQUFNQjhHQTFVZEl3UVlNQmFBRkNQeVNjUlBrK1R2SitiRTlpaHNQNks3L1M1TE1FVUdDQ3NHQVFVRkJ3RUJCRGt3TnpBMUJnZ3JCZ0VGQlFjd0FZWXBhSFIwY0RvdkwyOWpjM0F1WVhCd2JHVXVZMjl0TDI5amMzQXdOQzFoY0hCc1pXRnBZMkV6TURJd2dnRWRCZ05WSFNBRWdnRVVNSUlCRURDQ0FRd0dDU3FHU0liM1kyUUZBVENCL2pDQnd3WUlLd1lCQlFVSEFnSXdnYllNZ2JOU1pXeHBZVzVqWlNCdmJpQjBhR2x6SUdObGNuUnBabWxqWVhSbElHSjVJR0Z1ZVNCd1lYSjBlU0JoYzNOMWJXVnpJR0ZqWTJWd2RHRnVZMlVnYjJZZ2RHaGxJSFJvWlc0Z1lYQndiR2xqWVdKc1pTQnpkR0Z1WkdGeVpDQjBaWEp0Y3lCaGJtUWdZMjl1WkdsMGFXOXVjeUJ2WmlCMWMyVXNJR05sY25ScFptbGpZWFJsSUhCdmJHbGplU0JoYm1RZ1kyVnlkR2xtYVdOaGRHbHZiaUJ3Y21GamRHbGpaU0J6ZEdGMFpXMWxiblJ6TGpBMkJnZ3JCZ0VGQlFjQ0FSWXFhSFIwY0RvdkwzZDNkeTVoY0hCc1pTNWpiMjB2WTJWeWRHbG1hV05oZEdWaGRYUm9iM0pwZEhrdk1EUUdBMVVkSHdRdE1Dc3dLYUFub0NXR0kyaDBkSEE2THk5amNtd3VZWEJ3YkdVdVkyOXRMMkZ3Y0d4bFlXbGpZVE11WTNKc01CMEdBMVVkRGdRV0JCU1VWOXR2MVhTQmhvbUpkaTkrVjRVSDU1dFlKREFPQmdOVkhROEJBZjhFQkFNQ0I0QXdEd1lKS29aSWh2ZGpaQVlkQkFJRkFEQUtCZ2dxaGtqT1BRUURBZ05KQURCR0FpRUF2Z2xYSCtjZUhuTmJWZVd2ckxUSEwrdEVYekFZVWlMSEpSQUN0aDY5YjFVQ0lRRFJpelVLWGRiZGJyRjBZRFd4SHJMT2g4K2o1cTlzdllPQWlRM0lMTjJxWXpDQ0F1NHdnZ0oxb0FNQ0FRSUNDRWx0TDc4Nm1OcVhNQW9HQ0NxR1NNNDlCQU1DTUdjeEd6QVpCZ05WQkFNTUVrRndjR3hsSUZKdmIzUWdRMEVnTFNCSE16RW1NQ1FHQTFVRUN3d2RRWEJ3YkdVZ1EyVnlkR2xtYVdOaGRHbHZiaUJCZFhSb2IzSnBkSGt4RXpBUkJnTlZCQW9NQ2tGd2NHeGxJRWx1WXk0eEN6QUpCZ05WQkFZVEFsVlRNQjRYRFRFME1EVXdOakl6TkRZek1Gb1hEVEk1TURVd05qSXpORFl6TUZvd2VqRXVNQ3dHQTFVRUF3d2xRWEJ3YkdVZ1FYQndiR2xqWVhScGIyNGdTVzUwWldkeVlYUnBiMjRnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFOEJjUmhCblhaSVhWR2w0bGdRZDI2SUNpNzk1N3JrM2dqZnhMaytFelZ0Vm1Xeld1SXRDWGRnMGlUbnU2Q1AxMkY4Nkl5M2E3Wm5DK3lPZ3BoUDlVUmFPQjl6Q0I5REJHQmdnckJnRUZCUWNCQVFRNk1EZ3dOZ1lJS3dZQkJRVUhNQUdHS21oMGRFCQmJyZUEveG84N2p1b0xETDFnS1IvYy9wRDZYK0xKSGRYUGJnMFBIT3pYYjJFYm5RR1ZWYmZIWHRkQzBYTTdBPT0iLCJ0cmFuc2FjdGlvbklkIjoiMjBlYzhlM2I2N2YyYmNmMDExMDVmODAwNmEwNWFmNTRiNjBkZDIwMzgyOTdlMmExMmI0Y2FlNDY0ODhjYjZhOSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } } ``` <img width="1109" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/36aec432-6c2b-4bcf-a9ed-d5849fe96b19"> -> Session call having the `required_billing_contact_fields` being passed as the dynamic fields are present <img width="1140" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/e9d7a960-7d79-42a7-bbb6-4776cadc8fd5">
[ "crates/api_models/src/enums.rs", "crates/api_models/src/payment_methods.rs", "crates/api_models/src/payments.rs", "crates/connector_configs/src/transformer.rs", "crates/openapi/src/openapi.rs", "crates/router/src/connector/bluesnap/transformers.rs", "crates/router/src/connector/payme/transformers.rs", ...
juspay/hyperswitch
juspay__hyperswitch-4618
Bug: [FEAT] add an API to toggle KV for all the merchants
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 2e288140a9f..12d9832ada6 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -829,6 +829,22 @@ pub struct ToggleKVRequest { pub kv_enabled: bool, } +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct ToggleAllKVRequest { + /// Status of KV for the specific merchant + #[schema(example = true)] + pub kv_enabled: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct ToggleAllKVResponse { + ///Total number of updated merchants + #[schema(example = 20)] + pub total_updated: usize, + /// Status of KV for the specific merchant + #[schema(example = true)] + pub kv_enabled: bool, +} #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MerchantConnectorDetailsWrap { /// Creds Identifier is to uniquely identify the credentials. Do not send any sensitive info in this field. And do not send the string "null". diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index c9ae775fed8..9c26576e77b 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -60,6 +60,8 @@ impl_misc_api_event_type!( RevokeApiKeyResponse, ToggleKVResponse, ToggleKVRequest, + ToggleAllKVRequest, + ToggleAllKVResponse, MerchantAccountDeleteResponse, MerchantAccountUpdate, CardInfoResponse, diff --git a/crates/diesel_models/src/query/merchant_account.rs b/crates/diesel_models/src/query/merchant_account.rs index 1d4eef75206..dd2f284305b 100644 --- a/crates/diesel_models/src/query/merchant_account.rs +++ b/crates/diesel_models/src/query/merchant_account.rs @@ -123,4 +123,16 @@ impl MerchantAccount { ) .await } + + pub async fn update_all_merchant_accounts( + conn: &PgPooledConn, + merchant_account: MerchantAccountUpdateInternal, + ) -> StorageResult<Vec<Self>> { + generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( + conn, + dsl::merchant_id.ne_all(vec![""]), + merchant_account, + ) + .await + } } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 288de66de07..af707087ce3 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1420,6 +1420,36 @@ pub async fn kv_for_merchant( )) } +pub async fn toggle_kv_for_all_merchants( + state: AppState, + enable: bool, +) -> RouterResponse<api_models::admin::ToggleAllKVResponse> { + let db = state.store.as_ref(); + let storage_scheme = if enable { + MerchantStorageScheme::RedisKv + } else { + MerchantStorageScheme::PostgresOnly + }; + + let total_update = db + .update_all_merchant_account(storage::MerchantAccountUpdate::StorageSchemeUpdate { + storage_scheme, + }) + .await + .map_err(|error| { + error + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to switch merchant_storage_scheme for all merchants") + })?; + + Ok(service_api::ApplicationResponse::Json( + api_models::admin::ToggleAllKVResponse { + total_updated: total_update, + kv_enabled: enable, + }, + )) +} + pub async fn check_merchant_account_kv_status( state: AppState, merchant_id: String, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index bfe0592fd3d..88579892d2f 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -828,6 +828,15 @@ impl MerchantAccountInterface for KafkaStore { .await } + async fn update_all_merchant_account( + &self, + merchant_account: storage::MerchantAccountUpdate, + ) -> CustomResult<usize, errors::StorageError> { + self.diesel_store + .update_all_merchant_account(merchant_account) + .await + } + async fn find_merchant_account_by_publishable_key( &self, publishable_key: &str, diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index 08d0c279047..c323ca4abb1 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use common_utils::ext_traits::AsyncExt; +use diesel_models::MerchantAccountUpdateInternal; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] @@ -40,6 +41,11 @@ where merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError>; + async fn update_all_merchant_account( + &self, + merchant_account: storage::MerchantAccountUpdate, + ) -> CustomResult<usize, errors::StorageError>; + async fn update_merchant( &self, this: domain::MerchantAccount, @@ -354,6 +360,38 @@ impl MerchantAccountInterface for Store { Ok(merchant_accounts) } + + async fn update_all_merchant_account( + &self, + merchant_account: storage::MerchantAccountUpdate, + ) -> CustomResult<usize, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + + let db_func = || async { + storage::MerchantAccount::update_all_merchant_accounts( + &conn, + MerchantAccountUpdateInternal::from(merchant_account), + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + }; + + let total; + #[cfg(not(feature = "accounts_cache"))] + { + let ma = db_func().await?; + total = ma.len(); + } + + #[cfg(feature = "accounts_cache")] + { + let ma = db_func().await?; + publish_and_redact_all_merchant_account_cache(self, &ma).await?; + total = ma.len(); + } + + Ok(total) + } } #[async_trait::async_trait] @@ -433,6 +471,13 @@ impl MerchantAccountInterface for MockDb { Err(errors::StorageError::MockDbError)? } + async fn update_all_merchant_account( + &self, + _merchant_account_update: storage::MerchantAccountUpdate, + ) -> CustomResult<usize, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + async fn delete_merchant_account_by_merchant_id( &self, _merchant_id: &str, @@ -477,3 +522,22 @@ async fn publish_and_redact_merchant_account_cache( super::cache::publish_into_redact_channel(store, cache_keys).await?; Ok(()) } + +#[cfg(feature = "accounts_cache")] +async fn publish_and_redact_all_merchant_account_cache( + store: &dyn super::StorageInterface, + merchant_accounts: &[storage::MerchantAccount], +) -> CustomResult<(), errors::StorageError> { + let merchant_ids = merchant_accounts.iter().map(|m| m.merchant_id.clone()); + let publishable_keys = merchant_accounts + .iter() + .filter_map(|m| m.publishable_key.clone()); + + let cache_keys: Vec<CacheKind<'_>> = merchant_ids + .chain(publishable_keys) + .map(|s| CacheKind::Accounts(s.into())) + .collect(); + + super::cache::publish_into_redact_channel(store, cache_keys).await?; + Ok(()) +} diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index d9cadf002c1..2d1b77460a5 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -458,6 +458,31 @@ pub async fn merchant_account_toggle_kv( ) .await } + +/// Merchant Account - Toggle KV +/// +/// Toggle KV mode for all Merchant Accounts +#[instrument(skip_all)] +pub async fn merchant_account_toggle_all_kv( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<admin::ToggleAllKVRequest>, +) -> HttpResponse { + let flow = Flow::ConfigKeyUpdate; + let payload = json_payload.into_inner(); + + api::server_wrap( + flow, + state, + &req, + payload, + |state, _, payload, _| toggle_kv_for_all_merchants(state, payload.kv_enabled), + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + ) + .await +} + #[instrument(skip_all, fields(flow = ?Flow::BusinessProfileCreate))] pub async fn business_profile_create( state: web::Data<AppState>, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 21cc994381e..f4eded24be6 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -866,6 +866,7 @@ impl MerchantAccount { .route(web::post().to(merchant_account_toggle_kv)) .route(web::get().to(merchant_account_kv_status)), ) + .service(web::resource("/kv").route(web::post().to(merchant_account_toggle_all_kv))) .service( web::resource("/{id}") .route(web::get().to(retrieve_merchant_account)) diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index fcbd97d5cb1..8fc3ebb721f 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -3,7 +3,8 @@ pub use api_models::admin::{ MerchantAccountDeleteResponse, MerchantAccountResponse, MerchantAccountUpdate, MerchantConnectorCreate, MerchantConnectorDeleteResponse, MerchantConnectorDetails, MerchantConnectorDetailsWrap, MerchantConnectorId, MerchantConnectorResponse, MerchantDetails, - MerchantId, PaymentMethodsEnabled, ToggleKVRequest, ToggleKVResponse, WebhookDetails, + MerchantId, PaymentMethodsEnabled, ToggleAllKVRequest, ToggleAllKVResponse, ToggleKVRequest, + ToggleKVResponse, WebhookDetails, }; use common_utils::ext_traits::{Encode, ValueExt}; use error_stack::ResultExt;
2024-05-09T07:02:01Z
## Description <!-- Describe your changes in detail --> Add an API to toggle KV for all merchants ### Additional Changes - [x] This PR modifies the API contract ## 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 an API to toggle KV for all merchants ## 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)? --> - Enable KV for all merchants ```bash curl --location 'http://localhost:8080/accounts/kv' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "kv_enabled": true }' ``` Check if any merchant_account has `postgres_only`. ```sql SELECT storage_scheme from merchant_account where storage_scheme='postgres_only' ``` It should return 0 rows -Disable KV for all merchants ```bash curl --location 'http://localhost:8080/accounts/kv' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "kv_enabled": false }' ``` Check if any merchant_account has `redis_kv` ```sql SELECT storage_scheme from merchant_account where storage_scheme='redis_kv' ``` It should return 0 rows
5e84855496d80959c1fc43c1efc9bb2a4d802d5a
- Enable KV for all merchants ```bash curl --location 'http://localhost:8080/accounts/kv' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "kv_enabled": true }' ``` Check if any merchant_account has `postgres_only`. ```sql SELECT storage_scheme from merchant_account where storage_scheme='postgres_only' ``` It should return 0 rows -Disable KV for all merchants ```bash curl --location 'http://localhost:8080/accounts/kv' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "kv_enabled": false }' ``` Check if any merchant_account has `redis_kv` ```sql SELECT storage_scheme from merchant_account where storage_scheme='redis_kv' ``` It should return 0 rows
[ "crates/api_models/src/admin.rs", "crates/api_models/src/events.rs", "crates/diesel_models/src/query/merchant_account.rs", "crates/router/src/core/admin.rs", "crates/router/src/db/kafka_store.rs", "crates/router/src/db/merchant_account.rs", "crates/router/src/routes/admin.rs", "crates/router/src/route...
juspay/hyperswitch
juspay__hyperswitch-4595
Bug: [Feature] Add tenant-ID as a field to all KafkaStore events ### Context In-order to support multi-tenancy we need to store data partioned via tenant-id. In order to do that for kafka events we need to pass tenant-id as a field in the generated kafka events We can use the KafkaStore field added in #4512 to add them to events in Kafka ### Approach 1. Add a new field in `KafkaEvent` struct representing tenant_id ```rust #[derive(serde::Serialize, Debug)] struct KafkaEvent<'a, T: KafkaMessage> { #[serde(flatten)] event: &'a T, sign_flag: i32, tenant_id: TenantID } ``` Alternate approaches can be discussed in the issue
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index a64e3cc7e38..15a0b2e2046 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -76,7 +76,7 @@ use crate::{ }, }; -#[derive(Clone, Serialize)] +#[derive(Debug, Clone, Serialize)] pub struct TenantID(pub String); #[derive(Clone)] @@ -413,7 +413,11 @@ impl DisputeInterface for KafkaStore { ) -> CustomResult<storage::Dispute, errors::StorageError> { let dispute = self.diesel_store.insert_dispute(dispute_new).await?; - if let Err(er) = self.kafka_producer.log_dispute(&dispute, None).await { + if let Err(er) = self + .kafka_producer + .log_dispute(&dispute, None, self.tenant_id.clone()) + .await + { logger::error!(message="Failed to add analytics entry for Dispute {dispute:?}", error_message=?er); }; @@ -466,7 +470,7 @@ impl DisputeInterface for KafkaStore { .await?; if let Err(er) = self .kafka_producer - .log_dispute(&dispute_new, Some(this)) + .log_dispute(&dispute_new, Some(this), self.tenant_id.clone()) .await { logger::error!(message="Failed to add analytics entry for Dispute {dispute_new:?}", error_message=?er); @@ -1109,7 +1113,7 @@ impl PaymentAttemptInterface for KafkaStore { if let Err(er) = self .kafka_producer - .log_payment_attempt(&attempt, None) + .log_payment_attempt(&attempt, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) @@ -1131,7 +1135,7 @@ impl PaymentAttemptInterface for KafkaStore { if let Err(er) = self .kafka_producer - .log_payment_attempt(&attempt, Some(this)) + .log_payment_attempt(&attempt, Some(this), self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) @@ -1311,7 +1315,7 @@ impl PaymentIntentInterface for KafkaStore { if let Err(er) = self .kafka_producer - .log_payment_intent(&intent, Some(this)) + .log_payment_intent(&intent, Some(this), self.tenant_id.clone()) .await { logger::error!(message="Failed to add analytics entry for Payment Intent {intent:?}", error_message=?er); @@ -1331,7 +1335,11 @@ impl PaymentIntentInterface for KafkaStore { .insert_payment_intent(new, storage_scheme) .await?; - if let Err(er) = self.kafka_producer.log_payment_intent(&intent, None).await { + if let Err(er) = self + .kafka_producer + .log_payment_intent(&intent, None, self.tenant_id.clone()) + .await + { logger::error!(message="Failed to add analytics entry for Payment Intent {intent:?}", error_message=?er); }; @@ -1558,6 +1566,7 @@ impl PayoutAttemptInterface for KafkaStore { .log_payout( &KafkaPayout::from_storage(payouts, &updated_payout_attempt), Some(KafkaPayout::from_storage(payouts, this)), + self.tenant_id.clone(), ) .await { @@ -1582,6 +1591,7 @@ impl PayoutAttemptInterface for KafkaStore { .log_payout( &KafkaPayout::from_storage(payouts, &payout_attempt_new), None, + self.tenant_id.clone(), ) .await { @@ -1639,6 +1649,7 @@ impl PayoutsInterface for KafkaStore { .log_payout( &KafkaPayout::from_storage(&payout, payout_attempt), Some(KafkaPayout::from_storage(this, payout_attempt)), + self.tenant_id.clone(), ) .await { @@ -1903,7 +1914,11 @@ impl RefundInterface for KafkaStore { .update_refund(this.clone(), refund, storage_scheme) .await?; - if let Err(er) = self.kafka_producer.log_refund(&refund, Some(this)).await { + if let Err(er) = self + .kafka_producer + .log_refund(&refund, Some(this), self.tenant_id.clone()) + .await + { logger::error!(message="Failed to insert analytics event for Refund Update {refund?}", error_message=?er); } Ok(refund) @@ -1931,7 +1946,11 @@ impl RefundInterface for KafkaStore { ) -> CustomResult<storage::Refund, errors::StorageError> { let refund = self.diesel_store.insert_refund(new, storage_scheme).await?; - if let Err(er) = self.kafka_producer.log_refund(&refund, None).await { + if let Err(er) = self + .kafka_producer + .log_refund(&refund, None, self.tenant_id.clone()) + .await + { logger::error!(message="Failed to insert analytics event for Refund Create {refund?}", error_message=?er); } Ok(refund) @@ -2504,7 +2523,7 @@ impl BatchSampleDataInterface for KafkaStore { for payment_intent in payment_intents_list.iter() { let _ = self .kafka_producer - .log_payment_intent(payment_intent, None) + .log_payment_intent(payment_intent, None, self.tenant_id.clone()) .await; } Ok(payment_intents_list) @@ -2525,7 +2544,7 @@ impl BatchSampleDataInterface for KafkaStore { for payment_attempt in payment_attempts_list.iter() { let _ = self .kafka_producer - .log_payment_attempt(payment_attempt, None) + .log_payment_attempt(payment_attempt, None, self.tenant_id.clone()) .await; } Ok(payment_attempts_list) @@ -2542,7 +2561,10 @@ impl BatchSampleDataInterface for KafkaStore { .await?; for refund in refunds_list.iter() { - let _ = self.kafka_producer.log_refund(refund, None).await; + let _ = self + .kafka_producer + .log_refund(refund, None, self.tenant_id.clone()) + .await; } Ok(refunds_list) } @@ -2562,7 +2584,7 @@ impl BatchSampleDataInterface for KafkaStore { for payment_intent in payment_intents_list.iter() { let _ = self .kafka_producer - .log_payment_intent_delete(payment_intent) + .log_payment_intent_delete(payment_intent, self.tenant_id.clone()) .await; } Ok(payment_intents_list) @@ -2583,7 +2605,7 @@ impl BatchSampleDataInterface for KafkaStore { for payment_attempt in payment_attempts_list.iter() { let _ = self .kafka_producer - .log_payment_attempt_delete(payment_attempt) + .log_payment_attempt_delete(payment_attempt, self.tenant_id.clone()) .await; } @@ -2601,7 +2623,10 @@ impl BatchSampleDataInterface for KafkaStore { .await?; for refund in refunds_list.iter() { - let _ = self.kafka_producer.log_refund_delete(refund).await; + let _ = self + .kafka_producer + .log_refund_delete(refund, self.tenant_id.clone()) + .await; } Ok(refunds_list) diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index ba9806b29d1..58657c59fd8 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -30,6 +30,7 @@ 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>; +use crate::db::kafka_store::TenantID; pub trait KafkaMessage where @@ -54,19 +55,22 @@ struct KafkaEvent<'a, T: KafkaMessage> { #[serde(flatten)] event: &'a T, sign_flag: i32, + tenant_id: TenantID, } impl<'a, T: KafkaMessage> KafkaEvent<'a, T> { - fn new(event: &'a T) -> Self { + fn new(event: &'a T, tenant_id: TenantID) -> Self { Self { event, sign_flag: 1, + tenant_id, } } - fn old(event: &'a T) -> Self { + fn old(event: &'a T, tenant_id: TenantID) -> Self { Self { event, sign_flag: -1, + tenant_id, } } } @@ -266,28 +270,33 @@ impl KafkaProducer { &self, attempt: &PaymentAttempt, old_attempt: Option<PaymentAttempt>, + tenant_id: TenantID, ) -> MQResult<()> { if let Some(negative_event) = old_attempt { - self.log_event(&KafkaEvent::old(&KafkaPaymentAttempt::from_storage( - &negative_event, - ))) + self.log_event(&KafkaEvent::old( + &KafkaPaymentAttempt::from_storage(&negative_event), + tenant_id.clone(), + )) .attach_printable_lazy(|| { format!("Failed to add negative attempt event {negative_event:?}") })?; }; - self.log_event(&KafkaEvent::new(&KafkaPaymentAttempt::from_storage( - attempt, - ))) + self.log_event(&KafkaEvent::new( + &KafkaPaymentAttempt::from_storage(attempt), + tenant_id.clone(), + )) .attach_printable_lazy(|| format!("Failed to add positive attempt event {attempt:?}")) } pub async fn log_payment_attempt_delete( &self, delete_old_attempt: &PaymentAttempt, + tenant_id: TenantID, ) -> MQResult<()> { - self.log_event(&KafkaEvent::old(&KafkaPaymentAttempt::from_storage( - delete_old_attempt, - ))) + self.log_event(&KafkaEvent::old( + &KafkaPaymentAttempt::from_storage(delete_old_attempt), + tenant_id.clone(), + )) .attach_printable_lazy(|| { format!("Failed to add negative attempt event {delete_old_attempt:?}") }) @@ -297,48 +306,69 @@ impl KafkaProducer { &self, intent: &PaymentIntent, old_intent: Option<PaymentIntent>, + tenant_id: TenantID, ) -> MQResult<()> { if let Some(negative_event) = old_intent { - self.log_event(&KafkaEvent::old(&KafkaPaymentIntent::from_storage( - &negative_event, - ))) + self.log_event(&KafkaEvent::old( + &KafkaPaymentIntent::from_storage(&negative_event), + tenant_id.clone(), + )) .attach_printable_lazy(|| { format!("Failed to add negative intent event {negative_event:?}") })?; }; - self.log_event(&KafkaEvent::new(&KafkaPaymentIntent::from_storage(intent))) - .attach_printable_lazy(|| format!("Failed to add positive intent event {intent:?}")) + self.log_event(&KafkaEvent::new( + &KafkaPaymentIntent::from_storage(intent), + tenant_id.clone(), + )) + .attach_printable_lazy(|| format!("Failed to add positive intent event {intent:?}")) } pub async fn log_payment_intent_delete( &self, delete_old_intent: &PaymentIntent, + tenant_id: TenantID, ) -> MQResult<()> { - self.log_event(&KafkaEvent::old(&KafkaPaymentIntent::from_storage( - delete_old_intent, - ))) + self.log_event(&KafkaEvent::old( + &KafkaPaymentIntent::from_storage(delete_old_intent), + tenant_id.clone(), + )) .attach_printable_lazy(|| { format!("Failed to add negative intent event {delete_old_intent:?}") }) } - pub async fn log_refund(&self, refund: &Refund, old_refund: Option<Refund>) -> MQResult<()> { + pub async fn log_refund( + &self, + refund: &Refund, + old_refund: Option<Refund>, + tenant_id: TenantID, + ) -> MQResult<()> { if let Some(negative_event) = old_refund { - self.log_event(&KafkaEvent::old(&KafkaRefund::from_storage( - &negative_event, - ))) + self.log_event(&KafkaEvent::old( + &KafkaRefund::from_storage(&negative_event), + tenant_id.clone(), + )) .attach_printable_lazy(|| { format!("Failed to add negative refund event {negative_event:?}") })?; }; - self.log_event(&KafkaEvent::new(&KafkaRefund::from_storage(refund))) - .attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}")) + self.log_event(&KafkaEvent::new( + &KafkaRefund::from_storage(refund), + tenant_id.clone(), + )) + .attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}")) } - pub async fn log_refund_delete(&self, delete_old_refund: &Refund) -> MQResult<()> { - self.log_event(&KafkaEvent::old(&KafkaRefund::from_storage( - delete_old_refund, - ))) + pub async fn log_refund_delete( + &self, + delete_old_refund: &Refund, + tenant_id: TenantID, + ) -> MQResult<()> { + self.log_event(&KafkaEvent::old( + &KafkaRefund::from_storage(delete_old_refund), + tenant_id.clone(), + )) .attach_printable_lazy(|| { format!("Failed to add negative refund event {delete_old_refund:?}") }) @@ -348,17 +378,22 @@ impl KafkaProducer { &self, dispute: &Dispute, old_dispute: Option<Dispute>, + tenant_id: TenantID, ) -> MQResult<()> { if let Some(negative_event) = old_dispute { - self.log_event(&KafkaEvent::old(&KafkaDispute::from_storage( - &negative_event, - ))) + self.log_event(&KafkaEvent::old( + &KafkaDispute::from_storage(&negative_event), + tenant_id.clone(), + )) .attach_printable_lazy(|| { format!("Failed to add negative dispute event {negative_event:?}") })?; }; - self.log_event(&KafkaEvent::new(&KafkaDispute::from_storage(dispute))) - .attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}")) + self.log_event(&KafkaEvent::new( + &KafkaDispute::from_storage(dispute), + tenant_id.clone(), + )) + .attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}")) } #[cfg(feature = "payouts")] @@ -366,20 +401,25 @@ impl KafkaProducer { &self, payout: &KafkaPayout<'_>, old_payout: Option<KafkaPayout<'_>>, + tenant_id: TenantID, ) -> MQResult<()> { if let Some(negative_event) = old_payout { - self.log_event(&KafkaEvent::old(&negative_event)) + self.log_event(&KafkaEvent::old(&negative_event, tenant_id.clone())) .attach_printable_lazy(|| { format!("Failed to add negative payout event {negative_event:?}") })?; }; - self.log_event(&KafkaEvent::new(payout)) + self.log_event(&KafkaEvent::new(payout, tenant_id.clone())) .attach_printable_lazy(|| format!("Failed to add positive payout event {payout:?}")) } #[cfg(feature = "payouts")] - pub async fn log_payout_delete(&self, delete_old_payout: &KafkaPayout<'_>) -> MQResult<()> { - self.log_event(&KafkaEvent::old(delete_old_payout)) + pub async fn log_payout_delete( + &self, + delete_old_payout: &KafkaPayout<'_>, + tenant_id: TenantID, + ) -> MQResult<()> { + self.log_event(&KafkaEvent::old(delete_old_payout, tenant_id.clone())) .attach_printable_lazy(|| { format!("Failed to add negative payout event {delete_old_payout:?}") })
2024-05-09T04:56:02Z
## Description <!-- Describe your changes in detail --> - Add TenantID to the KafkaEvent struct and add the extra param to the KafkaEvent constructor - Made changes to the required placed ### 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). --> - Supporting multi-tenancy ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="973" alt="image" src="https://github.com/juspay/hyperswitch/assets/21202349/aaed9da0-ab3c-4161-afb2-51a752fdf2f3">
f3115c45114c1445456af229f11ca19459c9536d
<img width="973" alt="image" src="https://github.com/juspay/hyperswitch/assets/21202349/aaed9da0-ab3c-4161-afb2-51a752fdf2f3">
[ "crates/router/src/db/kafka_store.rs", "crates/router/src/services/kafka.rs" ]
juspay/hyperswitch
juspay__hyperswitch-4596
Bug: feat: Create API for TOTP Verification To complete the TOTP Flow, there needs to be an API which needs to verify the totp entered by the user and give the next token and flow that user should go to enter into the dashboard.
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 1d91a47bf56..e9eb5157095 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -17,7 +17,7 @@ use crate::user::{ ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse, UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate, - VerifyEmailRequest, + VerifyEmailRequest, VerifyTotpRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -74,7 +74,8 @@ common_utils::impl_misc_api_event_type!( GetUserRoleDetailsResponse, TokenResponse, UserFromEmailRequest, - BeginTotpResponse + BeginTotpResponse, + VerifyTotpRequest ); #[cfg(feature = "dummy_connector")] diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 0dde73d0545..7dbf867d1a0 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -252,3 +252,8 @@ pub struct TotpSecret { pub totp_url: Secret<String>, pub recovery_codes: Vec<Secret<String>>, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct VerifyTotpRequest { + pub totp: Option<Secret<String>>, +} diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index ddcd10c32e4..580e34ba7e8 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -66,6 +66,10 @@ pub enum UserErrors { RoleNameParsingError, #[error("RoleNameAlreadyExists")] RoleNameAlreadyExists, + #[error("TOTPNotSetup")] + TotpNotSetup, + #[error("InvalidTOTP")] + InvalidTotp, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -169,6 +173,12 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::RoleNameAlreadyExists => { AER::BadRequest(ApiError::new(sub_code, 35, self.get_error_message(), None)) } + Self::TotpNotSetup => { + AER::BadRequest(ApiError::new(sub_code, 36, self.get_error_message(), None)) + } + Self::InvalidTotp => { + AER::BadRequest(ApiError::new(sub_code, 37, self.get_error_message(), None)) + } } } } @@ -205,6 +215,8 @@ impl UserErrors { Self::InvalidRoleOperationWithMessage(error_message) => error_message, Self::RoleNameParsingError => "Invalid Role Name", Self::RoleNameAlreadyExists => "Role name already exists", + Self::TotpNotSetup => "TOTP not setup", + Self::InvalidTotp => "Invalid TOTP", } } } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index e01ed4b1a23..83cdd1d318b 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1642,3 +1642,65 @@ pub async fn begin_totp( }), })) } + +pub async fn verify_totp( + state: AppState, + user_token: auth::UserFromSinglePurposeToken, + req: user_api::VerifyTotpRequest, +) -> UserResponse<user_api::TokenResponse> { + let user_from_db: domain::UserFromStorage = state + .store + .find_user_by_id(&user_token.user_id) + .await + .change_context(UserErrors::InternalServerError)? + .into(); + + if let Some(user_totp) = req.totp { + if user_from_db.get_totp_status() == TotpStatus::NotSet { + return Err(UserErrors::TotpNotSetup.into()); + } + + let user_totp_secret = user_from_db + .decrypt_and_get_totp_secret(&state) + .await? + .ok_or(UserErrors::InternalServerError)?; + + let totp = + utils::user::generate_default_totp(user_from_db.get_email(), Some(user_totp_secret))?; + + if totp + .generate_current() + .change_context(UserErrors::InternalServerError)? + != user_totp.expose() + { + return Err(UserErrors::InvalidTotp.into()); + } + + if user_from_db.get_totp_status() == TotpStatus::InProgress { + state + .store + .update_user_by_user_id( + user_from_db.get_user_id(), + storage_user::UserUpdate::TotpUpdate { + totp_status: Some(TotpStatus::Set), + totp_secret: None, + totp_recovery_codes: None, + }, + ) + .await + .change_context(UserErrors::InternalServerError)?; + } + } + + let current_flow = domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::TOTP.into())?; + let next_flow = current_flow.next(user_from_db, &state).await?; + let token = next_flow.get_token(&state).await?; + + auth::cookies::set_cookie_response( + user_api::TokenResponse { + token: token.clone(), + token_type: next_flow.get_flow().into(), + }, + token, + ) +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 1560578f66f..49a8e063183 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1199,7 +1199,8 @@ impl User { .route(web::get().to(get_multiple_dashboard_metadata)) .route(web::post().to(set_dashboard_metadata)), ) - .service(web::resource("/totp/begin").route(web::get().to(totp_begin))); + .service(web::resource("/totp/begin").route(web::get().to(totp_begin))) + .service(web::resource("/totp/verify").route(web::post().to(totp_verify))); #[cfg(feature = "email")] { diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 5bef68073f0..ee42cc50fe3 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -211,7 +211,8 @@ impl From<Flow> for ApiIdentifier { | Flow::AcceptInviteFromEmail | Flow::VerifyEmailRequest | Flow::UpdateUserAccountDetails - | Flow::TotpBegin => Self::User, + | Flow::TotpBegin + | Flow::TotpVerify => Self::User, Flow::ListRoles | Flow::GetRole diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index db12729d01a..a901988e51e 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -626,3 +626,21 @@ pub async fn totp_begin(state: web::Data<AppState>, req: HttpRequest) -> HttpRes )) .await } + +pub async fn totp_verify( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_api::VerifyTotpRequest>, +) -> HttpResponse { + let flow = Flow::TotpVerify; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, user, req_body, _| user_core::verify_totp(state, user, req_body), + &auth::SinglePurposeJWTAuth(common_enums::TokenPurpose::TOTP), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 00881626c1c..45f5d74d6f6 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -4,7 +4,7 @@ use api_models::{ admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api, }; use common_enums::TokenPurpose; -use common_utils::{errors::CustomResult, pii}; +use common_utils::{crypto::Encryptable, errors::CustomResult, pii}; use diesel_models::{ enums::{TotpStatus, UserStatus}, organization as diesel_org, @@ -909,6 +909,32 @@ impl UserFromStorage { pub fn get_totp_status(&self) -> TotpStatus { self.0.totp_status } + + pub async fn decrypt_and_get_totp_secret( + &self, + state: &AppState, + ) -> UserResult<Option<Secret<String>>> { + if self.0.totp_secret.is_none() { + return Ok(None); + } + + let user_key_store = state + .store + .get_user_key_store_by_user_id( + self.get_user_id(), + &state.store.get_master_key().to_vec().into(), + ) + .await + .change_context(UserErrors::InternalServerError)?; + + Ok(domain_types::decrypt::<String, masking::WithType>( + self.0.totp_secret.clone(), + user_key_store.key.peek(), + ) + .await + .change_context(UserErrors::InternalServerError)? + .map(Encryptable::into_inner)) + } } impl From<info::ModuleInfo> for user_role_api::ModuleInfo { diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index b3252302413..9ea86167fcf 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -398,6 +398,8 @@ pub enum Flow { UserFromEmail, /// Begin TOTP TotpBegin, + /// Verify TOTP + TotpVerify, /// List initial webhook delivery attempts WebhookEventInitialDeliveryAttemptList, /// List delivery attempts for a webhook event
2024-05-08T18:01:14Z
## Description <!-- Describe your changes in detail --> This PR allows users to complete the TOTP flow. It adds a new api `/user/totp/verify`, which will verify the totp entered by the user and mark the user totp status as set if it is in `InProgress`. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #4596. ## 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/totp/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer SPT with Purpose as TOTP' \ --data '{ "totp": "189646" }' ``` If the TOTP is correct, the the API should return the next token that is in the current flow. ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZjYwOWFiMDAtNzg5Ny00NTU2LWFlMGMtNGQ4MDZmZGFkZTkxIiwicHVycG9zZSI6ImZvcmNlX3NldF9wYXNzd29yZCIsIm9yaWdpbiI6InNpZ25fdXAiLCJleHAiOjE3MTUyNjQ0NTF9.jkhMT8x1o5WhzNxqBbBwX4jS0TQuSpemlg9_5K5Kgk8", "token_type": "force_set_password" } ```
ec3b60e37c0b178c3e5e3fe79db88f83fd195722
``` curl --location 'http://localhost:8080/user/totp/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer SPT with Purpose as TOTP' \ --data '{ "totp": "189646" }' ``` If the TOTP is correct, the the API should return the next token that is in the current flow. ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZjYwOWFiMDAtNzg5Ny00NTU2LWFlMGMtNGQ4MDZmZGFkZTkxIiwicHVycG9zZSI6ImZvcmNlX3NldF9wYXNzd29yZCIsIm9yaWdpbiI6InNpZ25fdXAiLCJleHAiOjE3MTUyNjQ0NTF9.jkhMT8x1o5WhzNxqBbBwX4jS0TQuSpemlg9_5K5Kgk8", "token_type": "force_set_password" } ```
[ "crates/api_models/src/events/user.rs", "crates/api_models/src/user.rs", "crates/router/src/core/errors/user.rs", "crates/router/src/core/user.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/user.rs", "crates/router/src/types/domain/user.rs",...