repo
stringclasses
1 value
instance_id
stringlengths
24
24
problem_statement
stringlengths
24
8.41k
patch
stringlengths
0
367k
test_patch
stringclasses
1 value
created_at
stringdate
2023-04-18 16:43:29
2025-10-07 09:18:54
hints_text
stringlengths
57
132k
version
stringclasses
8 values
base_commit
stringlengths
40
40
environment_setup_commit
stringlengths
40
40
juspay/hyperswitch
juspay__hyperswitch-7506
Bug: [BUG] [BRAINTREE] Fix picking of creds identifier during Complete Authorize Flow ### Bug Description When MCA Create is not done for Braintree, and connector creds are passed in Payment Intent Request, then Complete Authorize Flow fails. ### Expected Behavior When MCA Create is not done for Braintree, and connector creds are passed in Payment Intent Request, then Complete Authorize Flow should not fail. ### Actual Behavior When MCA Create is not done for Braintree, and connector creds are passed in Payment Intent Request, then Complete Authorize Flow fails. ### Steps To Reproduce When MCA Create is not done for Braintree, and connector creds are passed in Payment Intent Request, then Complete Authorize Flow fails. ### Context For The Bug _No response_ ### Environment Integ, Sandbox, Production ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index d072463020a..6ebc5266eba 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -2328,6 +2328,12 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { let payment_confirm_req = api::PaymentsRequest { payment_id: Some(req.resource_id.clone()), merchant_id: req.merchant_id.clone(), + merchant_connector_details: req.creds_identifier.map(|creds_id| { + api::MerchantConnectorDetailsWrap { + creds_identifier: creds_id, + encoded_data: None, + } + }), feature_metadata: Some(api_models::payments::FeatureMetadata { redirect_response: Some(api_models::payments::RedirectResponse { param: req.param.map(Secret::new), diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index cdbda13997b..82c9eca97c4 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1262,13 +1262,18 @@ pub fn create_complete_authorize_url( router_base_url: &String, payment_attempt: &PaymentAttempt, connector_name: impl std::fmt::Display, + creds_identifier: Option<&str>, ) -> String { + let creds_identifier = creds_identifier.map_or_else(String::new, |creds_identifier| { + format!("/{}", creds_identifier) + }); format!( - "{}/payments/{}/{}/redirect/complete/{}", + "{}/payments/{}/{}/redirect/complete/{}{}", router_base_url, payment_attempt.payment_id.get_string_repr(), payment_attempt.merchant_id.get_string_repr(), - connector_name + connector_name, + creds_identifier ) } 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 d95e92115ad..7befdfc91d3 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -305,6 +305,14 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> id: profile_id.get_string_repr().to_owned(), })?; + let creds_identifier = + request + .merchant_connector_details + .as_ref() + .map(|merchant_connector_details| { + merchant_connector_details.creds_identifier.to_owned() + }); + let payment_data = PaymentData { flow: PhantomData, payment_intent, @@ -336,7 +344,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> attempts: None, sessions_token: vec![], card_cvc: request.card_cvc.clone(), - creds_identifier: None, + creds_identifier, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 9647a277b0e..f1577f6e10f 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -223,6 +223,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>( router_base_url, attempt, connector_id, + None, )); let webhook_url = Some(helpers::create_webhook_url( @@ -887,6 +888,7 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>( router_base_url, attempt, connector_id, + None, )); let webhook_url = Some(helpers::create_webhook_url( @@ -3115,7 +3117,9 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz router_base_url, attempt, connector_name, + payment_data.creds_identifier.as_deref(), )); + let merchant_connector_account_id_or_connector_name = payment_data .payment_attempt .merchant_connector_id @@ -4084,6 +4088,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz router_base_url, attempt, connector_name, + payment_data.creds_identifier.as_deref(), )); let braintree_metadata = payment_data .payment_intent @@ -4198,6 +4203,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProce router_base_url, attempt, connector_name, + payment_data.creds_identifier.as_deref(), )); let browser_info: Option<types::BrowserInformation> = payment_data .payment_attempt diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index de5593703d0..5d364d9b923 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -747,6 +747,11 @@ impl Payments { .route(web::get().to(payments::payments_redirect_response)) .route(web::post().to(payments::payments_redirect_response)) ) + .service( + web::resource("/{payment_id}/{merchant_id}/redirect/complete/{connector}/{creds_identifier}") + .route(web::get().to(payments::payments_complete_authorize_redirect_with_creds_identifier)) + .route(web::post().to(payments::payments_complete_authorize_redirect_with_creds_identifier)) + ) .service( web::resource("/{payment_id}/{merchant_id}/redirect/complete/{connector}") .route(web::get().to(payments::payments_complete_authorize_redirect)) diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 9708f34c53c..cd136ff784f 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -1084,6 +1084,58 @@ pub async fn payments_complete_authorize_redirect( .await } +#[cfg(feature = "v1")] +#[instrument(skip_all, fields(flow =? Flow::PaymentsRedirect, payment_id))] +pub async fn payments_complete_authorize_redirect_with_creds_identifier( + state: web::Data<app::AppState>, + req: actix_web::HttpRequest, + json_payload: Option<web::Form<serde_json::Value>>, + path: web::Path<( + common_utils::id_type::PaymentId, + common_utils::id_type::MerchantId, + String, + String, + )>, +) -> impl Responder { + let flow = Flow::PaymentsRedirect; + let (payment_id, merchant_id, connector, creds_identifier) = path.into_inner(); + let param_string = req.query_string(); + + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); + + let payload = payments::PaymentsRedirectResponseData { + resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id), + merchant_id: Some(merchant_id.clone()), + param: Some(param_string.to_string()), + json_payload: json_payload.map(|s| s.0), + force_sync: false, + connector: Some(connector), + creds_identifier: Some(creds_identifier), + }; + let locking_action = payload.get_locking_input(flow.clone()); + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: auth::AuthenticationData, req, req_state| { + + <payments::PaymentRedirectCompleteAuthorize as PaymentRedirectFlow>::handle_payments_redirect_response( + &payments::PaymentRedirectCompleteAuthorize {}, + state, + req_state, + auth.merchant_account, + auth.key_store, + req, + auth.platform_merchant_account, + ) + }, + &auth::MerchantIdAuth(merchant_id), + locking_action, + )) + .await +} + #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow =? Flow::PaymentsCompleteAuthorize, payment_id))] pub async fn payments_complete_authorize(
2025-03-12T14:27:12Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> When MCA Create is not done for Braintree, and connector creds are passed in Payment Intent Request, then Complete Authorize Flow fails. This PR is for fixing that. ### 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). --> Issue Link: https://github.com/juspay/hyperswitch/issues/7506 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> **Postman Tests** **1. Payment Intent Create (Without Braintree MCA Create)** -Request ``` curl --location 'http://localhost:8080/vs/v1/payment_intents' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --header 'User-Agent: helloMozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36' \ --header 'api-key: dev_cAhKiY0z6BCPtxdTZKiuoGXNfbk49QwuMRPJudoj4P5gWR24zvL1BniBwqBBP7SL' \ --data-urlencode 'amount=1200' \ --data-urlencode 'currency=USD' \ --data-urlencode 'confirm=true' \ --data-urlencode 'payment_method_data%5Btype%5D=card' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bnumber%5D=5200000000001096' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bexp_month%5D=10' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bexp_year%5D=26' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bcvc%5D=123' \ --data-urlencode 'connector%5B%5D=braintree' \ --data-urlencode 'capture_method=automatic' \ --data-urlencode 'customer=sahkal' \ --data-urlencode 'statementDescriptorSuffix=merchant_101' \ --data-urlencode 'metadata%5BorderId%5D=1677581650' \ --data-urlencode 'payment_method_options%5Bcard%5D%5Brequest_three_d_secure%5D=any' \ --data-urlencode 'description=Card Payment' \ --data-urlencode 'return_url=https://google.com' \ --data-urlencode 'merchant_connector_details%5Bencoded_data%5D=eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0.2Ef5oJ8MdVY9wdMdVVYHhrjUfY-NzgUc5oN7rKR3IG9jzYWkc9my0bMVQ31H2GjHQGBRuNzR0y-OfzFBHpmpSxA6qt5c-PFs2HaIEV69tXml6u6FcKtPvsMxVTRIiMMN1dJTwxKm9kqBMsXE6rpokDkKOJTU1-33Lz7v0VAT2KsZo7zNc4Tp0SI_tLaBwos4N-Ihws4PGbNy6CkEId0tTArJMg2y7utl759DAnUwwjgNNebMNUa9qAAIX6zCrn0U4n7NGyrpBbKqOu4Cd7sYeysP_jKjE12FexXHcEwHwUZTa453q-DvvvKlbfoACgGjE9ceBMr8kF1d1EnyS2J4DA.Wp1spmaGnWhvvCqY.X5I79LC8PC5AHQy6bT0JCNPrsvqc51iVWu1O5487ihDmCCkwC4eBXgm5STkYtNfttbMHD6-SimAVmtqD0AmhCUoJ7h0qQbcZt4XdB89gH5pdZvaSsmozlYxMG64jvGkXfp22aQZf-SwpcRWslP5CmFGTJDT7OgJTNBOZuoA6tbFIyxoXUh1L6Km4DuJA2dbKPRsw_Cg_5O869Wg5ghQmEtqHToirWLbwtZN32phRLt6L.GooLyxP-9xhU-vvi2vRGdA' \ --data-urlencode 'merchant_connector_details%5Bcreds_identifier%5D=azharamin_noon_1efwedxqwd' \ --data-urlencode 'id=154107184321542' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Bname%5D=Joseph Doe' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Bemail%[email protected]' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Baddress%5D%5Bcity%5D=siliguri' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Baddress%5D%5Bcountry%5D=IN' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Baddress%5D%5Bstate%5D=westbengal' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Baddress%5D%5Bline1%5D=pritilata' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Baddress%5D%5Bzip%5D=734006' \ --data-urlencode 'metadata%5Bmerchant_id%5D=sahkal' \ --data-urlencode 'metadata%5Beuler_merchant_id%5D=global_installment' \ --data-urlencode 'connector_metadata%5Bnoon%5D%5Border_category%5D=pay' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bholder_name%5D=Joseph Doe' \ --data-urlencode 'connector_metadata%5Bbraintree%5D%5Bmerchant_account_id%5D=juspay' \ --data-urlencode 'connector_metadata%5Bbraintree%5D%5Bmerchant_config_currency%5D=USD' ``` -Response ``` { "id": "154107184321542", "object": "payment_intent", "amount": 1200, "amount_received": null, "amount_capturable": 1200, "currency": "usd", "status": "requires_action", "client_secret": "154107184321542_secret_HE2P7xcJNdGJr061tYZh", "created": 1741828281, "customer": "sahkal", "refunds": null, "mandate": null, "metadata": { "orderId": "1677581650", "merchant_id": "sahkal", "euler_merchant_id": "global_installment" }, "charges": { "object": "list", "data": [], "has_more": false, "total_count": 0, "url": "http://placeholder" }, "connector": "braintree", "description": "Card Payment", "mandate_data": null, "setup_future_usage": null, "off_session": null, "authentication_type": "three_ds", "next_action": { "type": "redirect_to_url", "redirect_to_url": { "return_url": "https://google.com/", "url": "http://localhost:8080/payments/redirect/154107184321542/postman_merchant_GHAction_174568/154107184321542_1" } }, "cancellation_reason": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1096", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "520000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "26", "card_holder_name": "Joseph Doe", "payment_checks": null, "authentication_data": null } }, "shipping": null, "billing": { "address": { "city": "siliguri", "country": "IN", "line1": "pritilata", "line2": null, "line3": null, "zip": null, "state": "westbengal", "first_name": null, "last_name": null }, "phone": { "number": null, "country_code": "IN" }, "email": "[email protected]" }, "capture_on": null, "payment_token": null, "email": null, "phone": null, "statement_descriptor_suffix": null, "statement_descriptor_name": null, "capture_method": "automatic", "name": null, "last_payment_error": null, "connector_transaction_id": null } ``` **2. Payment Create (Normal Hyperswitch Flow)** -Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_cAhKiY0z6BCPtxdTZKiuoGXNfbk49QwuMRPJudoj4P5gWR24zvL1BniBwqBBP7SL' \ --data-raw '{ "amount": 2500, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 2500, "customer_id": "abcdef", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "5200000000001096", "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": "9123456789", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` -Response ``` { "payment_id": "pay_QLFSd62pZGRWHmzJl9V1", "merchant_id": "postman_merchant_GHAction_174568", "status": "requires_customer_action", "amount": 2500, "net_amount": 2500, "shipping_cost": null, "amount_capturable": 2500, "amount_received": null, "connector": "braintree", "client_secret": "pay_QLFSd62pZGRWHmzJl9V1_secret_1lRAyjj7PewghQLE5bMm", "created": "2025-03-13T01:13:16.662Z", "currency": "USD", "customer_id": "abcdef", "customer": { "id": "abcdef", "name": "John Doe", "email": "[email protected]", "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": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1096", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "520000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+91" }, "email": null }, "order_details": null, "email": "[email protected]", "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_QLFSd62pZGRWHmzJl9V1/postman_merchant_GHAction_174568/pay_QLFSd62pZGRWHmzJl9V1_1" }, "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": "abcdef", "created_at": 1741828396, "expires": 1741831996, "secret": "epk_beff18305e9f49bda8a0b9e2a77b249e" }, "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_1tsuB1vmUFHSgf5OavLc", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_iQuV3uVZfTRA8dJJg53p", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-13T01:28:16.662Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-13T01:13:18.053Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual" } ``` **2. PSync** -Request ``` curl --location 'http://localhost:8080/payments/pay_QLFSd62pZGRWHmzJl9V1' \ --header 'Accept: application/json' \ --header 'api-key: dev_cAhKiY0z6BCPtxdTZKiuoGXNfbk49QwuMRPJudoj4P5gWR24zvL1BniBwqBBP7SL' ``` -Response ``` { "payment_id": "pay_QLFSd62pZGRWHmzJl9V1", "merchant_id": "postman_merchant_GHAction_174568", "status": "succeeded", "amount": 2500, "net_amount": 2500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 2500, "connector": "braintree", "client_secret": "pay_QLFSd62pZGRWHmzJl9V1_secret_1lRAyjj7PewghQLE5bMm", "created": "2025-03-13T01:13:16.662Z", "currency": "USD", "customer_id": "abcdef", "customer": { "id": "abcdef", "name": "John Doe", "email": "[email protected]", "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": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1096", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "520000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+91" }, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "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": "dHJhbnNhY3Rpb25fNGMyNnRlN3I", "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_1tsuB1vmUFHSgf5OavLc", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_iQuV3uVZfTRA8dJJg53p", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-13T01:28:16.662Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-13T01:14:51.291Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
13a274909962872f1d663d082af33fc44205d419
13a274909962872f1d663d082af33fc44205d419
juspay/hyperswitch
juspay__hyperswitch-7507
Bug: Add support for co-badged cards info lookup for debit routing A debit card can be linked to multiple card networks, with one serving as the primary (international) network and the others as secondary (local) networks. In debit routing, payments will be processed through the local network based on the merchant's requirements. As part of this process, we need to have a co-badged card info lookup to retrieve all the networks associated with the card.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 76b65a1433e..b475142a570 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -7334,7 +7334,11 @@ "UnionPay", "Interac", "RuPay", - "Maestro" + "Maestro", + "Star", + "Pulse", + "Accel", + "Nyce" ] }, "CardNetworkTokenizeRequest": { diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index db90936370b..c71ee457f5d 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -9284,7 +9284,11 @@ "UnionPay", "Interac", "RuPay", - "Maestro" + "Maestro", + "Star", + "Pulse", + "Accel", + "Nyce" ] }, "CardNetworkTokenizeRequest": { diff --git a/config/config.example.toml b/config/config.example.toml index 4cfe6a61e38..9f34eea38fb 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -441,6 +441,12 @@ 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" } +[debit_routing_config] # Debit Routing configs +supported_currencies = "USD" # Supported currencies for debit routing +supported_connectors = "adyen" # Supported connectors for debit routing + +[debit_routing_config.connector_supported_debit_networks] # Debit Routing config that contains the supported debit networks for each connector +adyen = "Star,Pulse,Accel,Nyce" # Debit networks supported by adyen connector [temp_locker_enable_config] stripe = { payment_method = "bank_transfer" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 79074230917..1a15867e7db 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -590,6 +590,13 @@ eps = { country = "AT", currency = "EUR" } ideal = { country = "NL", currency = "EUR" } przelewy24 = { country = "PL", currency = "PLN,EUR" } +[debit_routing_config] +supported_currencies = "USD" +supported_connectors = "adyen" + +[debit_routing_config.connector_supported_debit_networks] +adyen = "Star,Pulse,Accel,Nyce" + [pm_filters.rapyd] apple_pay = { country = "AL,AS,AD,AR,AM,AU,AT,AZ,BH,BE,BM,BA,BR,BG,CA,KH,KY,CL,CO,CR,HR,CY,CZ,DK,DO,EC,SV,EE,FO,FI,FR,GE,DE,GI,GR,GL,GU,GT,GG,HN,HK,HU,IS,IE,IM,IL,IT,JP,KZ,KG,KW,LV,LI,LT,LU,MO,MY,MT,MX,MD,MC,ME,MA,NL,NZ,NI,MK,MP,NO,PA,PY,PR,PE,PL,PT,QA,RO,SM,RS,SG,SK,SI,ZA,ES,SE,CH,TW,TJ,TH,UA,AE,GB,US,UY,VI,VN", currency = "EUR,GBP,ISK,USD" } google_pay = { country = "AM,AT,AU,AZ,BA,BE,BG,BY,CA,CH,CL,CN,CO,CR,CY,CZ,DE,DK,DO,EC,EE,EG,ES,FI,FR,GB,GE,GL,GR,GT,HK,HN,HR,HU,IE,IL,IM,IS,IT,JE,JP,JO,KZ,KW,LA,LI,LT,LU,LV,MA,MC,MD,ME,MO,MN,MT,MX,MY,NC,NL,NO,NZ,OM,PA,PE,PL,PR,PT,QA,RO,RS,SA,SE,SG,SI,SK,SM,SV,TH,TW,UA,US,UY,VA,VN,ZA", currency = "EUR,GBP,ISK,USD" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 43f764f4e02..da9ad3daa4a 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -172,6 +172,13 @@ base_url = "https://app.hyperswitch.io" force_two_factor_auth = false force_cookies = false +[debit_routing_config] +supported_currencies = "USD" +supported_connectors = "adyen" + +[debit_routing_config.connector_supported_debit_networks] +adyen = "Star,Pulse,Accel,Nyce" + [frm] enabled = true diff --git a/config/development.toml b/config/development.toml index ccf5649951d..aeee9151c37 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1045,6 +1045,13 @@ payout_analytics_topic = "hyperswitch-payout-events" consolidated_events_topic = "hyperswitch-consolidated-events" authentication_analytics_topic = "hyperswitch-authentication-events" +[debit_routing_config] +supported_currencies = "USD" +supported_connectors = "adyen" + +[debit_routing_config.connector_supported_debit_networks] +adyen = "Star,Pulse,Accel,Nyce" + [analytics] source = "sqlx" forex_enabled = false diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 9ac4bb7f352..a82ba8c4a0e 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -594,6 +594,12 @@ eps = { country = "DE",currency = "EUR" } apple_pay = { country = "DE",currency = "EUR" } paypal = { country = "DE",currency = "EUR" } +[debit_routing_config] +supported_currencies = "USD" +supported_connectors = "adyen" + +[debit_routing_config.connector_supported_debit_networks] +adyen = "Star,Pulse,Accel,Nyce" [pm_filters.nuvei] credit = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,YER,ZAR" } diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index 1d5bfd58467..87e874f7fa5 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -23,7 +23,6 @@ pub mod gsm; pub mod health_check; pub mod locker_migration; pub mod mandates; -#[cfg(feature = "dynamic_routing")] pub mod open_router; pub mod organization; pub mod payment_methods; diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index 07af605892f..f80623efc64 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -1,6 +1,6 @@ use std::{collections::HashMap, fmt::Debug}; -use common_utils::{id_type, types::MinorUnit}; +use common_utils::{errors, id_type, types::MinorUnit}; pub use euclid::{ dssa::types::EuclidAnalysable, frontend::{ @@ -10,7 +10,10 @@ pub use euclid::{ }; use serde::{Deserialize, Serialize}; -use crate::enums::{Currency, PaymentMethod}; +use crate::{ + enums::{Currency, PaymentMethod}, + payment_methods, +}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -27,6 +30,7 @@ pub struct OpenRouterDecideGatewayRequest { pub enum RankingAlgorithm { SrBasedRouting, PlBasedRouting, + NtwBasedRouting, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -38,7 +42,7 @@ pub struct PaymentInfo { // customerId: Option<ETCu::CustomerId>, // preferredGateway: Option<ETG::Gateway>, pub payment_type: String, - // metadata: Option<String>, + pub metadata: Option<String>, // internalMetadata: Option<String>, // isEmi: Option<bool>, // emiBank: Option<String>, @@ -48,7 +52,7 @@ pub struct PaymentInfo { // paymentSource: Option<String>, // authType: Option<ETCa::txn_card_info::AuthType>, // cardIssuerBankName: Option<String>, - // cardIsin: Option<String>, + pub card_isin: Option<String>, // cardType: Option<ETCa::card_type::CardType>, // cardSwitchProvider: Option<Secret<String>>, } @@ -56,6 +60,63 @@ pub struct PaymentInfo { #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct DecidedGateway { pub gateway_priority_map: Option<HashMap<String, f64>>, + pub debit_routing_output: Option<DebitRoutingOutput>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct DebitRoutingOutput { + pub co_badged_card_networks: Vec<common_enums::CardNetwork>, + pub issuer_country: common_enums::CountryAlpha2, + pub is_regulated: bool, + pub regulated_name: Option<common_enums::RegulatedName>, + pub card_type: common_enums::CardType, +} + +impl From<&DebitRoutingOutput> for payment_methods::CoBadgedCardData { + fn from(output: &DebitRoutingOutput) -> Self { + Self { + co_badged_card_networks: output.co_badged_card_networks.clone(), + issuer_country_code: output.issuer_country, + is_regulated: output.is_regulated, + regulated_name: output.regulated_name.clone(), + } + } +} + +impl TryFrom<(payment_methods::CoBadgedCardData, String)> for DebitRoutingRequestData { + type Error = error_stack::Report<errors::ParsingError>; + + fn try_from( + (output, card_type): (payment_methods::CoBadgedCardData, String), + ) -> Result<Self, Self::Error> { + let parsed_card_type = card_type.parse::<common_enums::CardType>().map_err(|_| { + error_stack::Report::new(errors::ParsingError::EnumParseFailure("CardType")) + })?; + + Ok(Self { + co_badged_card_networks: output.co_badged_card_networks, + issuer_country: output.issuer_country_code, + is_regulated: output.is_regulated, + regulated_name: output.regulated_name, + card_type: parsed_card_type, + }) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CoBadgedCardRequest { + pub merchant_category_code: common_enums::MerchantCategoryCode, + pub acquirer_country: common_enums::CountryAlpha2, + pub co_badged_card_data: Option<DebitRoutingRequestData>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct DebitRoutingRequestData { + pub co_badged_card_networks: Vec<common_enums::CardNetwork>, + pub issuer_country: common_enums::CountryAlpha2, + pub is_regulated: bool, + pub regulated_name: Option<common_enums::RegulatedName>, + pub card_type: common_enums::CardType, } #[derive(Debug, Serialize, Deserialize)] diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index df4074dc00c..6e9a174c9f6 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -985,6 +985,15 @@ pub struct CardDetailsPaymentMethod { pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] pub saved_to_locker: bool, + pub co_badged_card_data: Option<CoBadgedCardData>, +} + +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct CoBadgedCardData { + pub co_badged_card_networks: Vec<api_enums::CardNetwork>, + pub issuer_country_code: common_enums::CountryAlpha2, + pub is_regulated: bool, + pub regulated_name: Option<common_enums::RegulatedName>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] @@ -1313,6 +1322,7 @@ impl From<CardDetail> for CardDetailsPaymentMethod { card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, + co_badged_card_data: None, } } } @@ -1321,8 +1331,10 @@ impl From<CardDetail> for CardDetailsPaymentMethod { any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] -impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { - fn from(item: CardDetailFromLocker) -> Self { +impl From<(CardDetailFromLocker, Option<&CoBadgedCardData>)> for CardDetailsPaymentMethod { + fn from( + (item, co_badged_card_data): (CardDetailFromLocker, Option<&CoBadgedCardData>), + ) -> Self { Self { issuer_country: item.issuer_country, last4_digits: item.last4_digits, @@ -1335,6 +1347,7 @@ impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, + co_badged_card_data: co_badged_card_data.cloned(), } } } @@ -1354,6 +1367,7 @@ impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, + co_badged_card_data: None, } } } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 880062cef21..226471dcc74 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2310,6 +2310,130 @@ pub enum CardNetwork { RuPay, #[serde(alias = "MAESTRO")] Maestro, + #[serde(alias = "STAR")] + Star, + #[serde(alias = "PULSE")] + Pulse, + #[serde(alias = "ACCEL")] + Accel, + #[serde(alias = "NYCE")] + Nyce, +} + +#[derive( + Clone, + Debug, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumIter, + strum::EnumString, + utoipa::ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "snake_case")] +pub enum RegulatedName { + #[serde(rename = "GOVERNMENT NON-EXEMPT INTERCHANGE FEE (WITH FRAUD)")] + #[strum(serialize = "GOVERNMENT NON-EXEMPT INTERCHANGE FEE (WITH FRAUD)")] + NonExemptWithFraud, + + #[serde(untagged)] + #[strum(default)] + Unknown(String), +} + +#[derive( + Clone, + Debug, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumIter, + strum::EnumString, + utoipa::ToSchema, + Copy, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "lowercase")] +pub enum PanOrToken { + Pan, + Token, +} + +#[derive( + Clone, + Debug, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumIter, + strum::EnumString, + utoipa::ToSchema, + Copy, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[strum(serialize_all = "UPPERCASE")] +#[serde(rename_all = "snake_case")] +pub enum CardType { + Credit, + Debit, +} + +#[derive(Debug, Clone, Serialize, Deserialize, strum::EnumString, strum::Display)] +#[serde(rename_all = "snake_case")] +pub enum MerchantCategoryCode { + #[serde(rename = "merchant_category_code_0001")] + Mcc0001, +} + +impl CardNetwork { + pub fn is_global_network(&self) -> bool { + match self { + Self::Interac + | Self::Star + | Self::Pulse + | Self::Accel + | Self::Nyce + | Self::CartesBancaires => false, + + Self::Visa + | Self::Mastercard + | Self::AmericanExpress + | Self::JCB + | Self::DinersClub + | Self::Discover + | Self::UnionPay + | Self::RuPay + | Self::Maestro => true, + } + } + + pub fn is_us_local_network(&self) -> bool { + match self { + Self::Star | Self::Pulse | Self::Accel | Self::Nyce => true, + Self::Interac + | Self::CartesBancaires + | Self::Visa + | Self::Mastercard + | Self::AmericanExpress + | Self::JCB + | Self::DinersClub + | Self::Discover + | Self::UnionPay + | Self::RuPay + | Self::Maestro => false, + } + } } /// Stage of the dispute diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 55dcc4e5bd2..40b37b6b3c5 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -402,6 +402,11 @@ impl MinorUnit { Self(value) } + /// checks if the amount is greater than the given value + pub fn is_greater_than(&self, value: i64) -> bool { + self.get_amount_as_i64() > value + } + /// Convert the amount to its major denomination based on Currency and return String /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index a4403923fd5..b46733d17cf 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -83,6 +83,14 @@ merchant_secret="Source verification key" payment_method_type = "Mastercard" [[adyen.debit]] payment_method_type = "Visa" +[[adyen.debit]] + payment_method_type = "Nyce" +[[adyen.debit]] + payment_method_type = "Pulse" +[[adyen.debit]] + payment_method_type = "Star" +[[adyen.debit]] + payment_method_type = "Accel" [[adyen.debit]] payment_method_type = "Interac" [[adyen.debit]] diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index d9dea35440b..331c92c39ba 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -83,6 +83,14 @@ merchant_secret="Source verification key" payment_method_type = "Mastercard" [[adyen.debit]] payment_method_type = "Visa" +[[adyen.debit]] + payment_method_type = "Nyce" +[[adyen.debit]] + payment_method_type = "Pulse" +[[adyen.debit]] + payment_method_type = "Star" +[[adyen.debit]] + payment_method_type = "Accel" [[adyen.debit]] payment_method_type = "Interac" [[adyen.debit]] diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index c899c62561f..26ba1cbe52b 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -1257,6 +1257,7 @@ pub enum CardBrand { Visa, MC, Amex, + Accel, Argencard, Bcmc, Bijcard, @@ -1281,13 +1282,16 @@ pub enum CardBrand { Mir, Naranja, Oasis, + Pulse, Rupay, Shopping, + Star, Solo, Troy, Uatp, Visaalphabankbonus, Visadankort, + Nyce, Warehouse, } @@ -2091,6 +2095,10 @@ fn get_adyen_card_network(card_network: common_enums::CardNetwork) -> Option<Car common_enums::CardNetwork::UnionPay => Some(CardBrand::Cup), common_enums::CardNetwork::RuPay => Some(CardBrand::Rupay), common_enums::CardNetwork::Maestro => Some(CardBrand::Maestro), + common_enums::CardNetwork::Star => Some(CardBrand::Star), + common_enums::CardNetwork::Accel => Some(CardBrand::Accel), + common_enums::CardNetwork::Pulse => Some(CardBrand::Pulse), + common_enums::CardNetwork::Nyce => Some(CardBrand::Nyce), common_enums::CardNetwork::Interac => None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs index 3a627fdfdf8..7aed189fbd7 100644 --- a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs @@ -556,7 +556,12 @@ fn get_boa_card_type(card_network: common_enums::CardNetwork) -> Option<&'static common_enums::CardNetwork::UnionPay => Some("062"), //"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024" common_enums::CardNetwork::Maestro => Some("042"), - common_enums::CardNetwork::Interac | common_enums::CardNetwork::RuPay => None, + common_enums::CardNetwork::Interac + | common_enums::CardNetwork::RuPay + | common_enums::CardNetwork::Star + | common_enums::CardNetwork::Accel + | common_enums::CardNetwork::Pulse + | common_enums::CardNetwork::Nyce => None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index 85125d1ddcc..25eedcd5e65 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -4305,7 +4305,12 @@ fn get_cybersource_card_type(card_network: common_enums::CardNetwork) -> Option< common_enums::CardNetwork::UnionPay => Some("062"), //"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024" common_enums::CardNetwork::Maestro => Some("042"), - common_enums::CardNetwork::Interac | common_enums::CardNetwork::RuPay => None, + common_enums::CardNetwork::Interac + | common_enums::CardNetwork::RuPay + | common_enums::CardNetwork::Star + | common_enums::CardNetwork::Accel + | common_enums::CardNetwork::Pulse + | common_enums::CardNetwork::Nyce => None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs index 0cfccd280f4..a967eefbd73 100644 --- a/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs @@ -204,7 +204,11 @@ impl TryFrom<&HipayRouterData<&PaymentsAuthorizeRouterData>> for HipayPaymentsRe Some(CardNetwork::Interac) => "interac".to_string(), Some(CardNetwork::RuPay) => "rupay".to_string(), Some(CardNetwork::Maestro) => "maestro".to_string(), - None => "".to_string(), + Some(CardNetwork::Star) + | Some(CardNetwork::Accel) + | Some(CardNetwork::Pulse) + | Some(CardNetwork::Nyce) + | None => "".to_string(), }, }, amount: item.amount.clone(), diff --git a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs index da6ec769363..73d9007706c 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs @@ -1398,7 +1398,11 @@ fn get_stripe_card_network(card_network: common_enums::CardNetwork) -> Option<St | common_enums::CardNetwork::UnionPay | common_enums::CardNetwork::Interac | common_enums::CardNetwork::RuPay - | common_enums::CardNetwork::Maestro => None, + | common_enums::CardNetwork::Maestro + | common_enums::CardNetwork::Star + | common_enums::CardNetwork::Accel + | common_enums::CardNetwork::Pulse + | common_enums::CardNetwork::Nyce => None, } } diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 9f62dbbe987..4ddb32b4d6c 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -77,6 +77,14 @@ impl PaymentMethodData { pub fn is_network_token_payment_method_data(&self) -> bool { matches!(self, Self::NetworkToken(_)) } + + pub fn get_co_badged_card_data(&self) -> Option<&payment_methods::CoBadgedCardData> { + if let Self::Card(card) = self { + card.co_badged_card_data.as_ref() + } else { + None + } + } } #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)] @@ -92,6 +100,7 @@ pub struct Card { pub bank_code: Option<String>, pub nick_name: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, + pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>, } #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)] @@ -120,6 +129,7 @@ pub struct CardDetail { pub bank_code: Option<String>, pub nick_name: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, + pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>, } impl CardDetailsForNetworkTransactionId { @@ -162,6 +172,7 @@ impl From<&Card> for CardDetail { bank_code: item.bank_code.to_owned(), nick_name: item.nick_name.to_owned(), card_holder_name: item.card_holder_name.to_owned(), + co_badged_card_data: item.co_badged_card_data.to_owned(), } } } @@ -723,6 +734,7 @@ impl TryFrom<payment_methods::PaymentMethodCreateData> for PaymentMethodData { bank_code: None, nick_name, card_holder_name, + co_badged_card_data: None, })), } } @@ -732,7 +744,7 @@ impl From<api_models::payments::PaymentMethodData> for PaymentMethodData { fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self { match api_model_payment_method_data { api_models::payments::PaymentMethodData::Card(card_data) => { - Self::Card(Card::from(card_data)) + Self::Card(Card::from((card_data, None))) } api_models::payments::PaymentMethodData::CardRedirect(card_redirect) => { Self::CardRedirect(From::from(card_redirect)) @@ -782,8 +794,18 @@ impl From<api_models::payments::PaymentMethodData> for PaymentMethodData { } } -impl From<api_models::payments::Card> for Card { - fn from(value: api_models::payments::Card) -> Self { +impl + From<( + api_models::payments::Card, + Option<payment_methods::CoBadgedCardData>, + )> for Card +{ + fn from( + (value, co_badged_card_data_optional): ( + api_models::payments::Card, + Option<payment_methods::CoBadgedCardData>, + ), + ) -> Self { let api_models::payments::Card { card_number, card_exp_month, @@ -810,6 +832,7 @@ impl From<api_models::payments::Card> for Card { bank_code, nick_name, card_holder_name, + co_badged_card_data: co_badged_card_data_optional, } } } @@ -1875,6 +1898,16 @@ pub enum PaymentMethodsData { NetworkToken(NetworkTokenDetailsPaymentMethod), } +impl PaymentMethodsData { + pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData> { + if let Self::Card(card) = self { + card.co_badged_card_data.clone() + } else { + None + } + } +} + #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct NetworkTokenDetailsPaymentMethod { pub last4_digits: Option<String>, @@ -1909,6 +1942,7 @@ pub struct CardDetailsPaymentMethod { pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] pub saved_to_locker: bool, + pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] @@ -1926,6 +1960,7 @@ impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod { card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, + co_badged_card_data: None, } } } diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs index 955d01c94df..de7d9641449 100644 --- a/crates/hyperswitch_domain_models/src/payment_methods.rs +++ b/crates/hyperswitch_domain_models/src/payment_methods.rs @@ -12,7 +12,11 @@ use common_utils::{ }; use diesel_models::{enums as storage_enums, PaymentMethodUpdate}; use error_stack::ResultExt; +#[cfg(feature = "v1")] +use masking::ExposeInterface; use masking::{PeekInterface, Secret}; +#[cfg(feature = "v1")] +use router_env::logger; #[cfg(feature = "v2")] use rustc_hash::FxHashMap; #[cfg(feature = "v2")] @@ -20,13 +24,11 @@ use serde_json::Value; use time::PrimitiveDateTime; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -use crate::{ - address::Address, payment_method_data as domain_payment_method_data, - type_encryption::OptionalEncryptableJsonType, -}; +use crate::{address::Address, type_encryption::OptionalEncryptableJsonType}; use crate::{ mandates::{self, CommonMandateReference}, merchant_key_store::MerchantKeyStore, + payment_method_data as domain_payment_method_data, type_encryption::{crypto_operation, AsyncLift, CryptoOperation}, }; @@ -131,6 +133,25 @@ impl PaymentMethod { &self.payment_method_id } + #[cfg(feature = "v1")] + pub fn get_payment_methods_data( + &self, + ) -> Option<domain_payment_method_data::PaymentMethodsData> { + self.payment_method_data + .clone() + .map(|value| value.into_inner().expose()) + .and_then(|value| { + serde_json::from_value::<domain_payment_method_data::PaymentMethodsData>(value) + .map_err(|error| { + logger::warn!( + ?error, + "Failed to parse payment method data in payment method info" + ); + }) + .ok() + }) + } + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub fn get_id(&self) -> &id_type::GlobalPaymentMethodId { &self.id diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 93e4f8e0408..1b5d3392aa2 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -325,6 +325,10 @@ impl IntoDirValue for api_enums::CardNetwork { Self::Interac => Ok(dirval!(CardNetwork = Interac)), Self::RuPay => Ok(dirval!(CardNetwork = RuPay)), Self::Maestro => Ok(dirval!(CardNetwork = Maestro)), + Self::Star => Ok(dirval!(CardNetwork = Star)), + Self::Accel => Ok(dirval!(CardNetwork = Accel)), + Self::Pulse => Ok(dirval!(CardNetwork = Pulse)), + Self::Nyce => Ok(dirval!(CardNetwork = Nyce)), } } } diff --git a/crates/payment_methods/src/core/migration/payment_methods.rs b/crates/payment_methods/src/core/migration/payment_methods.rs index 3dc8f3a5e5d..a957d2375b4 100644 --- a/crates/payment_methods/src/core/migration/payment_methods.rs +++ b/crates/payment_methods/src/core/migration/payment_methods.rs @@ -540,8 +540,9 @@ pub async fn skip_locker_call_and_migrate_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; - let payment_method_card_details = - pm_api::PaymentMethodsData::Card(pm_api::CardDetailsPaymentMethod::from(card.clone())); + let payment_method_card_details = pm_api::PaymentMethodsData::Card( + pm_api::CardDetailsPaymentMethod::from((card.clone(), None)), + ); let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = Some( create_encrypted_data( diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 12cc03eb929..49800dd3c89 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -536,6 +536,7 @@ pub(crate) async fn fetch_raw_secrets( platform: conf.platform, authentication_providers: conf.authentication_providers, open_router: conf.open_router, + debit_routing_config: conf.debit_routing_config, clone_connector_allowlist: conf.clone_connector_allowlist, } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index c0f2d680d37..34270971efb 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -115,6 +115,7 @@ pub struct Settings<S: SecretState> { #[cfg(feature = "payouts")] pub payouts: Payouts, pub payout_method_filters: ConnectorFilters, + pub debit_routing_config: DebitRoutingConfig, pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConfig, S>, pub paze_decrypt_keys: Option<SecretStateContainer<PazeDecryptConfig, S>>, pub google_pay_decrypt_keys: Option<GooglePayDecryptConfig>, @@ -156,6 +157,16 @@ pub struct Settings<S: SecretState> { pub clone_connector_allowlist: Option<CloneConnectorAllowlistConfig>, } +#[derive(Debug, Deserialize, Clone, Default)] +pub struct DebitRoutingConfig { + #[serde(deserialize_with = "deserialize_hashmap")] + pub connector_supported_debit_networks: HashMap<enums::Connector, HashSet<enums::CardNetwork>>, + #[serde(deserialize_with = "deserialize_hashset")] + pub supported_currencies: HashSet<enums::Currency>, + #[serde(deserialize_with = "deserialize_hashset")] + pub supported_connectors: HashSet<enums::Connector>, +} + #[derive(Debug, Deserialize, Clone, Default)] pub struct OpenRouter { pub enabled: bool, diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index e96aa339e9e..db2122b242c 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -45,6 +45,8 @@ pub mod refunds; #[cfg(feature = "v2")] pub mod refunds_v2; +#[cfg(feature = "v1")] +pub mod debit_routing; pub mod routing; pub mod surcharge_decision_config; #[cfg(feature = "olap")] diff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rs index 71cc4bd840f..0e7315c5d4a 100644 --- a/crates/router/src/core/authentication/utils.rs +++ b/crates/router/src/core/authentication/utils.rs @@ -24,28 +24,30 @@ pub fn get_connector_data_if_separate_authn_supported( connector_call_type: &api::ConnectorCallType, ) -> Option<api::ConnectorData> { match connector_call_type { - api::ConnectorCallType::PreDetermined(connector_data) => { - if connector_data + api::ConnectorCallType::PreDetermined(connector_routing_data) => { + if connector_routing_data + .connector_data .connector_name .is_separate_authentication_supported() { - Some(connector_data.clone()) + Some(connector_routing_data.connector_data.clone()) } else { None } } - api::ConnectorCallType::Retryable(connectors) => { - connectors.first().and_then(|connector_data| { - if connector_data + api::ConnectorCallType::Retryable(connector_routing_data) => connector_routing_data + .first() + .and_then(|connector_routing_data| { + if connector_routing_data + .connector_data .connector_name .is_separate_authentication_supported() { - Some(connector_data.clone()) + Some(connector_routing_data.connector_data.clone()) } else { None } - }) - } + }), api::ConnectorCallType::SessionMultiple(_) => None, } } diff --git a/crates/router/src/core/debit_routing.rs b/crates/router/src/core/debit_routing.rs new file mode 100644 index 00000000000..5824946c3e7 --- /dev/null +++ b/crates/router/src/core/debit_routing.rs @@ -0,0 +1,460 @@ +use std::{collections::HashSet, fmt::Debug}; + +use api_models::{enums as api_enums, open_router}; +use common_enums::enums; +use common_utils::id_type; +use error_stack::ResultExt; +use masking::Secret; + +use super::{ + payments::{OperationSessionGetters, OperationSessionSetters}, + routing::TransactionData, +}; +use crate::{ + core::{ + errors, + payments::{operations::BoxedOperation, routing}, + }, + logger, + routes::SessionState, + settings, + types::{ + api::{self, ConnectorCallType}, + domain, + }, +}; + +pub struct DebitRoutingResult { + pub debit_routing_connector_call_type: ConnectorCallType, + pub debit_routing_output: open_router::DebitRoutingOutput, +} + +pub async fn perform_debit_routing<F, Req, D>( + operation: &BoxedOperation<'_, F, Req, D>, + state: &SessionState, + business_profile: &domain::Profile, + payment_data: &mut D, + connector: Option<ConnectorCallType>, +) -> ( + Option<ConnectorCallType>, + Option<open_router::DebitRoutingOutput>, +) +where + F: Send + Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, +{ + let mut debit_routing_output = None; + + if should_execute_debit_routing(state, business_profile, operation, payment_data).await { + let debit_routing_config = state.conf.debit_routing_config.clone(); + let debit_routing_supported_connectors = debit_routing_config.supported_connectors.clone(); + + if let Some((call_connector_type, acquirer_country)) = connector + .clone() + .zip(business_profile.merchant_business_country) + { + debit_routing_output = match call_connector_type { + ConnectorCallType::PreDetermined(connector_data) => { + logger::info!("Performing debit routing for PreDetermined connector"); + handle_pre_determined_connector( + state, + &debit_routing_config, + debit_routing_supported_connectors, + &connector_data, + payment_data, + acquirer_country, + ) + .await + } + ConnectorCallType::Retryable(connector_data) => { + logger::info!("Performing debit routing for Retryable connector"); + handle_retryable_connector( + state, + &debit_routing_config, + debit_routing_supported_connectors, + connector_data, + payment_data, + acquirer_country, + ) + .await + } + ConnectorCallType::SessionMultiple(_) => { + logger::info!( + "SessionMultiple connector type is not supported for debit routing" + ); + None + } + #[cfg(feature = "v2")] + ConnectorCallType::Skip => { + logger::info!("Skip connector type is not supported for debit routing"); + None + } + }; + } + } + + if let Some(debit_routing_output) = debit_routing_output { + ( + Some(debit_routing_output.debit_routing_connector_call_type), + Some(debit_routing_output.debit_routing_output), + ) + } else { + // If debit_routing_output is None, return the static routing output (connector) + logger::info!("Debit routing is not performed, returning static routing output"); + (connector, None) + } +} + +async fn should_execute_debit_routing<F, Req, D>( + state: &SessionState, + business_profile: &domain::Profile, + operation: &BoxedOperation<'_, F, Req, D>, + payment_data: &D, +) -> bool +where + F: Send + Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, +{ + if business_profile.is_debit_routing_enabled + && state.conf.open_router.enabled + && business_profile.merchant_business_country.is_some() + { + logger::info!("Debit routing is enabled for the profile"); + + let debit_routing_config = &state.conf.debit_routing_config; + + if should_perform_debit_routing_for_the_flow(operation, payment_data, debit_routing_config) + { + let is_debit_routable_connector_present = check_for_debit_routing_connector_in_profile( + state, + business_profile.get_id(), + payment_data, + ) + .await; + + if is_debit_routable_connector_present { + logger::debug!("Debit routable connector is configured for the profile"); + return true; + } + } + } + false +} + +pub fn should_perform_debit_routing_for_the_flow<Op: Debug, F: Clone, D>( + operation: &Op, + payment_data: &D, + debit_routing_config: &settings::DebitRoutingConfig, +) -> bool +where + D: OperationSessionGetters<F> + Send + Sync + Clone, +{ + match format!("{operation:?}").as_str() { + "PaymentConfirm" => { + logger::info!("Checking if debit routing is required"); + let payment_intent = payment_data.get_payment_intent(); + let payment_attempt = payment_data.get_payment_attempt(); + + request_validation(payment_intent, payment_attempt, debit_routing_config) + } + _ => false, + } +} + +pub fn request_validation( + payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, + payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, + debit_routing_config: &settings::DebitRoutingConfig, +) -> bool { + logger::debug!("Validating request for debit routing"); + let is_currency_supported = payment_intent.currency.map(|currency| { + debit_routing_config + .supported_currencies + .contains(&currency) + }); + + payment_intent.setup_future_usage != Some(enums::FutureUsage::OffSession) + && payment_intent.amount.is_greater_than(0) + && is_currency_supported == Some(true) + && payment_attempt.authentication_type != Some(enums::AuthenticationType::ThreeDs) + && payment_attempt.payment_method == Some(enums::PaymentMethod::Card) + && payment_attempt.payment_method_type == Some(enums::PaymentMethodType::Debit) +} + +pub async fn check_for_debit_routing_connector_in_profile< + F: Clone, + D: OperationSessionGetters<F>, +>( + state: &SessionState, + business_profile_id: &id_type::ProfileId, + payment_data: &D, +) -> bool { + logger::debug!("Checking for debit routing connector in profile"); + let debit_routing_supported_connectors = + state.conf.debit_routing_config.supported_connectors.clone(); + + let transaction_data = super::routing::PaymentsDslInput::new( + payment_data.get_setup_mandate(), + payment_data.get_payment_attempt(), + payment_data.get_payment_intent(), + payment_data.get_payment_method_data(), + payment_data.get_address(), + payment_data.get_recurring_details(), + payment_data.get_currency(), + ); + + let fallback_config_optional = super::routing::helpers::get_merchant_default_config( + &*state.clone().store, + business_profile_id.get_string_repr(), + &enums::TransactionType::from(&TransactionData::Payment(transaction_data)), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .map_err(|error| { + logger::warn!(?error, "Failed to fetch default connector for a profile"); + }) + .ok(); + + let is_debit_routable_connector_present = fallback_config_optional + .map(|fallback_config| { + fallback_config.iter().any(|fallback_config_connector| { + debit_routing_supported_connectors.contains(&api_enums::Connector::from( + fallback_config_connector.connector, + )) + }) + }) + .unwrap_or(false); + + is_debit_routable_connector_present +} + +async fn handle_pre_determined_connector<F, D>( + state: &SessionState, + debit_routing_config: &settings::DebitRoutingConfig, + debit_routing_supported_connectors: HashSet<api_enums::Connector>, + connector_data: &api::ConnectorRoutingData, + payment_data: &mut D, + acquirer_country: enums::CountryAlpha2, +) -> Option<DebitRoutingResult> +where + F: Send + Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, +{ + if debit_routing_supported_connectors.contains(&connector_data.connector_data.connector_name) { + logger::debug!("Chosen connector is supported for debit routing"); + + let debit_routing_output = + get_debit_routing_output::<F, D>(state, payment_data, acquirer_country).await?; + + logger::debug!( + "Sorted co-badged networks: {:?}", + debit_routing_output.co_badged_card_networks + ); + + let valid_connectors = build_connector_routing_data( + connector_data, + debit_routing_config, + &debit_routing_output.co_badged_card_networks, + ); + + if !valid_connectors.is_empty() { + return Some(DebitRoutingResult { + debit_routing_connector_call_type: ConnectorCallType::Retryable(valid_connectors), + debit_routing_output, + }); + } + } + + None +} + +pub async fn get_debit_routing_output< + F: Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F>, +>( + state: &SessionState, + payment_data: &mut D, + acquirer_country: enums::CountryAlpha2, +) -> Option<open_router::DebitRoutingOutput> { + logger::debug!("Fetching sorted card networks"); + let payment_attempt = payment_data.get_payment_attempt(); + + let (saved_co_badged_card_data, saved_card_type, card_isin) = + extract_saved_card_info(payment_data); + + match ( + saved_co_badged_card_data + .clone() + .zip(saved_card_type.clone()), + card_isin.clone(), + ) { + (None, None) => { + logger::debug!("Neither co-badged data nor ISIN found; skipping routing"); + None + } + _ => { + let co_badged_card_data = saved_co_badged_card_data + .zip(saved_card_type) + .and_then(|(co_badged, card_type)| { + open_router::DebitRoutingRequestData::try_from((co_badged, card_type)) + .map(Some) + .map_err(|error| { + logger::warn!("Failed to convert co-badged card data: {:?}", error); + }) + .ok() + }) + .flatten(); + + if co_badged_card_data.is_none() && card_isin.is_none() { + logger::debug!("Neither co-badged data nor ISIN found; skipping routing"); + return None; + } + + let co_badged_card_request = open_router::CoBadgedCardRequest { + merchant_category_code: enums::MerchantCategoryCode::Mcc0001, + acquirer_country, + co_badged_card_data, + }; + + routing::perform_open_routing_for_debit_routing( + state, + payment_attempt, + co_badged_card_request, + card_isin, + ) + .await + .map_err(|error| { + logger::warn!(?error, "Debit routing call to open router failed"); + }) + .ok() + } + } +} + +fn extract_saved_card_info<F, D>( + payment_data: &D, +) -> ( + Option<api_models::payment_methods::CoBadgedCardData>, + Option<String>, + Option<Secret<String>>, +) +where + D: OperationSessionGetters<F>, +{ + let payment_method_data_optional = payment_data.get_payment_method_data(); + match payment_data + .get_payment_method_info() + .and_then(|info| info.get_payment_methods_data()) + { + Some(hyperswitch_domain_models::payment_method_data::PaymentMethodsData::Card(card)) => { + match (&card.co_badged_card_data, &card.card_isin) { + (Some(co_badged), _) => { + logger::debug!("Co-badged card data found in saved payment method"); + (Some(co_badged.clone()), card.card_type, None) + } + (None, Some(card_isin)) => { + logger::debug!("No co-badged data; using saved card ISIN"); + (None, None, Some(Secret::new(card_isin.clone()))) + } + _ => (None, None, None), + } + } + _ => match payment_method_data_optional { + Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(card)) => { + logger::debug!("Using card data from payment request"); + ( + None, + None, + Some(Secret::new(card.card_number.get_card_isin())), + ) + } + _ => (None, None, None), + }, + } +} + +fn check_connector_support_for_network( + debit_routing_config: &settings::DebitRoutingConfig, + connector_name: api_enums::Connector, + network: &enums::CardNetwork, +) -> Option<enums::CardNetwork> { + debit_routing_config + .connector_supported_debit_networks + .get(&connector_name) + .and_then(|supported_networks| { + (supported_networks.contains(network) || network.is_global_network()) + .then(|| network.clone()) + }) +} + +fn build_connector_routing_data( + connector_data: &api::ConnectorRoutingData, + debit_routing_config: &settings::DebitRoutingConfig, + fee_sorted_debit_networks: &[enums::CardNetwork], +) -> Vec<api::ConnectorRoutingData> { + fee_sorted_debit_networks + .iter() + .filter_map(|network| { + check_connector_support_for_network( + debit_routing_config, + connector_data.connector_data.connector_name, + network, + ) + .map(|valid_network| api::ConnectorRoutingData { + connector_data: connector_data.connector_data.clone(), + network: Some(valid_network), + }) + }) + .collect() +} + +async fn handle_retryable_connector<F, D>( + state: &SessionState, + debit_routing_config: &settings::DebitRoutingConfig, + debit_routing_supported_connectors: HashSet<api_enums::Connector>, + connector_data_list: Vec<api::ConnectorRoutingData>, + payment_data: &mut D, + acquirer_country: enums::CountryAlpha2, +) -> Option<DebitRoutingResult> +where + F: Send + Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, +{ + let is_any_debit_routing_connector_supported = + connector_data_list.iter().any(|connector_data| { + debit_routing_supported_connectors + .contains(&connector_data.connector_data.connector_name) + }); + + if is_any_debit_routing_connector_supported { + let debit_routing_output = + get_debit_routing_output::<F, D>(state, payment_data, acquirer_country).await?; + + logger::debug!( + "Sorted co-badged networks: {:?}", + debit_routing_output.co_badged_card_networks + ); + + let supported_connectors: Vec<_> = connector_data_list + .iter() + .flat_map(|connector_data| { + build_connector_routing_data( + connector_data, + debit_routing_config, + &debit_routing_output.co_badged_card_networks, + ) + }) + .collect(); + + if !supported_connectors.is_empty() { + return Some(DebitRoutingResult { + debit_routing_connector_call_type: ConnectorCallType::Retryable( + supported_connectors, + ), + debit_routing_output, + }); + } + } + + None +} diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 221390e573f..0b4590b2bec 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -780,6 +780,11 @@ pub(crate) async fn get_payment_method_create_request( Some(pm_data) => match payment_method { Some(payment_method) => match pm_data { domain::PaymentMethodData::Card(card) => { + let card_network = get_card_network_with_us_local_debit_network_override( + card.card_network.clone(), + card.co_badged_card_data.as_ref(), + ); + let card_detail = payment_methods::CardDetail { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), @@ -787,7 +792,7 @@ pub(crate) async fn get_payment_method_create_request( card_holder_name: billing_name, nick_name: card.nick_name.clone(), card_issuing_country: card.card_issuing_country.clone(), - card_network: card.card_network.clone(), + card_network: card_network.clone(), card_issuer: card.card_issuer.clone(), card_type: card.card_type.clone(), }; @@ -803,8 +808,8 @@ pub(crate) async fn get_payment_method_create_request( card: Some(card_detail), metadata: None, customer_id: customer_id.clone(), - card_network: card - .card_network + card_network: card_network + .clone() .as_ref() .map(|card_network| card_network.to_string()), client_secret: None, @@ -852,6 +857,32 @@ pub(crate) async fn get_payment_method_create_request( } } +/// Determines the appropriate card network to to be stored. +/// +/// If the provided card network is a US local network, this function attempts to +/// override it with the first global network from the co-badged card data, if available. +/// Otherwise, it returns the original card network as-is. +/// +fn get_card_network_with_us_local_debit_network_override( + card_network: Option<common_enums::CardNetwork>, + co_badged_card_data: Option<&payment_methods::CoBadgedCardData>, +) -> Option<common_enums::CardNetwork> { + if let Some(true) = card_network + .as_ref() + .map(|network| network.is_us_local_network()) + { + services::logger::debug!("Card network is a US local network, checking for global network in co-badged card data"); + co_badged_card_data.and_then(|data| { + data.co_badged_card_networks + .iter() + .find(|network| network.is_global_network()) + .cloned() + }) + } else { + card_network + } +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn create_payment_method( diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index a11562c7c26..6c2c2cb0739 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -424,7 +424,7 @@ impl PaymentMethodsController for PmCards<'_> { logger::debug!("Network token added to locker"); let (token_pm_resp, _duplication_check) = resp; let pm_token_details = token_pm_resp.card.as_ref().map(|card| { - PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) + PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None))) }); let pm_network_token_data_encrypted = pm_token_details .async_map(|pm_card| { @@ -502,10 +502,9 @@ impl PaymentMethodsController for PmCards<'_> { network_token_locker_id: Option<String>, network_token_payment_method_data: crypto::OptionalEncryptableValue, ) -> errors::RouterResult<domain::PaymentMethod> { - let pm_card_details = resp - .card - .clone() - .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); + let pm_card_details = resp.card.clone().map(|card| { + PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None))) + }); let key_manager_state = self.state.into(); let pm_data_encrypted: crypto::OptionalEncryptableValue = pm_card_details .clone() @@ -1278,7 +1277,10 @@ impl PaymentMethodsController for PmCards<'_> { }); let updated_pmd = updated_card.as_ref().map(|card| { - PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) + PaymentMethodsData::Card(CardDetailsPaymentMethod::from(( + card.clone(), + None, + ))) }); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd @@ -1593,6 +1595,7 @@ pub async fn add_payment_method_data( card_issuer: card_info.as_ref().and_then(|ci| ci.card_issuer.clone()), card_type: card_info.as_ref().and_then(|ci| ci.card_type.clone()), saved_to_locker: true, + co_badged_card_data: None, }; let pm_data_encrypted: Encryptable<Secret<serde_json::Value>> = create_encrypted_data( @@ -1836,9 +1839,9 @@ pub async fn update_customer_payment_method( saved_to_locker: true, }); - let updated_pmd = updated_card - .as_ref() - .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); + let updated_pmd = updated_card.as_ref().map(|card| { + PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None))) + }); let key_manager_state = (&state).into(); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd .async_map(|updated_pmd| { diff --git a/crates/router/src/core/payment_methods/tokenize.rs b/crates/router/src/core/payment_methods/tokenize.rs index cc27e813b5c..98eca478c93 100644 --- a/crates/router/src/core/payment_methods/tokenize.rs +++ b/crates/router/src/core/payment_methods/tokenize.rs @@ -272,6 +272,7 @@ where card_network: card_details.card_network.clone(), card_type: card_details.card_type.clone(), saved_to_locker, + co_badged_card_data: card_details.co_badged_card_data.clone(), }); create_encrypted_data(&self.state.into(), self.key_store, pm_data) .await @@ -297,6 +298,7 @@ where card_network: card_details.card_network.clone(), card_type: card_details.card_type.clone(), saved_to_locker, + co_badged_card_data: None, }); create_encrypted_data(&self.state.into(), self.key_store, token_data) .await diff --git a/crates/router/src/core/payment_methods/tokenize/card_executor.rs b/crates/router/src/core/payment_methods/tokenize/card_executor.rs index b714bdb9a6b..2537a244a58 100644 --- a/crates/router/src/core/payment_methods/tokenize/card_executor.rs +++ b/crates/router/src/core/payment_methods/tokenize/card_executor.rs @@ -132,6 +132,7 @@ impl<'a> NetworkTokenizationBuilder<'a, CardRequestValidated> { .map_or(card_req.card_issuing_country.clone(), |card_info| { card_info.card_issuing_country.clone() }), + co_badged_card_data: None, }; NetworkTokenizationBuilder { state: std::marker::PhantomData, diff --git a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs index 2249434b107..a55896b36c5 100644 --- a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs +++ b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs @@ -151,6 +151,7 @@ impl<'a> NetworkTokenizationBuilder<'a, PmValidated> { card_issuing_country: optional_card_info .as_ref() .and_then(|card_info| card_info.card_issuing_country.clone()), + co_badged_card_data: None, }; NetworkTokenizationBuilder { state: std::marker::PhantomData, diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 2231f7d89f6..af60d07a466 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -121,6 +121,7 @@ impl Vaultable for domain::Card { card_type: None, nick_name: value1.nickname.map(masking::Secret::new), card_holder_name: value1.card_holder_name, + co_badged_card_data: None, }; let supp_data = SupplementaryVaultData { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index d166bc41a24..cb68ece2039 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -88,9 +88,11 @@ use self::{ use super::{ errors::StorageErrorExt, payment_methods::surcharge_decision_configs, routing::TransactionData, }; +#[cfg(feature = "v1")] +use crate::core::debit_routing; #[cfg(feature = "frm")] use crate::core::fraud_check as frm_core; -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[cfg(feature = "v1")] use crate::core::routing::helpers as routing_helpers; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use crate::types::api::convert_connector_data_to_routable_connectors; @@ -197,7 +199,7 @@ where state, req_state.clone(), &merchant_context, - connector_data.clone(), + connector_data.connector_data.clone(), &operation, &mut payment_data, &customer, @@ -353,6 +355,15 @@ where ) .await?; + let (connector, debit_routing_output) = debit_routing::perform_debit_routing( + &operation, + state, + &business_profile, + &mut payment_data, + connector, + ) + .await; + let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data); let locale = header_payload.locale.clone(); @@ -487,7 +498,7 @@ where let schedule_time = if should_add_task_to_process_tracker { payment_sync::get_sync_process_schedule_time( &*state.store, - connector.connector.id(), + connector.connector_data.connector.id(), merchant_context.get_merchant_account().get_id(), 0, ) @@ -501,7 +512,7 @@ where state, req_state.clone(), merchant_context, - connector.clone(), + connector.connector_data.clone(), &operation, &mut payment_data, &customer, @@ -516,6 +527,7 @@ where &business_profile, false, false, + None, ) .await?; @@ -579,7 +591,7 @@ where merchant_context, &customer, &mca, - connector, + &connector.connector_data, &mut payment_data, op_ref, Some(header_payload.clone()), @@ -599,7 +611,12 @@ where let mut connectors = connectors.clone().into_iter(); - let connector_data = get_connector_data(&mut connectors)?; + let (connector_data, routing_decision) = + get_connector_data_with_routing_decision( + &mut connectors, + &business_profile, + debit_routing_output, + )?; let schedule_time = if should_add_task_to_process_tracker { payment_sync::get_sync_process_schedule_time( @@ -633,6 +650,7 @@ where &business_profile, false, false, + routing_decision, ) .await?; @@ -1018,9 +1036,10 @@ where add_connector_http_status_code_metrics(connector_http_status_code); #[cfg(all(feature = "dynamic_routing", feature = "v1"))] - let routable_connectors = convert_connector_data_to_routable_connectors(&[connector.clone()]) - .map_err(|e| logger::error!(routable_connector_error=?e)) - .unwrap_or_default(); + let routable_connectors = + convert_connector_data_to_routable_connectors(&[connector.clone().into()]) + .map_err(|e| logger::error!(routable_connector_error=?e)) + .unwrap_or_default(); let mut payment_data = operation .to_post_update_tracker()? @@ -1126,7 +1145,7 @@ where state, req_state.clone(), &merchant_context, - connector_data.clone(), + connector_data.connector_data.clone(), &operation, &mut payment_data, call_connector_action.clone(), @@ -1404,14 +1423,50 @@ where #[inline] pub fn get_connector_data( - connectors: &mut IntoIter<api::ConnectorData>, -) -> RouterResult<api::ConnectorData> { + connectors: &mut IntoIter<api::ConnectorRoutingData>, +) -> RouterResult<api::ConnectorRoutingData> { connectors .next() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Connector not found in connectors iterator") } +#[cfg(feature = "v1")] +pub fn get_connector_with_networks( + connectors: &mut IntoIter<api::ConnectorRoutingData>, +) -> Option<(api::ConnectorData, enums::CardNetwork)> { + connectors.find_map(|connector| { + connector + .network + .map(|network| (connector.connector_data, network)) + }) +} + +#[cfg(feature = "v1")] +fn get_connector_data_with_routing_decision( + connectors: &mut IntoIter<api::ConnectorRoutingData>, + business_profile: &domain::Profile, + debit_routing_output_optional: Option<api_models::open_router::DebitRoutingOutput>, +) -> RouterResult<( + api::ConnectorData, + Option<routing_helpers::RoutingDecisionData>, +)> { + if business_profile.is_debit_routing_enabled && debit_routing_output_optional.is_some() { + if let Some((data, card_network)) = get_connector_with_networks(connectors) { + let debit_routing_output = + debit_routing_output_optional.get_required_value("debit routing output")?; + let routing_decision = + routing_helpers::RoutingDecisionData::get_debit_routing_decision_data( + card_network, + debit_routing_output, + ); + return Ok((data, Some(routing_decision))); + } + } + + Ok((get_connector_data(connectors)?.connector_data, None)) +} + #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn call_surcharge_decision_management_for_session_flow( @@ -3013,6 +3068,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>( business_profile: &domain::Profile, is_retry_payment: bool, should_retry_with_pan: bool, + routing_decision: Option<routing_helpers::RoutingDecisionData>, ) -> RouterResult<( RouterData<F, RouterDReq, router_types::PaymentsResponseData>, helpers::MerchantConnectorAccountType, @@ -3075,6 +3131,10 @@ where .await?; *payment_data = pd; + // This is used to apply any kind of routing decision to the required data, + // before the call to `connector` is made. + routing_decision.map(|decision| decision.apply_routing_decision(payment_data)); + // Validating the blocklist guard and generate the fingerprint blocklist_guard(state, merchant_context, operation, payment_data).await?; @@ -6434,7 +6494,7 @@ where .attach_printable("Invalid connector name received in 'routed_through'")?; routing_data.routed_through = Some(connector_name.clone()); - return Ok(ConnectorCallType::PreDetermined(connector_data)); + return Ok(ConnectorCallType::PreDetermined(connector_data.into())); } if let Some(mandate_connector_details) = payment_data.get_mandate_connector().as_ref() { @@ -6453,7 +6513,7 @@ where .merchant_connector_id .clone_from(&mandate_connector_details.merchant_connector_id); - return Ok(ConnectorCallType::PreDetermined(connector_data)); + return Ok(ConnectorCallType::PreDetermined(connector_data.into())); } if let Some((pre_routing_results, storage_pm_type)) = @@ -6497,7 +6557,8 @@ where connector_choice.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Invalid connector name received")?; + .attach_printable("Invalid connector name received")? + .into(); pre_routing_connector_data_list.push(connector_data); } @@ -6664,7 +6725,7 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone state: &SessionState, payment_data: &mut D, routing_data: &mut storage::RoutingData, - connectors: Vec<api::ConnectorData>, + connectors: Vec<api::ConnectorRoutingData>, mandate_type: Option<api::MandateTransactionType>, is_connector_agnostic_mit_enabled: Option<bool>, is_network_tokenization_enabled: bool, @@ -6751,12 +6812,16 @@ where "no eligible connector found for token-based MIT payment", )?; - routing_data.routed_through = - Some(chosen_connector_data.connector_name.to_string()); + routing_data.routed_through = Some( + chosen_connector_data + .connector_data + .connector_name + .to_string(), + ); routing_data .merchant_connector_id - .clone_from(&chosen_connector_data.merchant_connector_id); + .clone_from(&chosen_connector_data.connector_data.merchant_connector_id); payment_data.set_mandate_id(payments_api::MandateIds { mandate_id: None, @@ -6788,16 +6853,20 @@ where Some(api::MandateTransactionType::RecurringMandateTransaction), ) => { if let Some(connector) = connectors.first() { + let connector = &connector.connector_data; routing_data.routed_through = Some(connector.connector_name.clone().to_string()); routing_data .merchant_connector_id .clone_from(&connector.merchant_connector_id); - Ok(ConnectorCallType::PreDetermined(api::ConnectorData { - connector: connector.connector.clone(), - connector_name: connector.connector_name, - get_token: connector.get_token.clone(), - merchant_connector_id: connector.merchant_connector_id.clone(), - })) + Ok(ConnectorCallType::PreDetermined( + api::ConnectorData { + connector: connector.connector.clone(), + connector_name: connector.connector_name, + get_token: connector.get_token.clone(), + merchant_connector_id: connector.merchant_connector_id.clone(), + } + .into(), + )) } else { logger::error!("no eligible connector found for the ppt_mandate payment"); Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration.into()) @@ -6813,9 +6882,10 @@ where .attach_printable("no eligible connector found for payment")? .clone(); - routing_data.routed_through = Some(first_choice.connector_name.to_string()); + routing_data.routed_through = + Some(first_choice.connector_data.connector_name.to_string()); - routing_data.merchant_connector_id = first_choice.merchant_connector_id; + routing_data.merchant_connector_id = first_choice.connector_data.merchant_connector_id; Ok(ConnectorCallType::Retryable(connectors)) } @@ -6847,7 +6917,7 @@ pub async fn decide_connector_for_normal_or_recurring_payment<F: Clone, D>( state: &SessionState, payment_data: &mut D, routing_data: &mut storage::RoutingData, - connectors: Vec<api::ConnectorData>, + connectors: Vec<api::ConnectorRoutingData>, is_connector_agnostic_mit_enabled: Option<bool>, payment_method_info: &domain::PaymentMethod, ) -> RouterResult<ConnectorCallType> @@ -6863,7 +6933,8 @@ where let mut connector_choice = None; - for connector_data in connectors { + for connector_info in connectors { + let connector_data = connector_info.connector_data; let merchant_connector_id = connector_data .merchant_connector_id .as_ref() @@ -6897,11 +6968,12 @@ where )?; let mandate_reference_id = Some(payments_api::MandateReferenceId::ConnectorMandateId( api_models::payments::ConnectorMandateReferenceId::new( - Some(mandate_reference_record.connector_mandate_id.clone()), // connector_mandate_id - Some(payment_method_info.get_id().clone()), // payment_method_id - None, // update_history - mandate_reference_record.mandate_metadata.clone(), // mandate_metadata - mandate_reference_record.connector_mandate_request_reference_id.clone(), // connector_mandate_request_reference_id + Some(mandate_reference_record.connector_mandate_id.clone()), + Some(payment_method_info.get_id().clone()), + // update_history + None, + mandate_reference_record.mandate_metadata.clone(), + mandate_reference_record.connector_mandate_request_reference_id.clone(), ) )); payment_data.set_recurring_mandate_payment_data( @@ -6959,16 +7031,18 @@ where mandate_reference_id, }); - Ok(ConnectorCallType::PreDetermined(chosen_connector_data)) + Ok(ConnectorCallType::PreDetermined( + chosen_connector_data.into(), + )) } pub fn filter_ntid_supported_connectors( - connectors: Vec<api::ConnectorData>, + connectors: Vec<api::ConnectorRoutingData>, ntid_supported_connectors: &HashSet<enums::Connector>, -) -> Vec<api::ConnectorData> { +) -> Vec<api::ConnectorRoutingData> { connectors .into_iter() - .filter(|data| ntid_supported_connectors.contains(&data.connector_name)) + .filter(|data| ntid_supported_connectors.contains(&data.connector_data.connector_name)) .collect() } @@ -6991,12 +7065,14 @@ pub enum ActionType { } pub fn filter_network_tokenization_supported_connectors( - connectors: Vec<api::ConnectorData>, + connectors: Vec<api::ConnectorRoutingData>, network_tokenization_supported_connectors: &HashSet<enums::Connector>, -) -> Vec<api::ConnectorData> { +) -> Vec<api::ConnectorRoutingData> { connectors .into_iter() - .filter(|data| network_tokenization_supported_connectors.contains(&data.connector_name)) + .filter(|data| { + network_tokenization_supported_connectors.contains(&data.connector_data.connector_name) + }) .collect() } @@ -7006,7 +7082,7 @@ pub async fn decide_action_type( is_connector_agnostic_mit_enabled: Option<bool>, is_network_tokenization_enabled: bool, payment_method_info: &domain::PaymentMethod, - filtered_nt_supported_connectors: Vec<api::ConnectorData>, //network tokenization supported connectors + filtered_nt_supported_connectors: Vec<api::ConnectorRoutingData>, //network tokenization supported connectors ) -> Option<ActionType> { match ( is_network_token_with_network_transaction_id_flow( @@ -7351,6 +7427,7 @@ where api::GetToken::Connector, conn.merchant_connector_id, ) + .map(|connector_data| connector_data.into()) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -7440,6 +7517,7 @@ pub async fn route_connector_v1_for_payouts( api::GetToken::Connector, conn.merchant_connector_id, ) + .map(|connector_data| connector_data.into()) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -7970,7 +8048,6 @@ pub trait PaymentMethodChecker<F> { fn should_update_in_post_update_tracker(&self) -> bool; fn should_update_in_update_tracker(&self) -> bool; } - #[cfg(feature = "v1")] impl<F: Clone> PaymentMethodChecker<F> for PaymentData<F> { fn should_update_in_post_update_tracker(&self) -> bool { @@ -8066,6 +8143,11 @@ pub trait OperationSessionSetters<F> { &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ); + fn set_card_network(&mut self, card_network: enums::CardNetwork); + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ); #[cfg(feature = "v1")] fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod); fn set_frm_message(&mut self, frm_message: FraudCheck); @@ -8298,6 +8380,31 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> { self.payment_attempt.merchant_connector_id = merchant_connector_id; } + fn set_card_network(&mut self, card_network: enums::CardNetwork) { + if let Some(domain::PaymentMethodData::Card(card)) = &mut self.payment_method_data { + logger::debug!("set card network {:?}", card_network.clone()); + card.card_network = Some(card_network); + }; + } + + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ) { + let co_badged_card_data = + api_models::payment_methods::CoBadgedCardData::from(debit_routing_ouput); + let card_type = debit_routing_ouput + .card_type + .clone() + .to_string() + .to_uppercase(); + if let Some(domain::PaymentMethodData::Card(card)) = &mut self.payment_method_data { + card.co_badged_card_data = Some(co_badged_card_data); + card.card_type = Some(card_type); + logger::debug!("set co-badged card data in payment method data"); + }; + } + #[cfg(feature = "v1")] fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod) { self.payment_attempt.capture_method = Some(capture_method); @@ -8523,6 +8630,17 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> { todo!() } + fn set_card_network(&mut self, card_network: enums::CardNetwork) { + todo!() + } + + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ) { + todo!() + } + fn set_email_if_not_present(&mut self, _email: pii::Email) { todo!() } @@ -8763,6 +8881,17 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> { todo!() } + fn set_card_network(&mut self, card_network: enums::CardNetwork) { + todo!() + } + + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ) { + todo!() + } + fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) { todo!() } @@ -8975,6 +9104,17 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> { todo!() } + fn set_card_network(&mut self, card_network: enums::CardNetwork) { + todo!() + } + + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ) { + todo!() + } + fn set_pm_token(&mut self, _token: String) { todo!() } @@ -9197,6 +9337,17 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> { todo!() } + fn set_card_network(&mut self, card_network: enums::CardNetwork) { + todo!() + } + + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ) { + todo!() + } + fn set_email_if_not_present(&mut self, _email: pii::Email) { todo!() } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 59b25d9b86b..0cada8c368e 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2120,6 +2120,11 @@ pub async fn retrieve_payment_method_data_with_permanent_token( .network_token_requestor_reference_id .clone(), ); + + let co_badged_card_data = payment_method_info + .get_payment_methods_data() + .and_then(|payment_methods_data| payment_methods_data.get_co_badged_card_data()); + match vault_fetch_action { VaultFetchAction::FetchCardDetailsFromLocker => { let card = vault_data @@ -2132,6 +2137,7 @@ pub async fn retrieve_payment_method_data_with_permanent_token( &payment_intent.merchant_id, locker_id, card_token_data, + co_badged_card_data, ) .await }) @@ -2182,6 +2188,7 @@ pub async fn retrieve_payment_method_data_with_permanent_token( &payment_intent.merchant_id, locker_id, card_token_data, + co_badged_card_data, ) .await }) @@ -2246,6 +2253,7 @@ pub async fn retrieve_card_with_permanent_token_for_external_authentication( &payment_intent.merchant_id, locker_id, card_token_data, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2263,7 +2271,9 @@ pub async fn fetch_card_details_from_locker( merchant_id: &id_type::MerchantId, locker_id: &str, card_token_data: Option<&domain::CardToken>, + co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>, ) -> RouterResult<domain::Card> { + logger::debug!("Fetching card details from locker"); let card = cards::get_card_from_locker(state, customer_id, merchant_id, locker_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2308,7 +2318,7 @@ pub async fn fetch_card_details_from_locker( card_issuing_country: None, bank_code: None, }; - Ok(api_card.into()) + Ok(domain::Card::from((api_card, co_badged_card_data))) } #[cfg(all( @@ -4584,15 +4594,32 @@ pub async fn get_additional_payment_data( _ => None, }; - let card_network = match card_data + // Added an additional check for card_data.co_badged_card_data.is_some() + // because is_cobadged_card() only returns true if the card number matches a specific regex. + // However, this regex does not cover all possible co-badged networks. + // The co_badged_card_data field is populated based on a co-badged BIN lookup + // and helps identify co-badged cards that may not match the regex alone. + // Determine the card network based on cobadge detection and co-badged BIN data + let is_cobadged_based_on_regex = card_data .card_number .is_cobadged_card() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Card cobadge check failed due to an invalid card network regex", - )? { - true => card_data.card_network.clone(), - false => None, + )?; + + let card_network = match ( + is_cobadged_based_on_regex, + card_data.co_badged_card_data.is_some(), + ) { + (false, false) => { + logger::debug!("Card network is not cobadged"); + None + } + _ => { + logger::debug!("Card network is cobadged"); + card_data.card_network.clone() + } }; let last4 = Some(card_data.card_number.get_last4()); @@ -5170,10 +5197,10 @@ pub async fn get_apple_pay_retryable_connectors<F, D>( state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: &D, - pre_routing_connector_data_list: &[api::ConnectorData], + pre_routing_connector_data_list: &[api::ConnectorRoutingData], merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>, business_profile: domain::Profile, -) -> CustomResult<Option<Vec<api::ConnectorData>>, errors::ApiErrorResponse> +) -> CustomResult<Option<Vec<api::ConnectorRoutingData>>, errors::ApiErrorResponse> where F: Send + Clone, D: payments::OperationSessionGetters<F> + Send, @@ -5190,7 +5217,10 @@ where payment_data.get_creds_identifier(), merchant_context.get_merchant_key_store(), profile_id, - &pre_decided_connector_data_first.connector_name.to_string(), + &pre_decided_connector_data_first + .connector_data + .connector_name + .to_string(), merchant_connector_id, ) .await?; @@ -5225,19 +5255,22 @@ where merchant_connector_account.metadata.clone(), 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(), - api::GetToken::Connector, - Some(merchant_connector_account.get_id()), - ) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Invalid connector name received")?; + let routing_data: api::ConnectorRoutingData = + api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &merchant_connector_account.connector_name.to_string(), + api::GetToken::Connector, + Some(merchant_connector_account.get_id()), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received")? + .into(); if !connector_data_list.iter().any(|connector_details| { - connector_details.merchant_connector_id == connector_data.merchant_connector_id + connector_details.connector_data.merchant_connector_id + == routing_data.connector_data.merchant_connector_id }) { - connector_data_list.push(connector_data) + connector_data_list.push(routing_data) } } } @@ -5260,7 +5293,7 @@ where 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()) + routing_connector_data_list.push(pre_val.connector_data.merchant_connector_id.clone()) }); fallback_connetors_list.iter().for_each(|fallback_val| { @@ -5281,7 +5314,7 @@ where .iter() .for_each(|merchant_connector_id| { let connector_data = connector_data_list.iter().find(|connector_data| { - *merchant_connector_id == connector_data.merchant_connector_id + *merchant_connector_id == connector_data.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/operations/payment_capture_v2.rs b/crates/router/src/core/payments/operations/payment_capture_v2.rs index ecdf4365970..9fe4e805f94 100644 --- a/crates/router/src/core/payments/operations/payment_capture_v2.rs +++ b/crates/router/src/core/payments/operations/payment_capture_v2.rs @@ -288,7 +288,7 @@ impl<F: Clone + Send> Domain<F, PaymentsCaptureRequest, PaymentCaptureData<F>> f .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; - Ok(ConnectorCallType::PreDetermined(connector_data)) + Ok(ConnectorCallType::PreDetermined(connector_data.into())) } } diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs index 37cb3875b90..2074b28fd00 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -365,7 +365,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConf Some(merchant_connector_id), )?; - Ok(ConnectorCallType::PreDetermined(connector_data)) + Ok(ConnectorCallType::PreDetermined(connector_data.into())) } } diff --git a/crates/router/src/core/payments/operations/payment_get.rs b/crates/router/src/core/payments/operations/payment_get.rs index 14c4b15052b..05536c56296 100644 --- a/crates/router/src/core/payments/operations/payment_get.rs +++ b/crates/router/src/core/payments/operations/payment_get.rs @@ -293,7 +293,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRetrieveRequest, PaymentStatusDat .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; - Ok(ConnectorCallType::PreDetermined(connector_data)) + Ok(ConnectorCallType::PreDetermined(connector_data.into())) } None | Some(_) => Ok(ConnectorCallType::Skip), } diff --git a/crates/router/src/core/payments/operations/proxy_payments_intent.rs b/crates/router/src/core/payments/operations/proxy_payments_intent.rs index 5d6717b8ca2..1d7fb108b30 100644 --- a/crates/router/src/core/payments/operations/proxy_payments_intent.rs +++ b/crates/router/src/core/payments/operations/proxy_payments_intent.rs @@ -318,7 +318,7 @@ impl<F: Clone + Send + Sync> Domain<F, ProxyPaymentsRequest, PaymentConfirmData< merchant_connector_id, )?; - Ok(ConnectorCallType::PreDetermined(connector_data)) + Ok(ConnectorCallType::PreDetermined(connector_data.into())) } else { Err(error_stack::Report::new( errors::ApiErrorResponse::InternalServerError, diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 5fde726a21b..bfe2c99855e 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -34,7 +34,7 @@ pub async fn do_gsm_actions<F, ApiRequest, FData, D>( state: &app::SessionState, req_state: ReqState, payment_data: &mut D, - mut connectors: IntoIter<api::ConnectorData>, + mut connector_routing_data: IntoIter<api::ConnectorRoutingData>, original_connector_data: &api::ConnectorData, mut router_data: types::RouterData<F, FData, types::PaymentsResponseData>, merchant_context: &domain::MerchantContext, @@ -137,7 +137,7 @@ where break; } - if connectors.len() == 0 { + if connector_routing_data.len() == 0 { logger::info!("connectors exhausted for auto_retry payment"); metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(1, &[]); break; @@ -159,7 +159,7 @@ where // If should_retry_with_pan is true, it indicates that we are retrying with PAN using the same connector. original_connector_data.clone() } else { - super::get_connector_data(&mut connectors)? + super::get_connector_data(&mut connector_routing_data)?.connector_data }; router_data = do_retry( @@ -372,6 +372,7 @@ where business_profile, true, should_retry_with_pan, + None, ) .await?; diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 9280415412d..b485cd9d987 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1,27 +1,24 @@ mod transformers; pub mod utils; - #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use std::collections::hash_map; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use std::hash::{Hash, Hasher}; use std::{collections::HashMap, str::FromStr, sync::Arc}; +#[cfg(feature = "v1")] +use api_models::open_router::{self as or_types, DecidedGateway, OpenRouterDecideGatewayRequest}; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use api_models::routing as api_routing; use api_models::{ admin as admin_api, enums::{self as api_enums, CountryAlpha2}, routing::ConnectorSelection, }; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use api_models::{ - open_router::{self as or_types, DecidedGateway, OpenRouterDecideGatewayRequest}, - routing as api_routing, -}; +use common_utils::ext_traits::AsyncExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use common_utils::{ - ext_traits::{AsyncExt, BytesExt}, - request, -}; +use common_utils::{ext_traits::BytesExt, request}; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use euclid::{ @@ -43,7 +40,7 @@ use kgraph_utils::{ transformers::{IntoContext, IntoDirValue}, types::CountryCurrencyFilter, }; -use masking::PeekInterface; +use masking::{PeekInterface, Secret}; use rand::distributions::{self, Distribution}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use rand::SeedableRng; @@ -57,11 +54,13 @@ use utils::perform_decision_euclid_routing; use crate::core::admin; #[cfg(feature = "payouts")] use crate::core::payouts; +#[cfg(feature = "v1")] +use crate::core::routing::transformers::OpenRouterDecideGatewayRequestExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use crate::{core::routing::transformers::OpenRouterDecideGatewayRequestExt, headers, services}; +use crate::headers; use crate::{ - core::{errors, errors as oss_errors, routing}, - logger, + core::{errors, errors as oss_errors, payments::routing::utils::EuclidApiHandler, routing}, + logger, services, types::{ api::{self, routing as routing_types}, domain, storage as oss_storage, @@ -1580,6 +1579,64 @@ pub async fn perform_dynamic_routing_with_open_router( Ok(connectors) } +#[cfg(feature = "v1")] +pub async fn perform_open_routing_for_debit_routing( + state: &SessionState, + payment_attempt: &oss_storage::PaymentAttempt, + co_badged_card_request: or_types::CoBadgedCardRequest, + card_isin: Option<Secret<String>>, +) -> RoutingResult<or_types::DebitRoutingOutput> { + logger::debug!( + "performing debit routing with open_router for profile {}", + payment_attempt.profile_id.get_string_repr() + ); + + let metadata = Some( + serde_json::to_string(&co_badged_card_request) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encode Vaulting data to string") + .change_context(errors::RoutingError::MetadataParsingError)?, + ); + + let open_router_req_body = OpenRouterDecideGatewayRequest::construct_debit_request( + payment_attempt, + metadata, + card_isin, + Some(or_types::RankingAlgorithm::NtwBasedRouting), + ); + + let response: RoutingResult<DecidedGateway> = utils::EuclidApiClient::send_euclid_request( + state, + services::Method::Post, + "decide-gateway", + Some(open_router_req_body), + None, + ) + .await; + + let output = match response { + Ok(decided_gateway) => { + let debit_routing_output = decided_gateway + .debit_routing_output + .get_required_value("debit_routing_output") + .change_context(errors::RoutingError::OpenRouterError( + "Failed to parse the response from open_router".into(), + )) + .attach_printable("debit_routing_output is missing in the open routing response")?; + + Ok(debit_routing_output) + } + Err(error_response) => { + logger::error!("open_router_error_response: {:?}", error_response); + Err(errors::RoutingError::OpenRouterError( + "Failed to perform debit routing in open router".into(), + )) + } + }?; + + Ok(output) +} + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub async fn perform_dynamic_routing_with_intelligent_router( state: &SessionState, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 25008523633..ae68ea53773 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -204,6 +204,11 @@ where payment_method_billing_address, ) .await?; + let payment_methods_data = + &save_payment_method_data.request.get_payment_method_data(); + + let co_badged_card_data = payment_methods_data.get_co_badged_card_data(); + let customer_id = customer_id.to_owned().get_required_value("customer_id")?; let merchant_id = merchant_context.get_merchant_account().get_id(); let is_network_tokenization_enabled = @@ -272,7 +277,7 @@ where save_payment_method_data.request.get_payment_method_data(), ) { (Some(card), _) => Some(PaymentMethodsData::Card( - CardDetailsPaymentMethod::from(card.clone()), + CardDetailsPaymentMethod::from((card.clone(), co_badged_card_data)), )), ( _, @@ -303,7 +308,10 @@ where > = match network_token_resp { Some(token_resp) => { let pm_token_details = token_resp.card.as_ref().map(|card| { - PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) + PaymentMethodsData::Card(CardDetailsPaymentMethod::from(( + card.clone(), + None, + ))) }); pm_token_details @@ -645,9 +653,10 @@ where }); let updated_pmd = updated_card.as_ref().map(|card| { - PaymentMethodsData::Card(CardDetailsPaymentMethod::from( + PaymentMethodsData::Card(CardDetailsPaymentMethod::from(( card.clone(), - )) + co_badged_card_data, + ))) }); let pm_data_encrypted: Option< Encryptable<Secret<serde_json::Value>>, diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 55b25a0ed36..87888ab4257 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -82,8 +82,8 @@ pub struct PayoutData { // ********************************************** CORE FLOWS ********************************************** pub fn get_next_connector( - connectors: &mut IntoIter<api::ConnectorData>, -) -> RouterResult<api::ConnectorData> { + connectors: &mut IntoIter<api::ConnectorRoutingData>, +) -> RouterResult<api::ConnectorRoutingData> { connectors .next() .ok_or(errors::ApiErrorResponse::InternalServerError) @@ -170,11 +170,11 @@ pub async fn make_connector_decision( payout_data: &mut PayoutData, ) -> RouterResult<()> { match connector_call_type { - api::ConnectorCallType::PreDetermined(connector_data) => { + api::ConnectorCallType::PreDetermined(routing_data) => { Box::pin(call_connector_payout( state, merchant_context, - &connector_data, + &routing_data.connector_data, payout_data, )) .await?; @@ -191,7 +191,7 @@ pub async fn make_connector_decision( if config_bool && payout_data.should_call_gsm() { Box::pin(retry::do_gsm_single_connector_actions( state, - connector_data, + routing_data.connector_data, payout_data, merchant_context, )) @@ -201,10 +201,10 @@ pub async fn make_connector_decision( Ok(()) } - api::ConnectorCallType::Retryable(connectors) => { - let mut connectors = connectors.into_iter(); + api::ConnectorCallType::Retryable(routing_data) => { + let mut routing_data = routing_data.into_iter(); - let connector_data = get_next_connector(&mut connectors)?; + let connector_data = get_next_connector(&mut routing_data)?.connector_data; Box::pin(call_connector_payout( state, @@ -226,7 +226,7 @@ pub async fn make_connector_decision( if config_multiple_connector_bool && payout_data.should_call_gsm() { Box::pin(retry::do_gsm_multiple_connector_actions( state, - connectors, + routing_data, connector_data.clone(), payout_data, merchant_context, @@ -1799,10 +1799,15 @@ pub async fn complete_payout_retrieve( payout_data: &mut PayoutData, ) -> RouterResult<()> { match connector_call_type { - api::ConnectorCallType::PreDetermined(connector_data) => { - create_payout_retrieve(state, merchant_context, &connector_data, payout_data) - .await - .attach_printable("Payout retrieval failed for given Payout request")?; + api::ConnectorCallType::PreDetermined(routing_data) => { + create_payout_retrieve( + state, + merchant_context, + &routing_data.connector_data, + payout_data, + ) + .await + .attach_printable("Payout retrieval failed for given Payout request")?; } api::ConnectorCallType::Retryable(_) | api::ConnectorCallType::SessionMultiple(_) => { Err(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 010331090d0..b157fb0e557 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -495,6 +495,7 @@ pub async fn save_payout_data_to_locker( card_network: card_info.card_network, card_type: card_info.card_type, saved_to_locker: true, + co_badged_card_data: None, }, ) }) @@ -515,6 +516,7 @@ pub async fn save_payout_data_to_locker( card_network: None, card_type: None, saved_to_locker: true, + co_badged_card_data: None, }, ) }); @@ -847,7 +849,7 @@ pub async fn decide_payout_connector( .attach_printable("Invalid connector name received in 'routed_through'")?; routing_data.routed_through = Some(connector_name.clone()); - return Ok(api::ConnectorCallType::PreDetermined(connector_data)); + return Ok(api::ConnectorCallType::PreDetermined(connector_data.into())); } // Validate and get the business_profile from payout_attempt @@ -897,6 +899,7 @@ pub async fn decide_payout_connector( api::GetToken::Connector, payout_attempt.merchant_connector_id.clone(), ) + .map(|connector_data| connector_data.into()) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -947,6 +950,7 @@ pub async fn decide_payout_connector( api::GetToken::Connector, payout_attempt.merchant_connector_id.clone(), ) + .map(|connector_data| connector_data.into()) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rs index 3e0697bea19..3b5e93eaf11 100644 --- a/crates/router/src/core/payouts/retry.rs +++ b/crates/router/src/core/payouts/retry.rs @@ -23,7 +23,7 @@ use crate::{ #[allow(clippy::too_many_arguments)] pub async fn do_gsm_multiple_connector_actions( state: &app::SessionState, - mut connectors: IntoIter<api::ConnectorData>, + mut connectors_routing_data: IntoIter<api::ConnectorRoutingData>, original_connector_data: api::ConnectorData, payout_data: &mut PayoutData, merchant_context: &domain::MerchantContext, @@ -53,13 +53,13 @@ pub async fn do_gsm_multiple_connector_actions( break; } - if connectors.len() == 0 { + if connectors_routing_data.len() == 0 { logger::info!("connectors exhausted for auto_retry payout"); metrics::AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT.add(1, &[]); break; } - connector = super::get_next_connector(&mut connectors)?; + connector = super::get_next_connector(&mut connectors_routing_data)?.connector_data; Box::pin(do_retry( &state.clone(), diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 39b601ed296..c65a8c6b9ec 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -8,7 +8,7 @@ use std::str::FromStr; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] use std::sync::Arc; -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[cfg(feature = "v1")] use api_models::open_router; use api_models::routing as routing_types; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] @@ -303,6 +303,56 @@ pub struct RoutingAlgorithmHelpers<'h> { pub routing_algorithm: &'h routing_types::RoutingAlgorithm, } +#[cfg(feature = "v1")] +pub enum RoutingDecisionData { + DebitRouting(DebitRoutingDecisionData), +} +#[cfg(feature = "v1")] +pub struct DebitRoutingDecisionData { + pub card_network: common_enums::enums::CardNetwork, + pub debit_routing_result: open_router::DebitRoutingOutput, +} +#[cfg(feature = "v1")] +impl RoutingDecisionData { + pub fn apply_routing_decision<F, D>(&self, payment_data: &mut D) + where + F: Send + Clone, + D: crate::core::payments::OperationSessionGetters<F> + + crate::core::payments::OperationSessionSetters<F> + + Send + + Sync + + Clone, + { + match self { + Self::DebitRouting(data) => data.apply_debit_routing_decision(payment_data), + } + } + + pub fn get_debit_routing_decision_data( + network: common_enums::enums::CardNetwork, + debit_routing_result: open_router::DebitRoutingOutput, + ) -> Self { + Self::DebitRouting(DebitRoutingDecisionData { + card_network: network, + debit_routing_result, + }) + } +} +#[cfg(feature = "v1")] +impl DebitRoutingDecisionData { + pub fn apply_debit_routing_decision<F, D>(&self, payment_data: &mut D) + where + F: Send + Clone, + D: crate::core::payments::OperationSessionGetters<F> + + crate::core::payments::OperationSessionSetters<F> + + Send + + Sync + + Clone, + { + payment_data.set_card_network(self.card_network.clone()); + payment_data.set_co_badged_card_data(&self.debit_routing_result); + } +} #[derive(Clone, Debug)] pub struct ConnectNameAndMCAIdForProfile<'a>( pub FxHashSet<( diff --git a/crates/router/src/core/routing/transformers.rs b/crates/router/src/core/routing/transformers.rs index e9088ded2e7..ebf521c4604 100644 --- a/crates/router/src/core/routing/transformers.rs +++ b/crates/router/src/core/routing/transformers.rs @@ -2,7 +2,7 @@ use api_models::routing::{ MerchantRoutingAlgorithm, RoutingAlgorithm as Algorithm, RoutingAlgorithmKind, RoutingDictionaryRecord, }; -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[cfg(feature = "v1")] use api_models::{ open_router::{OpenRouterDecideGatewayRequest, PaymentInfo, RankingAlgorithm}, routing::RoutableConnectorChoice, @@ -12,8 +12,9 @@ use diesel_models::{ enums as storage_enums, routing_algorithm::{RoutingAlgorithm, RoutingProfileMetadata}, }; -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[cfg(feature = "v1")] use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt; +use masking::{PeekInterface, Secret}; use crate::{ core::{errors, routing}, @@ -108,7 +109,7 @@ impl From<&routing::TransactionData<'_>> for storage_enums::TransactionType { } } -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[cfg(feature = "v1")] pub trait OpenRouterDecideGatewayRequestExt { fn construct_sr_request( attempt: &PaymentAttempt, @@ -118,9 +119,18 @@ pub trait OpenRouterDecideGatewayRequestExt { ) -> Self where Self: Sized; + + fn construct_debit_request( + attempt: &PaymentAttempt, + metadata: Option<String>, + card_isin: Option<Secret<String>>, + ranking_algorithm: Option<RankingAlgorithm>, + ) -> Self + where + Self: Sized; } -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[cfg(feature = "v1")] impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest { fn construct_sr_request( attempt: &PaymentAttempt, @@ -134,9 +144,10 @@ impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest { amount: attempt.net_amount.get_order_amount(), currency: attempt.currency.unwrap_or(storage_enums::Currency::USD), payment_type: "ORDER_PAYMENT".to_string(), - // payment_method_type: attempt.payment_method_type.clone().unwrap(), payment_method_type: "UPI".into(), // TODO: once open-router makes this field string, we can send from attempt payment_method: attempt.payment_method.unwrap_or_default(), + metadata: None, + card_isin: None, }, merchant_id: attempt.profile_id.clone(), eligible_gateway_list: Some( @@ -149,4 +160,29 @@ impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest { elimination_enabled: Some(is_elimination_enabled), } } + + fn construct_debit_request( + attempt: &PaymentAttempt, + metadata: Option<String>, + card_isin: Option<Secret<String>>, + ranking_algorithm: Option<RankingAlgorithm>, + ) -> Self { + Self { + payment_info: PaymentInfo { + payment_id: attempt.payment_id.clone(), + amount: attempt.net_amount.get_order_amount(), + currency: attempt.currency.unwrap_or(storage_enums::Currency::USD), + payment_type: "ORDER_PAYMENT".to_string(), + card_isin: card_isin.map(|value| value.peek().clone()), + metadata, + payment_method_type: "UPI".into(), // TODO: once open-router makes this field string, we can send from attempt + payment_method: attempt.payment_method.unwrap_or_default(), + }, + merchant_id: attempt.profile_id.clone(), + // eligible gateway list is not used in debit routing + eligible_gateway_list: None, + ranking_algorithm, + elimination_enabled: None, + } + } } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 9291bdb3bf0..5009b993710 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -92,8 +92,8 @@ use crate::{ }; #[derive(Clone)] pub enum ConnectorCallType { - PreDetermined(ConnectorData), - Retryable(Vec<ConnectorData>), + PreDetermined(ConnectorRoutingData), + Retryable(Vec<ConnectorRoutingData>), SessionMultiple(SessionConnectorDatas), #[cfg(feature = "v2")] Skip, @@ -122,6 +122,15 @@ pub struct ConnectorData { pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } +impl From<ConnectorData> for ConnectorRoutingData { + fn from(connector_data: ConnectorData) -> Self { + Self { + connector_data, + network: None, + } + } +} + #[derive(Clone, Debug)] pub struct SessionConnectorData { pub payment_method_sub_type: api_enums::PaymentMethodType, @@ -186,11 +195,15 @@ common_utils::create_list_wrapper!( ); pub fn convert_connector_data_to_routable_connectors( - connectors: &[ConnectorData], + connectors: &[ConnectorRoutingData], ) -> CustomResult<Vec<RoutableConnectorChoice>, common_utils::errors::ValidationError> { connectors .iter() - .map(|connector_data| RoutableConnectorChoice::foreign_try_from(connector_data.clone())) + .map(|connectors_routing_data| { + RoutableConnectorChoice::foreign_try_from( + connectors_routing_data.connector_data.clone(), + ) + }) .collect() } diff --git a/crates/router/src/types/api/fraud_check.rs b/crates/router/src/types/api/fraud_check.rs index 44dc3514669..b0ed7ed35d4 100644 --- a/crates/router/src/types/api/fraud_check.rs +++ b/crates/router/src/types/api/fraud_check.rs @@ -24,11 +24,17 @@ pub struct FraudCheckConnectorData { pub connector_name: enums::FrmConnectors, } pub enum ConnectorCallType { - PreDetermined(ConnectorData), - Retryable(Vec<ConnectorData>), + PreDetermined(ConnectorRoutingData), + Retryable(Vec<ConnectorRoutingData>), SessionMultiple(SessionConnectorDatas), } +#[derive(Clone)] +pub struct ConnectorRoutingData { + pub connector_data: ConnectorData, + pub network: Option<common_enums::CardNetwork>, +} + impl FraudCheckConnectorData { pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> { let connector_name = enums::FrmConnectors::from_str(name) diff --git a/crates/router/src/utils/verify_connector.rs b/crates/router/src/utils/verify_connector.rs index b13ba70e6fb..0f5d9e6b318 100644 --- a/crates/router/src/utils/verify_connector.rs +++ b/crates/router/src/utils/verify_connector.rs @@ -24,6 +24,7 @@ pub fn generate_card_from_details( card_issuing_country: None, bank_code: None, card_holder_name: None, + co_badged_card_data: None, }) } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 8b3372d7dec..3497a048a8a 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -52,6 +52,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }), confirm: true, statement_descriptor_suffix: None, @@ -302,6 +303,7 @@ async fn payments_create_failure() { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }); let response = services::api::execute_connector_processing_step( diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index c7ad3b69a32..d7017d3d44e 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -154,6 +154,7 @@ impl AdyenTest { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }), confirm: true, statement_descriptor_suffix: None, diff --git a/crates/router/tests/connectors/airwallex.rs b/crates/router/tests/connectors/airwallex.rs index 0e538818d50..bf5a06f157a 100644 --- a/crates/router/tests/connectors/airwallex.rs +++ b/crates/router/tests/connectors/airwallex.rs @@ -83,6 +83,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), router_return_url: Some("https://google.com".to_string()), diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rs index 78235278ed9..77ab8223145 100644 --- a/crates/router/tests/connectors/fiserv.rs +++ b/crates/router/tests/connectors/fiserv.rs @@ -54,6 +54,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 diff --git a/crates/router/tests/connectors/rapyd.rs b/crates/router/tests/connectors/rapyd.rs index ee6ac303e88..e173f4753d6 100644 --- a/crates/router/tests/connectors/rapyd.rs +++ b/crates/router/tests/connectors/rapyd.rs @@ -54,6 +54,7 @@ async fn should_only_authorize_payment() { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 @@ -82,6 +83,7 @@ async fn should_authorize_and_capture_payment() { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }), ..utils::PaymentAuthorizeType::default().0 }), diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index ede3aeb17db..d6925ae1667 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -941,6 +941,7 @@ impl Default for CCardType { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }) } } diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index 793a1cc15f4..22fd198bd0a 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -84,6 +84,7 @@ impl WorldlineTest { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }), confirm: true, statement_descriptor_suffix: None, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index f4f1eeb2fad..d682b5c3f8a 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -590,6 +590,12 @@ bank_redirect.trustly.connector_list = "adyen,aci" bank_redirect.open_banking_uk.connector_list = "adyen" bank_redirect.eps.connector_list = "globalpay,nexinets,aci" +[debit_routing_config] +supported_currencies = "USD" +supported_connectors = "adyen" + +[debit_routing_config.connector_supported_debit_networks] +adyen = "Star,Pulse,Accel,Nyce" [cors] max_age = 30
2025-04-25T13:45:19Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> A debit card can be linked to multiple card networks, with one serving as the primary (international) network and the others as secondary (local) networks. In debit routing, payments will be processed through the local network based on the merchant's requirements. This pr add the integration open router for debit routing. This pull request introduces a comprehensive set of changes to support debit routing functionality, expand card network capabilities, and improve code maintainability. Key updates include the addition of debit routing configurations, new card networks, and corresponding transformations across multiple modules. Below is a summary of the most important changes: ### Debit Routing Enhancements: * Added a new `DebitRoutingConfig` struct to the `Settings` configuration, which includes supported currencies, connectors, and debit networks * Added a `debit_routing` module under the `core` directory to support debit routing logic ### Card Network Expansion: * Added support for new card networks (`Star`, `Pulse`, `Accel`, `Nyce`) in the `CardNetwork` enum and implemented corresponding logic for global network checks ### API Model Updates: * Added new routing-related fields and structs such as `DebitRoutingOutput`, `CoBadgedCardRequest`, and `DebitRoutingRequestData` to support debit routing in the `OpenRouter` module ### 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 by creating dummy co-badged card bin dump -> Create a merchant account and business profile -> Enable debit routing and provide merchant business country for the business profile ``` curl --location 'http://localhost:8080/account/merchant_1745690754/business_profile/pro_OiJkBiFuCYbYAkCG9X02' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ' \ --data '{ "is_debit_routing_enabled": true, "merchant_business_country": "US" }' ``` -> Create a adyen connector account as we have debit routing flow only for adyen -> Make a payment with a co-badged card ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-tenant-id: hyperswitch' \ --header 'api-key: ' \ --data-raw '{ "amount": 100, "amount_to_capture": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "setup_future_usage": "on_session", "capture_on": "2022-09-10T10:11:12Z", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "customer_id": "cu_1745693422", "return_url": "http://127.0.0.1:4040", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4400002000000004", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ``` { "payment_id": "pay_RjnzToNFSTe9QjbKcZUk", "merchant_id": "merchant_1745690754", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "adyen", "client_secret": "pay_RjnzToNFSTe9QjbKcZUk_secret_jpBstmZ1YgDBO0b0XStn", "created": "2025-04-26T18:50:32.942Z", "currency": "USD", "customer_id": "cu_1745693422", "customer": { "id": "cu_1745693422", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0004", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "440000", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1745693422", "created_at": 1745693432, "expires": 1745697032, "secret": "epk_dbe0b04c709b4984a02f312e4c5ec36f" }, "manual_retry_allowed": false, "connector_transaction_id": "JRVPVXD3PD22KMV5", "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_RjnzToNFSTe9QjbKcZUk_1", "payment_link": null, "profile_id": "pro_OiJkBiFuCYbYAkCG9X02", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_VyX6BwB09KJrmeR1ODFD", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-26T19:05:32.941Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-26T18:50:36.398Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` -> logs indicating debit routing flow ![image](https://github.com/user-attachments/assets/28042da0-54d2-4af5-b6fe-0f758616acc6) -> connector request, card brand or network is being sent as `star` ![image](https://github.com/user-attachments/assets/ec378e88-4be3-474c-959c-236749b5f201) -> adyen dashboard indicating the payment was processed with star network ![image](https://github.com/user-attachments/assets/8a628ebe-a466-4a32-8312-93ffcc325fba) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
34dd99d8050a84f0478cdb4fa0f0cc83608e52d9
34dd99d8050a84f0478cdb4fa0f0cc83608e52d9
juspay/hyperswitch
juspay__hyperswitch-7500
Bug: [REFACTOR][payment_methods] refactor network tokenization flow for v2 Refactor network tokenization flow for v2 payment method. - moved the network tokenization req, response types from domain to router types, since the types are not generic for Hyperswitch but req and response types of token service. - replaced hanging functions to impl based in the flow - Update ListCustomerPaymentMethod response and Payment Method response with network token details.
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 77963ee90df..6b9b35ac2c0 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -11,7 +11,10 @@ use common_utils::{ id_type, link_utils, pii, types::{MinorUnit, Percentage, Surcharge}, }; +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use masking::PeekInterface; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +use masking::{ExposeInterface, PeekInterface}; use serde::de; use utoipa::{schema, ToSchema}; @@ -901,9 +904,8 @@ pub struct ConnectorTokenDetails { pub metadata: Option<pii::SecretSerdeValue>, /// The value of the connector token. This token can be used to make merchant initiated payments ( MIT ), directly with the connector. - pub token: String, + pub token: masking::Secret<String>, } - #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema, Clone)] pub struct PaymentMethodResponse { @@ -951,6 +953,8 @@ pub struct PaymentMethodResponse { /// The connector token details if available pub connector_tokens: Option<Vec<ConnectorTokenDetails>>, + + pub network_token: Option<NetworkTokenResponse>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] @@ -976,6 +980,22 @@ pub struct CardDetailsPaymentMethod { pub saved_to_locker: bool, } +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct NetworkTokenDetailsPaymentMethod { + pub last4_digits: Option<String>, + pub issuer_country: Option<String>, + pub network_token_expiry_month: Option<masking::Secret<String>>, + pub network_token_expiry_year: Option<masking::Secret<String>>, + pub nick_name: Option<masking::Secret<String>>, + pub card_holder_name: Option<masking::Secret<String>>, + pub card_isin: Option<String>, + pub card_issuer: Option<String>, + pub card_network: Option<api_enums::CardNetwork>, + pub card_type: Option<String>, + #[serde(default = "saved_in_locker_default")] + pub saved_to_locker: bool, +} + #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodDataBankCreds { pub mask: String, @@ -1122,6 +1142,12 @@ pub struct CardDetailFromLocker { pub saved_to_locker: bool, } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] +pub struct NetworkTokenResponse { + pub payment_method_data: NetworkTokenDetailsPaymentMethod, +} + fn saved_in_locker_default() -> bool { true } @@ -1990,6 +2016,9 @@ pub struct CustomerPaymentMethod { /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, + + ///The network token details for the payment method + pub network_tokenization: Option<NetworkTokenResponse>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index f2dddf39b03..fac251d8b68 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -31,6 +31,8 @@ pub mod router_request_types; pub mod router_response_types; pub mod type_encryption; pub mod types; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub mod vault; #[cfg(not(feature = "payouts"))] pub trait PayoutAttemptInterface {} diff --git a/crates/hyperswitch_domain_models/src/network_tokenization.rs b/crates/hyperswitch_domain_models/src/network_tokenization.rs index a29792e969e..4dd54fe3323 100644 --- a/crates/hyperswitch_domain_models/src/network_tokenization.rs +++ b/crates/hyperswitch_domain_models/src/network_tokenization.rs @@ -1,6 +1,3 @@ -use std::fmt::Debug; - -use api_models::enums as api_enums; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") @@ -8,218 +5,6 @@ use api_models::enums as api_enums; use cards::CardNumber; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use cards::{CardNumber, NetworkToken}; -use common_utils::id_type; -use masking::Secret; -use serde::{Deserialize, Serialize}; - -#[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_methods_v2") -))] -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CardData { - pub card_number: CardNumber, - pub exp_month: Secret<String>, - pub exp_year: Secret<String>, - pub card_security_code: Option<Secret<String>>, -} - -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CardData { - pub card_number: CardNumber, - pub exp_month: Secret<String>, - pub exp_year: Secret<String>, - #[serde(skip_serializing_if = "Option::is_none")] - pub card_security_code: Option<Secret<String>>, -} - -#[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_methods_v2") -))] -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct OrderData { - pub consent_id: String, - pub customer_id: id_type::CustomerId, -} - -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct OrderData { - pub consent_id: String, - pub customer_id: id_type::GlobalCustomerId, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct ApiPayload { - pub service: String, - pub card_data: Secret<String>, //encrypted card data - pub order_data: OrderData, - pub key_id: String, - pub should_send_token: bool, -} - -#[derive(Debug, Deserialize, Eq, PartialEq)] -pub struct CardNetworkTokenResponse { - pub payload: Secret<String>, //encrypted payload -} - -#[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_methods_v2") -))] -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CardNetworkTokenResponsePayload { - pub card_brand: api_enums::CardNetwork, - pub card_fingerprint: Option<Secret<String>>, - pub card_reference: String, - pub correlation_id: String, - pub customer_id: String, - pub par: String, - pub token: CardNumber, - pub token_expiry_month: Secret<String>, - pub token_expiry_year: Secret<String>, - pub token_isin: String, - pub token_last_four: String, - pub token_status: String, -} - -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct GenerateNetworkTokenResponsePayload { - pub card_brand: api_enums::CardNetwork, - pub card_fingerprint: Option<Secret<String>>, - pub card_reference: String, - pub correlation_id: String, - pub customer_id: String, - pub par: String, - pub token: NetworkToken, - pub token_expiry_month: Secret<String>, - pub token_expiry_year: Secret<String>, - pub token_isin: String, - pub token_last_four: String, - pub token_status: String, -} - -#[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_methods_v2") -))] -#[derive(Debug, Serialize)] -pub struct GetCardToken { - pub card_reference: String, - pub customer_id: id_type::CustomerId, -} - -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[derive(Debug, Serialize)] -pub struct GetCardToken { - pub card_reference: String, - pub customer_id: id_type::GlobalCustomerId, -} -#[derive(Debug, Deserialize)] -pub struct AuthenticationDetails { - pub cryptogram: Secret<String>, - pub token: CardNumber, //network token -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct TokenDetails { - pub exp_month: Secret<String>, - pub exp_year: Secret<String>, -} - -#[derive(Debug, Deserialize)] -pub struct TokenResponse { - pub authentication_details: AuthenticationDetails, - pub network: api_enums::CardNetwork, - pub token_details: TokenDetails, -} - -#[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_methods_v2") -))] -#[derive(Debug, Serialize, Deserialize)] -pub struct DeleteCardToken { - pub card_reference: String, //network token requestor ref id - pub customer_id: id_type::CustomerId, -} - -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[derive(Debug, Serialize, Deserialize)] -pub struct DeleteCardToken { - pub card_reference: String, //network token requestor ref id - pub customer_id: id_type::GlobalCustomerId, -} - -#[derive(Debug, Deserialize, Eq, PartialEq)] -#[serde(rename_all = "UPPERCASE")] -pub enum DeleteNetworkTokenStatus { - Success, -} - -#[derive(Debug, Deserialize, Eq, PartialEq)] -pub struct NetworkTokenErrorInfo { - pub code: String, - pub developer_message: String, -} - -#[derive(Debug, Deserialize, Eq, PartialEq)] -pub struct NetworkTokenErrorResponse { - pub error_message: String, - pub error_info: NetworkTokenErrorInfo, -} - -#[derive(Debug, Deserialize, Eq, PartialEq)] -pub struct DeleteNetworkTokenResponse { - pub status: DeleteNetworkTokenStatus, -} - -#[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_methods_v2") -))] -#[derive(Debug, Serialize, Deserialize)] -pub struct CheckTokenStatus { - pub card_reference: String, - pub customer_id: id_type::CustomerId, -} - -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[derive(Debug, Serialize, Deserialize)] -pub struct CheckTokenStatus { - pub card_reference: String, - pub customer_id: id_type::GlobalCustomerId, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "UPPERCASE")] -pub enum TokenStatus { - Active, - Inactive, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CheckTokenStatusResponsePayload { - pub token_expiry_month: Secret<String>, - pub token_expiry_year: Secret<String>, - pub token_status: TokenStatus, -} - -#[derive(Debug, Deserialize)] -pub struct CheckTokenStatusResponse { - pub payload: CheckTokenStatusResponsePayload, -} #[cfg(all( any(feature = "v1", feature = "v2"), diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 64a95778af3..3f253f7cc31 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -1884,3 +1884,21 @@ impl From<NetworkTokenDetails> for NetworkTokenDetailsPaymentMethod { } } } + +impl From<NetworkTokenDetailsPaymentMethod> for payment_methods::NetworkTokenDetailsPaymentMethod { + fn from(item: NetworkTokenDetailsPaymentMethod) -> Self { + Self { + last4_digits: item.last4_digits, + issuer_country: item.issuer_country, + network_token_expiry_month: item.network_token_expiry_month, + network_token_expiry_year: item.network_token_expiry_year, + nick_name: item.nick_name, + card_holder_name: item.card_holder_name, + card_isin: item.card_isin, + card_issuer: item.card_issuer, + card_network: item.card_network, + card_type: item.card_type, + saved_to_locker: item.saved_to_locker, + } + } +} diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs index 963ec83e0be..66fc6214eaa 100644 --- a/crates/hyperswitch_domain_models/src/payment_methods.rs +++ b/crates/hyperswitch_domain_models/src/payment_methods.rs @@ -20,7 +20,10 @@ use serde_json::Value; use time::PrimitiveDateTime; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -use crate::{address::Address, type_encryption::OptionalEncryptableJsonType}; +use crate::{ + address::Address, payment_method_data as domain_payment_method_data, + type_encryption::OptionalEncryptableJsonType, +}; use crate::{ errors, mandates::{self, CommonMandateReference}, @@ -116,7 +119,8 @@ pub struct PaymentMethod { pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, #[encrypt(ty = Value)] - pub network_token_payment_method_data: Option<Encryptable<Value>>, + pub network_token_payment_method_data: + Option<Encryptable<domain_payment_method_data::PaymentMethodsData>>, } impl PaymentMethod { @@ -512,11 +516,16 @@ impl super::behaviour::Conversion for PaymentMethod { .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Error while deserializing Payment Method Data")?; - let network_token_payment_method_data = - data.network_token_payment_method_data - .map(|network_token_payment_method_data| { - network_token_payment_method_data.map(|value| value.expose()) - }); + let network_token_payment_method_data = data + .network_token_payment_method_data + .map(|network_token_payment_method_data| { + network_token_payment_method_data.deserialize_inner_value(|value| { + value.parse_value("Network token Payment Method Data") + }) + }) + .transpose() + .change_context(common_utils::errors::CryptoError::DecodingFailed) + .attach_printable("Error while deserializing Network token Payment Method Data")?; Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { customer_id: storage_model.customer_id, diff --git a/crates/hyperswitch_domain_models/src/vault.rs b/crates/hyperswitch_domain_models/src/vault.rs new file mode 100644 index 00000000000..9aac1e1f18e --- /dev/null +++ b/crates/hyperswitch_domain_models/src/vault.rs @@ -0,0 +1,54 @@ +use api_models::payment_methods; +use serde::{Deserialize, Serialize}; + +use crate::payment_method_data; + +#[derive(Debug, Deserialize, Serialize, Clone)] +pub enum PaymentMethodVaultingData { + Card(payment_methods::CardDetail), + NetworkToken(payment_method_data::NetworkTokenDetails), +} + +impl PaymentMethodVaultingData { + pub fn get_card(&self) -> Option<&payment_methods::CardDetail> { + match self { + Self::Card(card) => Some(card), + _ => None, + } + } + pub fn get_payment_methods_data(&self) -> payment_method_data::PaymentMethodsData { + match self { + Self::Card(card) => payment_method_data::PaymentMethodsData::Card( + payment_method_data::CardDetailsPaymentMethod::from(card.clone()), + ), + Self::NetworkToken(network_token) => { + payment_method_data::PaymentMethodsData::NetworkToken( + payment_method_data::NetworkTokenDetailsPaymentMethod::from( + network_token.clone(), + ), + ) + } + } + } +} + +pub trait VaultingDataInterface { + fn get_vaulting_data_key(&self) -> String; +} + +impl VaultingDataInterface for PaymentMethodVaultingData { + fn get_vaulting_data_key(&self) -> String { + match &self { + Self::Card(card) => card.card_number.to_string(), + Self::NetworkToken(network_token) => network_token.network_token.to_string(), + } + } +} + +impl From<payment_methods::PaymentMethodCreateData> for PaymentMethodVaultingData { + fn from(item: payment_methods::PaymentMethodCreateData) -> Self { + match item { + payment_methods::PaymentMethodCreateData::Card(card) => Self::Card(card), + } + } +} diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index d82bef27d1f..64b2b817252 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -446,6 +446,12 @@ pub enum NetworkTokenizationError { NetworkTokenizationServiceNotConfigured, #[error("Failed while calling Network Token Service API")] ApiError, + #[error("Network Tokenization is not enabled for profile")] + NetworkTokenizationNotEnabledForProfile, + #[error("Network Tokenization is not supported for {message}")] + NotSupported { message: String }, + #[error("Failed to encrypt the NetworkToken payment method details")] + NetworkTokenDetailsEncryptionFailed, } #[derive(Debug, thiserror::Error)] diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 08968997243..5893fbc6853 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -933,11 +933,9 @@ pub async fn create_payment_method_core( .await .attach_printable("Failed to add Payment method to DB")?; - let payment_method_data = - pm_types::PaymentMethodVaultingData::from(req.payment_method_data.clone()); - - let payment_method_data = - populate_bin_details_for_payment_method(state, &payment_method_data).await; + let payment_method_data = domain::PaymentMethodVaultingData::from(req.payment_method_data) + .populate_bin_details_for_payment_method(state) + .await; let vaulting_result = vault_payment_method( state, @@ -958,15 +956,7 @@ pub async fn create_payment_method_core( profile.is_network_tokenization_enabled, &customer_id, ) - .await - .map_err(|e| { - services::logger::error!( - "Failed to network tokenize the payment method for customer: {}. Error: {} ", - customer_id.get_string_repr(), - e - ); - }) - .ok(); + .await; let (response, payment_method) = match vaulting_result { Ok((vaulting_resp, fingerprint_id)) => { @@ -1035,86 +1025,83 @@ pub struct NetworkTokenPaymentMethodDetails { #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub async fn network_tokenize_and_vault_the_pmd( state: &SessionState, - payment_method_data: &pm_types::PaymentMethodVaultingData, + payment_method_data: &domain::PaymentMethodVaultingData, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, network_tokenization_enabled_for_profile: bool, customer_id: &id_type::GlobalCustomerId, -) -> RouterResult<NetworkTokenPaymentMethodDetails> { - when(!network_tokenization_enabled_for_profile, || { - Err(report!(errors::ApiErrorResponse::NotSupported { - message: "Network Tokenization is not enabled for this payment method".to_string() - })) - })?; - - let is_network_tokenization_enabled_for_pm = network_tokenization - .as_ref() - .map(|nt| matches!(nt.enable, common_enums::NetworkTokenizationToggle::Enable)) - .unwrap_or(false); - - let card_data = match payment_method_data { - pm_types::PaymentMethodVaultingData::Card(data) - if is_network_tokenization_enabled_for_pm => - { - Ok(data) - } - _ => Err(report!(errors::ApiErrorResponse::NotSupported { - message: "Network Tokenization is not supported for this payment method".to_string() - })), - }?; - - let (resp, network_token_req_ref_id) = - network_tokenization::make_card_network_tokenization_request(state, card_data, customer_id) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to generate network token")?; +) -> Option<NetworkTokenPaymentMethodDetails> { + let network_token_pm_details_result: errors::CustomResult< + NetworkTokenPaymentMethodDetails, + errors::NetworkTokenizationError, + > = async { + when(!network_tokenization_enabled_for_profile, || { + Err(report!( + errors::NetworkTokenizationError::NetworkTokenizationNotEnabledForProfile + )) + })?; - let network_token_vaulting_data = pm_types::PaymentMethodVaultingData::NetworkToken(resp); - let vaulting_resp = vault::add_payment_method_to_vault( - state, - merchant_account, - &network_token_vaulting_data, - None, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to vault the network token data")?; + let is_network_tokenization_enabled_for_pm = network_tokenization + .as_ref() + .map(|nt| matches!(nt.enable, common_enums::NetworkTokenizationToggle::Enable)) + .unwrap_or(false); + + let card_data = payment_method_data + .get_card() + .and_then(|card| is_network_tokenization_enabled_for_pm.then_some(card)) + .ok_or_else(|| { + report!(errors::NetworkTokenizationError::NotSupported { + message: "Payment method".to_string(), + }) + })?; - let key_manager_state = &(state).into(); - let network_token = match network_token_vaulting_data { - pm_types::PaymentMethodVaultingData::Card(card) => { - payment_method_data::PaymentMethodsData::Card( - payment_method_data::CardDetailsPaymentMethod::from(card.clone()), - ) - } - pm_types::PaymentMethodVaultingData::NetworkToken(network_token) => { - payment_method_data::PaymentMethodsData::NetworkToken( - payment_method_data::NetworkTokenDetailsPaymentMethod::from(network_token.clone()), + let (resp, network_token_req_ref_id) = + network_tokenization::make_card_network_tokenization_request( + state, + card_data, + customer_id, ) - } - }; + .await?; - let network_token_pmd = - cards::create_encrypted_data(key_manager_state, key_store, network_token) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt Payment method data")?; + let network_token_vaulting_data = domain::PaymentMethodVaultingData::NetworkToken(resp); + let vaulting_resp = vault::add_payment_method_to_vault( + state, + merchant_account, + &network_token_vaulting_data, + None, + ) + .await + .change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed) + .attach_printable("Failed to vault network token")?; - Ok(NetworkTokenPaymentMethodDetails { - network_token_requestor_reference_id: network_token_req_ref_id, - network_token_locker_id: vaulting_resp.vault_id.get_string_repr().clone(), - network_token_pmd, - }) + let key_manager_state = &(state).into(); + let network_token_pmd = cards::create_encrypted_data( + key_manager_state, + key_store, + network_token_vaulting_data.get_payment_methods_data(), + ) + .await + .change_context(errors::NetworkTokenizationError::NetworkTokenDetailsEncryptionFailed) + .attach_printable("Failed to encrypt PaymentMethodsData")?; + + Ok(NetworkTokenPaymentMethodDetails { + network_token_requestor_reference_id: network_token_req_ref_id, + network_token_locker_id: vaulting_resp.vault_id.get_string_repr().clone(), + network_token_pmd, + }) + } + .await; + network_token_pm_details_result.ok() } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub async fn populate_bin_details_for_payment_method( state: &SessionState, - payment_method_data: &pm_types::PaymentMethodVaultingData, -) -> pm_types::PaymentMethodVaultingData { + payment_method_data: &domain::PaymentMethodVaultingData, +) -> domain::PaymentMethodVaultingData { match payment_method_data { - pm_types::PaymentMethodVaultingData::Card(card) => { + domain::PaymentMethodVaultingData::Card(card) => { let card_isin = card.card_number.get_card_isin(); if card.card_issuer.is_some() @@ -1122,7 +1109,7 @@ pub async fn populate_bin_details_for_payment_method( && card.card_type.is_some() && card.card_issuing_country.is_some() { - pm_types::PaymentMethodVaultingData::Card(card.clone()) + domain::PaymentMethodVaultingData::Card(card.clone()) } else { let card_info = state .store @@ -1132,7 +1119,7 @@ pub async fn populate_bin_details_for_payment_method( .ok() .flatten(); - pm_types::PaymentMethodVaultingData::Card(payment_methods::CardDetail { + domain::PaymentMethodVaultingData::Card(payment_methods::CardDetail { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), @@ -1163,6 +1150,67 @@ pub async fn populate_bin_details_for_payment_method( _ => payment_method_data.clone(), } } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[async_trait::async_trait] +pub trait PaymentMethodExt { + async fn populate_bin_details_for_payment_method(&self, state: &SessionState) -> Self; +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[async_trait::async_trait] +impl PaymentMethodExt for domain::PaymentMethodVaultingData { + async fn populate_bin_details_for_payment_method(&self, state: &SessionState) -> Self { + match self { + Self::Card(card) => { + let card_isin = card.card_number.get_card_isin(); + + if card.card_issuer.is_some() + && card.card_network.is_some() + && card.card_type.is_some() + && card.card_issuing_country.is_some() + { + Self::Card(card.clone()) + } else { + let card_info = state + .store + .get_card_info(&card_isin) + .await + .map_err(|error| services::logger::error!(card_info_error=?error)) + .ok() + .flatten(); + + Self::Card(payment_methods::CardDetail { + card_number: card.card_number.clone(), + card_exp_month: card.card_exp_month.clone(), + card_exp_year: card.card_exp_year.clone(), + card_holder_name: card.card_holder_name.clone(), + nick_name: card.nick_name.clone(), + card_issuing_country: card_info.as_ref().and_then(|val| { + val.card_issuing_country + .as_ref() + .map(|c| api_enums::CountryAlpha2::from_str(c)) + .transpose() + .ok() + .flatten() + }), + card_network: card_info.as_ref().and_then(|val| val.card_network.clone()), + card_issuer: card_info.as_ref().and_then(|val| val.card_issuer.clone()), + card_type: card_info.as_ref().and_then(|val| { + val.card_type + .as_ref() + .map(|c| payment_methods::CardType::from_str(c)) + .transpose() + .ok() + .flatten() + }), + card_cvc: card.card_cvc.clone(), + }) + } + } + _ => self.clone(), + } + } +} #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] @@ -1557,7 +1605,7 @@ fn create_connector_token_details_update( #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[allow(clippy::too_many_arguments)] pub async fn create_pm_additional_data_update( - payment_method_vaulting_data: Option<&pm_types::PaymentMethodVaultingData>, + pmd: Option<&domain::PaymentMethodVaultingData>, state: &SessionState, key_store: &domain::MerchantKeyStore, vault_id: Option<String>, @@ -1568,15 +1616,15 @@ pub async fn create_pm_additional_data_update( payment_method_type: Option<common_enums::PaymentMethod>, payment_method_subtype: Option<common_enums::PaymentMethodType>, ) -> RouterResult<storage::PaymentMethodUpdate> { - let encrypted_payment_method_data = payment_method_vaulting_data + let encrypted_payment_method_data = pmd .map( |payment_method_vaulting_data| match payment_method_vaulting_data { - pm_types::PaymentMethodVaultingData::Card(card) => { + domain::PaymentMethodVaultingData::Card(card) => { payment_method_data::PaymentMethodsData::Card( payment_method_data::CardDetailsPaymentMethod::from(card.clone()), ) } - pm_types::PaymentMethodVaultingData::NetworkToken(network_token) => { + domain::PaymentMethodVaultingData::NetworkToken(network_token) => { payment_method_data::PaymentMethodsData::NetworkToken( payment_method_data::NetworkTokenDetailsPaymentMethod::from( network_token.clone(), @@ -1625,7 +1673,7 @@ pub async fn create_pm_additional_data_update( #[instrument(skip_all)] pub async fn vault_payment_method( state: &SessionState, - pmd: &pm_types::PaymentMethodVaultingData, + pmd: &domain::PaymentMethodVaultingData, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, existing_vault_id: Option<domain::VaultId>, @@ -1893,11 +1941,12 @@ pub async fn update_payment_method_core( }, )?; - let pmd = vault::retrieve_payment_method_from_vault(state, merchant_account, &payment_method) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to retrieve payment method from vault")? - .data; + let pmd: domain::PaymentMethodVaultingData = + vault::retrieve_payment_method_from_vault(state, merchant_account, &payment_method) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to retrieve payment method from vault")? + .data; let vault_request_data = request.payment_method_data.map(|payment_method_data| { pm_transforms::generate_pm_vaulting_req_from_update_request(pmd, payment_method_data) diff --git a/crates/router/src/core/payment_methods/network_tokenization.rs b/crates/router/src/core/payment_methods/network_tokenization.rs index 41a94402baf..8aa371e7a73 100644 --- a/crates/router/src/core/payment_methods/network_tokenization.rs +++ b/crates/router/src/core/payment_methods/network_tokenization.rs @@ -30,7 +30,7 @@ use crate::{ routes::{self, metrics}, services::{self, encryption}, settings, - types::{api, domain}, + types::{api, domain, payment_methods as pm_types}, }; pub const NETWORK_TOKEN_SERVICE: &str = "NETWORK_TOKEN"; @@ -45,7 +45,7 @@ pub async fn mk_tokenization_req( customer_id: id_type::CustomerId, tokenization_service: &settings::NetworkTokenizationService, ) -> CustomResult< - (domain::CardNetworkTokenResponsePayload, Option<String>), + (pm_types::CardNetworkTokenResponsePayload, Option<String>), errors::NetworkTokenizationError, > { let enc_key = tokenization_service.public_key.peek().clone(); @@ -62,12 +62,12 @@ pub async fn mk_tokenization_req( .change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed) .attach_printable("Error on jwe encrypt")?; - let order_data = domain::OrderData { + let order_data = pm_types::OrderData { consent_id: uuid::Uuid::new_v4().to_string(), customer_id, }; - let api_payload = domain::ApiPayload { + let api_payload = pm_types::ApiPayload { service: NETWORK_TOKEN_SERVICE.to_string(), card_data: Secret::new(jwt), order_data, @@ -103,7 +103,7 @@ pub async fn mk_tokenization_req( .attach_printable("Error while receiving response") .and_then(|inner| match inner { Err(err_res) => { - let parsed_error: domain::NetworkTokenErrorResponse = err_res + let parsed_error: pm_types::NetworkTokenErrorResponse = err_res .response .parse_struct("Card Network Tokenization Response") .change_context( @@ -124,7 +124,7 @@ pub async fn mk_tokenization_req( logger::error!("Error while deserializing response: {:?}", err); })?; - let network_response: domain::CardNetworkTokenResponse = res + let network_response: pm_types::CardNetworkTokenResponse = res .response .parse_struct("Card Network Tokenization Response") .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?; @@ -143,7 +143,7 @@ pub async fn mk_tokenization_req( "Failed to decrypt the tokenization response from the tokenization service", )?; - let cn_response: domain::CardNetworkTokenResponsePayload = + let cn_response: pm_types::CardNetworkTokenResponsePayload = serde_json::from_str(&card_network_token_response) .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?; Ok((cn_response.clone(), Some(cn_response.card_reference))) @@ -156,7 +156,7 @@ pub async fn generate_network_token( customer_id: id_type::GlobalCustomerId, tokenization_service: &settings::NetworkTokenizationService, ) -> CustomResult< - (domain::GenerateNetworkTokenResponsePayload, String), + (pm_types::GenerateNetworkTokenResponsePayload, String), errors::NetworkTokenizationError, > { let enc_key = tokenization_service.public_key.peek().clone(); @@ -173,12 +173,12 @@ pub async fn generate_network_token( .change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed) .attach_printable("Error on jwe encrypt")?; - let order_data = domain::OrderData { + let order_data = pm_types::OrderData { consent_id: uuid::Uuid::new_v4().to_string(), customer_id, }; - let api_payload = domain::ApiPayload { + let api_payload = pm_types::ApiPayload { service: NETWORK_TOKEN_SERVICE.to_string(), card_data: Secret::new(jwt), order_data, @@ -214,7 +214,7 @@ pub async fn generate_network_token( .attach_printable("Error while receiving response") .and_then(|inner| match inner { Err(err_res) => { - let parsed_error: domain::NetworkTokenErrorResponse = err_res + let parsed_error: pm_types::NetworkTokenErrorResponse = err_res .response .parse_struct("Card Network Tokenization Response") .change_context( @@ -235,7 +235,7 @@ pub async fn generate_network_token( logger::error!("Error while deserializing response: {:?}", err); })?; - let network_response: domain::CardNetworkTokenResponse = res + let network_response: pm_types::CardNetworkTokenResponse = res .response .parse_struct("Card Network Tokenization Response") .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?; @@ -255,7 +255,7 @@ pub async fn generate_network_token( "Failed to decrypt the tokenization response from the tokenization service", )?; - let cn_response: domain::GenerateNetworkTokenResponsePayload = + let cn_response: pm_types::GenerateNetworkTokenResponsePayload = serde_json::from_str(&card_network_token_response) .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?; Ok((cn_response.clone(), cn_response.card_reference)) @@ -271,10 +271,10 @@ pub async fn make_card_network_tokenization_request( optional_cvc: Option<Secret<String>>, customer_id: &id_type::CustomerId, ) -> CustomResult< - (domain::CardNetworkTokenResponsePayload, Option<String>), + (pm_types::CardNetworkTokenResponsePayload, Option<String>), errors::NetworkTokenizationError, > { - let card_data = domain::CardData { + let card_data = pm_types::CardData { card_number: card.card_number.clone(), exp_month: card.card_exp_month.clone(), exp_year: card.card_exp_year.clone(), @@ -320,7 +320,7 @@ pub async fn make_card_network_tokenization_request( card: &api_payment_methods::CardDetail, customer_id: &id_type::GlobalCustomerId, ) -> CustomResult<(NetworkTokenDetails, String), errors::NetworkTokenizationError> { - let card_data = domain::CardData { + let card_data = pm_types::CardData { card_number: card.card_number.clone(), exp_month: card.card_exp_month.clone(), exp_year: card.card_exp_year.clone(), @@ -376,12 +376,12 @@ pub async fn get_network_token( customer_id: id_type::CustomerId, network_token_requestor_ref_id: String, tokenization_service: &settings::NetworkTokenizationService, -) -> CustomResult<domain::TokenResponse, errors::NetworkTokenizationError> { +) -> CustomResult<pm_types::TokenResponse, errors::NetworkTokenizationError> { let mut request = services::Request::new( services::Method::Post, tokenization_service.fetch_token_url.as_str(), ); - let payload = domain::GetCardToken { + let payload = pm_types::GetCardToken { card_reference: network_token_requestor_ref_id, customer_id, }; @@ -411,7 +411,7 @@ pub async fn get_network_token( .attach_printable("Error while receiving response") .and_then(|inner| match inner { Err(err_res) => { - let parsed_error: domain::NetworkTokenErrorResponse = err_res + let parsed_error: pm_types::NetworkTokenErrorResponse = err_res .response .parse_struct("Card Network Tokenization Response") .change_context( @@ -429,7 +429,7 @@ pub async fn get_network_token( Ok(res) => Ok(res), })?; - let token_response: domain::TokenResponse = res + let token_response: pm_types::TokenResponse = res .response .parse_struct("Get Network Token Response") .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?; @@ -444,12 +444,12 @@ pub async fn get_network_token( customer_id: &id_type::GlobalCustomerId, network_token_requestor_ref_id: String, tokenization_service: &settings::NetworkTokenizationService, -) -> CustomResult<domain::TokenResponse, errors::NetworkTokenizationError> { +) -> CustomResult<pm_types::TokenResponse, errors::NetworkTokenizationError> { let mut request = services::Request::new( services::Method::Post, tokenization_service.fetch_token_url.as_str(), ); - let payload = domain::GetCardToken { + let payload = pm_types::GetCardToken { card_reference: network_token_requestor_ref_id, customer_id: customer_id.clone(), }; @@ -479,7 +479,7 @@ pub async fn get_network_token( .attach_printable("Error while receiving response") .and_then(|inner| match inner { Err(err_res) => { - let parsed_error: domain::NetworkTokenErrorResponse = err_res + let parsed_error: pm_types::NetworkTokenErrorResponse = err_res .response .parse_struct("Card Network Tokenization Response") .change_context( @@ -497,7 +497,7 @@ pub async fn get_network_token( Ok(res) => Ok(res), })?; - let token_response: domain::TokenResponse = res + let token_response: pm_types::TokenResponse = res .response .parse_struct("Get Network Token Response") .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?; @@ -656,7 +656,7 @@ pub async fn check_token_status_with_tokenization_service( services::Method::Post, tokenization_service.check_token_status_url.as_str(), ); - let payload = domain::CheckTokenStatus { + let payload = pm_types::CheckTokenStatus { card_reference: network_token_requestor_reference_id, customer_id: customer_id.clone(), }; @@ -683,7 +683,7 @@ pub async fn check_token_status_with_tokenization_service( .attach_printable("Error while receiving response") .and_then(|inner| match inner { Err(err_res) => { - let parsed_error: domain::NetworkTokenErrorResponse = err_res + let parsed_error: pm_types::NetworkTokenErrorResponse = err_res .response .parse_struct("Delete Network Tokenization Response") .change_context( @@ -704,17 +704,17 @@ pub async fn check_token_status_with_tokenization_service( logger::error!("Error while deserializing response: {:?}", err); })?; - let check_token_status_response: domain::CheckTokenStatusResponse = res + let check_token_status_response: pm_types::CheckTokenStatusResponse = res .response .parse_struct("Delete Network Tokenization Response") .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?; match check_token_status_response.payload.token_status { - domain::TokenStatus::Active => Ok(( + pm_types::TokenStatus::Active => Ok(( Some(check_token_status_response.payload.token_expiry_month), Some(check_token_status_response.payload.token_expiry_year), )), - domain::TokenStatus::Inactive => Ok((None, None)), + pm_types::TokenStatus::Inactive => Ok((None, None)), } } @@ -791,7 +791,7 @@ pub async fn delete_network_token_from_tokenization_service( services::Method::Post, tokenization_service.delete_token_url.as_str(), ); - let payload = domain::DeleteCardToken { + let payload = pm_types::DeleteCardToken { card_reference: network_token_requestor_reference_id, customer_id: customer_id.clone(), }; @@ -820,7 +820,7 @@ pub async fn delete_network_token_from_tokenization_service( .attach_printable("Error while receiving response") .and_then(|inner| match inner { Err(err_res) => { - let parsed_error: domain::NetworkTokenErrorResponse = err_res + let parsed_error: pm_types::NetworkTokenErrorResponse = err_res .response .parse_struct("Delete Network Tokenization Response") .change_context( @@ -841,14 +841,14 @@ pub async fn delete_network_token_from_tokenization_service( logger::error!("Error while deserializing response: {:?}", err); })?; - let delete_token_response: domain::DeleteNetworkTokenResponse = res + let delete_token_response: pm_types::DeleteNetworkTokenResponse = res .response .parse_struct("Delete Network Tokenization Response") .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?; logger::info!("Delete Network Token Response: {:?}", delete_token_response); - if delete_token_response.status == domain::DeleteNetworkTokenStatus::Success { + if delete_token_response.status == pm_types::DeleteNetworkTokenStatus::Success { Ok(true) } else { Err(errors::NetworkTokenizationError::DeleteNetworkTokenFailed) diff --git a/crates/router/src/core/payment_methods/tokenize.rs b/crates/router/src/core/payment_methods/tokenize.rs index 853d3c0a2bd..bd0a5a2192b 100644 --- a/crates/router/src/core/payment_methods/tokenize.rs +++ b/crates/router/src/core/payment_methods/tokenize.rs @@ -7,9 +7,7 @@ use common_utils::{ transformers::{ForeignFrom, ForeignTryFrom}, }; use error_stack::{report, ResultExt}; -use hyperswitch_domain_models::{ - network_tokenization as nt_domain_types, router_request_types as domain_request_types, -}; +use hyperswitch_domain_models::router_request_types as domain_request_types; use masking::{ExposeInterface, Secret}; use router_env::logger; @@ -21,7 +19,7 @@ use crate::{ }, errors::{self, RouterResult}, services, - types::{api, domain}, + types::{api, domain, payment_methods as pm_types}, SessionState, }; @@ -137,10 +135,7 @@ pub async fn tokenize_cards( } // Data types -type NetworkTokenizationResponse = ( - nt_domain_types::CardNetworkTokenResponsePayload, - Option<String>, -); +type NetworkTokenizationResponse = (pm_types::CardNetworkTokenResponsePayload, Option<String>); pub struct StoreLockerResponse { pub store_card_resp: pm_transformers::StoreCardRespPayload, @@ -162,7 +157,7 @@ pub struct NetworkTokenizationBuilder<'a, S: State> { pub card_cvc: Option<Secret<String>>, /// Network token details - pub network_token: Option<&'a nt_domain_types::CardNetworkTokenResponsePayload>, + pub network_token: Option<&'a pm_types::CardNetworkTokenResponsePayload>, /// Stored card details pub stored_card: Option<&'a pm_transformers::StoreCardRespPayload>, diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 233dade651c..87f7e38c935 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -522,14 +522,14 @@ pub fn mk_add_card_response_hs( #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub fn generate_pm_vaulting_req_from_update_request( - pm_create: pm_types::PaymentMethodVaultingData, + pm_create: domain::PaymentMethodVaultingData, pm_update: api::PaymentMethodUpdateData, -) -> pm_types::PaymentMethodVaultingData { +) -> domain::PaymentMethodVaultingData { match (pm_create, pm_update) { ( - pm_types::PaymentMethodVaultingData::Card(card_create), + domain::PaymentMethodVaultingData::Card(card_create), api::PaymentMethodUpdateData::Card(update_card), - ) => pm_types::PaymentMethodVaultingData::Card(api::CardDetail { + ) => domain::PaymentMethodVaultingData::Card(api::CardDetail { card_number: card_create.card_number, card_exp_month: card_create.card_exp_month, card_exp_year: card_create.card_exp_year, @@ -571,6 +571,20 @@ pub fn generate_payment_method_response( .map(transformers::ForeignFrom::foreign_from) .collect::<Vec<_>>() }); + let network_token_pmd = payment_method + .network_token_payment_method_data + .clone() + .map(|data| data.into_inner()) + .and_then(|data| match data { + domain::PaymentMethodsData::NetworkToken(token) => { + Some(api::NetworkTokenDetailsPaymentMethod::from(token)) + } + _ => None, + }); + + let network_token = network_token_pmd.map(|pmd| api::NetworkTokenResponse { + payment_method_data: pmd, + }); let resp = api::PaymentMethodResponse { merchant_id: payment_method.merchant_id.to_owned(), @@ -583,6 +597,7 @@ pub fn generate_payment_method_response( last_used_at: Some(payment_method.last_used_at), payment_method_data: pmd, connector_tokens, + network_token, }; Ok(resp) @@ -839,15 +854,6 @@ pub fn get_card_detail( Ok(card_detail) } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -impl From<api::PaymentMethodCreateData> for pm_types::PaymentMethodVaultingData { - fn from(item: api::PaymentMethodCreateData) -> Self { - match item { - api::PaymentMethodCreateData::Card(card) => Self::Card(card), - } - } -} - //------------------------------------------------TokenizeService------------------------------------------------ pub fn mk_crud_locker_request( locker: &settings::Locker, @@ -961,6 +967,21 @@ impl transformers::ForeignTryFrom<domain::PaymentMethod> for api::CustomerPaymen .map(|billing| billing.into_inner()) .map(From::from); + let network_token_pmd = item + .network_token_payment_method_data + .clone() + .map(|data| data.into_inner()) + .and_then(|data| match data { + domain::PaymentMethodsData::NetworkToken(token) => { + Some(api::NetworkTokenDetailsPaymentMethod::from(token)) + } + _ => None, + }); + + let network_token_resp = network_token_pmd.map(|pmd| api::NetworkTokenResponse { + payment_method_data: pmd, + }); + // TODO: check how we can get this field let recurring_enabled = true; @@ -977,6 +998,7 @@ impl transformers::ForeignTryFrom<domain::PaymentMethod> for api::CustomerPaymen requires_cvv: true, is_default: false, billing: payment_method_billing, + network_tokenization: network_token_resp, }) } } @@ -1033,7 +1055,7 @@ impl transformers::ForeignFrom<api_models::payment_methods::ConnectorTokenDetail } = item; Self { - connector_token: token, + connector_token: token.expose().clone(), // TODO: check why do we need this field payment_method_subtype: None, original_payment_authorized_amount, @@ -1075,7 +1097,7 @@ impl original_payment_authorized_amount, original_payment_authorized_currency, metadata, - token: connector_token, + token: Secret::new(connector_token), // Token that is derived from payments mandate reference will always be multi use token token_type: common_enums::TokenizationType::MultiUse, } diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index f65f048885c..0325acd5991 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1252,9 +1252,7 @@ pub async fn call_to_vault<V: pm_types::VaultingInterface>( #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] -pub async fn get_fingerprint_id_from_vault< - D: pm_types::VaultingDataInterface + serde::Serialize, ->( +pub async fn get_fingerprint_id_from_vault<D: domain::VaultingDataInterface + serde::Serialize>( state: &routes::SessionState, data: &D, key: String, @@ -1286,7 +1284,7 @@ pub async fn get_fingerprint_id_from_vault< pub async fn add_payment_method_to_vault( state: &routes::SessionState, merchant_account: &domain::MerchantAccount, - pmd: &pm_types::PaymentMethodVaultingData, + pmd: &domain::PaymentMethodVaultingData, existing_vault_id: Option<domain::VaultId>, ) -> CustomResult<pm_types::AddVaultResponse, errors::VaultError> { let payload = pm_types::AddVaultRequest { diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 1c69852a108..bcf0d624ff9 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -2613,7 +2613,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::SetupMandateRe original_payment_authorized_amount: Some(net_amount), original_payment_authorized_currency: Some(currency), metadata: None, - token, + token: masking::Secret::new(token), token_type: common_enums::TokenizationType::MultiUse, }; diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index 87475fcd89a..9c5030a30a0 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -4,14 +4,15 @@ pub use api_models::payment_methods::{ CardNetworkTokenizeResponse, CardType, CustomerPaymentMethod, CustomerPaymentMethodsListResponse, DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, MigrateCardDetail, - PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate, - PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId, - PaymentMethodIntentConfirm, PaymentMethodIntentCreate, PaymentMethodListData, - PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodMigrate, - PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodResponseData, - PaymentMethodUpdate, PaymentMethodUpdateData, PaymentMethodsData, TokenizePayloadEncrypted, - TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, - TokenizedWalletValue2, TotalPaymentMethodCountResponse, + NetworkTokenDetailsPaymentMethod, NetworkTokenResponse, PaymentMethodCollectLinkRenderRequest, + PaymentMethodCollectLinkRequest, PaymentMethodCreate, PaymentMethodCreateData, + PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodIntentConfirm, + PaymentMethodIntentCreate, PaymentMethodListData, PaymentMethodListRequest, + PaymentMethodListResponse, PaymentMethodMigrate, PaymentMethodMigrateResponse, + PaymentMethodResponse, PaymentMethodResponseData, PaymentMethodUpdate, PaymentMethodUpdateData, + PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, + TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, + TotalPaymentMethodCountResponse, }; #[cfg(all( any(feature = "v2", feature = "v1"), diff --git a/crates/router/src/types/domain.rs b/crates/router/src/types/domain.rs index 51f07fd6d2e..88bc1bbd34f 100644 --- a/crates/router/src/types/domain.rs +++ b/crates/router/src/types/domain.rs @@ -40,6 +40,15 @@ pub mod payment_methods { pub mod consts { pub use hyperswitch_domain_models::consts::*; } +pub mod payment_method_data { + pub use hyperswitch_domain_models::payment_method_data::*; +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub mod vault { + pub use hyperswitch_domain_models::vault::*; +} + pub mod payments; pub mod types; #[cfg(feature = "olap")] @@ -54,8 +63,10 @@ pub use event::*; pub use merchant_connector_account::*; pub use merchant_key_store::*; pub use network_tokenization::*; +pub use payment_method_data::*; pub use payment_methods::*; -pub use payments::*; #[cfg(feature = "olap")] pub use user::*; pub use user_key_store::*; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub use vault::*; diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rs index d639bc44bc8..2f580b7d3ee 100644 --- a/crates/router/src/types/payment_methods.rs +++ b/crates/router/src/types/payment_methods.rs @@ -1,9 +1,20 @@ +use std::fmt::Debug; + +use api_models::enums as api_enums; +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] +use cards::CardNumber; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +use cards::{CardNumber, NetworkToken}; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use common_utils::generate_id; +use common_utils::id_type; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use hyperswitch_domain_models::payment_method_data::NetworkTokenDetails; -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use masking::Secret; +use serde::{Deserialize, Serialize}; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use crate::{ @@ -18,11 +29,6 @@ pub trait VaultingInterface { fn get_vaulting_flow_name() -> &'static str; } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -pub trait VaultingDataInterface { - fn get_vaulting_data_key(&self) -> String; -} - #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultFingerprintRequest { @@ -39,7 +45,7 @@ pub struct VaultFingerprintResponse { #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AddVaultRequest<D> { - pub entity_id: common_utils::id_type::MerchantId, + pub entity_id: id_type::MerchantId, pub vault_id: domain::VaultId, pub data: D, pub ttl: i64, @@ -48,7 +54,7 @@ pub struct AddVaultRequest<D> { #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AddVaultResponse { - pub entity_id: common_utils::id_type::MerchantId, + pub entity_id: id_type::MerchantId, pub vault_id: domain::VaultId, pub fingerprint_id: Option<String>, } @@ -113,23 +119,6 @@ impl VaultingInterface for VaultDelete { } } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] -pub enum PaymentMethodVaultingData { - Card(api::CardDetail), - NetworkToken(NetworkTokenDetails), -} - -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -impl VaultingDataInterface for PaymentMethodVaultingData { - fn get_vaulting_data_key(&self) -> String { - match &self { - Self::Card(card) => card.card_number.to_string(), - Self::NetworkToken(network_token) => network_token.network_token.to_string(), - } - } -} - #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub struct SavedPMLPaymentsInfo { pub payment_intent: storage::PaymentIntent, @@ -142,26 +131,235 @@ pub struct SavedPMLPaymentsInfo { #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultRetrieveRequest { - pub entity_id: common_utils::id_type::MerchantId, + pub entity_id: id_type::MerchantId, pub vault_id: domain::VaultId, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultRetrieveResponse { - pub data: PaymentMethodVaultingData, + pub data: domain::PaymentMethodVaultingData, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultDeleteRequest { - pub entity_id: common_utils::id_type::MerchantId, + pub entity_id: id_type::MerchantId, pub vault_id: domain::VaultId, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultDeleteResponse { - pub entity_id: common_utils::id_type::MerchantId, + pub entity_id: id_type::MerchantId, pub vault_id: domain::VaultId, } + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CardData { + pub card_number: CardNumber, + pub exp_month: Secret<String>, + pub exp_year: Secret<String>, + pub card_security_code: Option<Secret<String>>, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CardData { + pub card_number: CardNumber, + pub exp_month: Secret<String>, + pub exp_year: Secret<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub card_security_code: Option<Secret<String>>, +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OrderData { + pub consent_id: String, + pub customer_id: id_type::CustomerId, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OrderData { + pub consent_id: String, + pub customer_id: id_type::GlobalCustomerId, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ApiPayload { + pub service: String, + pub card_data: Secret<String>, //encrypted card data + pub order_data: OrderData, + pub key_id: String, + pub should_send_token: bool, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct CardNetworkTokenResponse { + pub payload: Secret<String>, //encrypted payload +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CardNetworkTokenResponsePayload { + pub card_brand: api_enums::CardNetwork, + pub card_fingerprint: Option<Secret<String>>, + pub card_reference: String, + pub correlation_id: String, + pub customer_id: String, + pub par: String, + pub token: CardNumber, + pub token_expiry_month: Secret<String>, + pub token_expiry_year: Secret<String>, + pub token_isin: String, + pub token_last_four: String, + pub token_status: String, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GenerateNetworkTokenResponsePayload { + pub card_brand: api_enums::CardNetwork, + pub card_fingerprint: Option<Secret<String>>, + pub card_reference: String, + pub correlation_id: String, + pub customer_id: String, + pub par: String, + pub token: NetworkToken, + pub token_expiry_month: Secret<String>, + pub token_expiry_year: Secret<String>, + pub token_isin: String, + pub token_last_four: String, + pub token_status: String, +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] +#[derive(Debug, Serialize)] +pub struct GetCardToken { + pub card_reference: String, + pub customer_id: id_type::CustomerId, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, Serialize)] +pub struct GetCardToken { + pub card_reference: String, + pub customer_id: id_type::GlobalCustomerId, +} +#[derive(Debug, Deserialize)] +pub struct AuthenticationDetails { + pub cryptogram: Secret<String>, + pub token: CardNumber, //network token +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct TokenDetails { + pub exp_month: Secret<String>, + pub exp_year: Secret<String>, +} + +#[derive(Debug, Deserialize)] +pub struct TokenResponse { + pub authentication_details: AuthenticationDetails, + pub network: api_enums::CardNetwork, + pub token_details: TokenDetails, +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] +#[derive(Debug, Serialize, Deserialize)] +pub struct DeleteCardToken { + pub card_reference: String, //network token requestor ref id + pub customer_id: id_type::CustomerId, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, Serialize, Deserialize)] +pub struct DeleteCardToken { + pub card_reference: String, //network token requestor ref id + pub customer_id: id_type::GlobalCustomerId, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "UPPERCASE")] +pub enum DeleteNetworkTokenStatus { + Success, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct NetworkTokenErrorInfo { + pub code: String, + pub developer_message: String, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct NetworkTokenErrorResponse { + pub error_message: String, + pub error_info: NetworkTokenErrorInfo, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct DeleteNetworkTokenResponse { + pub status: DeleteNetworkTokenStatus, +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] +#[derive(Debug, Serialize, Deserialize)] +pub struct CheckTokenStatus { + pub card_reference: String, + pub customer_id: id_type::CustomerId, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, Serialize, Deserialize)] +pub struct CheckTokenStatus { + pub card_reference: String, + pub customer_id: id_type::GlobalCustomerId, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum TokenStatus { + Active, + Inactive, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CheckTokenStatusResponsePayload { + pub token_expiry_month: Secret<String>, + pub token_expiry_year: Secret<String>, + pub token_status: TokenStatus, +} + +#[derive(Debug, Deserialize)] +pub struct CheckTokenStatusResponse { + pub payload: CheckTokenStatusResponsePayload, +}
2025-02-19T10:30:38Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Refactor network tokenization flow for v2 payment method. 1. moved the network tokenization req, response types from domain to router types, since the types are not generic for Hyperswitch but req and response types of token service. 2. replaced hanging functions to impl based in the flow 3. Update ListCustomerPaymentMethod response and Payment Method response with network token 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` 4. `crates/router/src/configs` 5. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
3667a7ffd216e165e1f51ad1ceac05d6901bb187
3667a7ffd216e165e1f51ad1ceac05d6901bb187
juspay/hyperswitch
juspay__hyperswitch-7495
Bug: refactor(connector): [BILLWERK, FISERVEMEA, TSYS] use LazyLock instead of lazy_static! Use LazyLock instead of lazy_static!
diff --git a/crates/hyperswitch_connectors/src/connectors/billwerk.rs b/crates/hyperswitch_connectors/src/connectors/billwerk.rs index 4d76dcd5706..4d5e324b39f 100644 --- a/crates/hyperswitch_connectors/src/connectors/billwerk.rs +++ b/crates/hyperswitch_connectors/src/connectors/billwerk.rs @@ -1,5 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; + use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use base64::Engine; use common_enums::enums; @@ -44,7 +46,6 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; -use lazy_static::lazy_static; use masking::{Mask, PeekInterface}; use transformers::{ self as billwerk, BillwerkAuthType, BillwerkCaptureRequest, BillwerkErrorResponse, @@ -808,8 +809,8 @@ impl IncomingWebhook for Billwerk { } } -lazy_static! { - static ref BILLWERK_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { +static BILLWERK_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, @@ -833,7 +834,7 @@ lazy_static! { billwerk_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, - PaymentMethodDetails{ + PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), @@ -846,13 +847,13 @@ lazy_static! { } }), ), - } + }, ); billwerk_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, - PaymentMethodDetails{ + PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), @@ -865,24 +866,23 @@ lazy_static! { } }), ), - } + }, ); billwerk_supported_payment_methods - }; + }); - static ref BILLWERK_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { - display_name: "Billwerk", - description: "Billwerk+ Pay is an acquirer independent payment gateway that's easy to setup with more than 50 recurring and non-recurring payment methods.", - connector_type: enums::PaymentConnectorCategory::PaymentGateway, - }; +static BILLWERK_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Billwerk", + description: "Billwerk+ Pay is an acquirer independent payment gateway that's easy to setup with more than 50 recurring and non-recurring payment methods.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; - static ref BILLWERK_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); -} +static BILLWERK_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Billwerk { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { - Some(&*BILLWERK_CONNECTOR_INFO) + Some(&BILLWERK_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { @@ -890,6 +890,6 @@ impl ConnectorSpecifications for Billwerk { } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { - Some(&*BILLWERK_SUPPORTED_WEBHOOK_FLOWS) + Some(&BILLWERK_SUPPORTED_WEBHOOK_FLOWS) } } diff --git a/crates/hyperswitch_connectors/src/connectors/fiservemea.rs b/crates/hyperswitch_connectors/src/connectors/fiservemea.rs index cb00c66a4fd..95c252cb685 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiservemea.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiservemea.rs @@ -1,5 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; + use base64::Engine; use common_enums::enums; use common_utils::{ @@ -41,7 +43,6 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks, }; -use lazy_static::lazy_static; use masking::{ExposeInterface, Mask, PeekInterface}; use ring::hmac; use time::OffsetDateTime; @@ -784,8 +785,8 @@ impl webhooks::IncomingWebhook for Fiservemea { } } -lazy_static! { - static ref FISERVEMEA_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { +static FISERVEMEA_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, @@ -809,7 +810,7 @@ lazy_static! { fiservemea_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, - PaymentMethodDetails{ + PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), @@ -822,13 +823,13 @@ lazy_static! { } }), ), - } + }, ); fiservemea_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, - PaymentMethodDetails{ + PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), @@ -841,24 +842,23 @@ lazy_static! { } }), ), - } + }, ); fiservemea_supported_payment_methods - }; + }); - static ref FISERVEMEA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { - display_name: "Fiservemea", - description: "Fiserv powers over 6+ million merchants and 10,000+ financial institutions enabling them to accept billions of payments a year.", - connector_type: enums::PaymentConnectorCategory::BankAcquirer, - }; +static FISERVEMEA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Fiservemea", + description: "Fiserv powers over 6+ million merchants and 10,000+ financial institutions enabling them to accept billions of payments a year.", + connector_type: enums::PaymentConnectorCategory::BankAcquirer, +}; - static ref FISERVEMEA_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); -} +static FISERVEMEA_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Fiservemea { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { - Some(&*FISERVEMEA_CONNECTOR_INFO) + Some(&FISERVEMEA_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { @@ -866,6 +866,6 @@ impl ConnectorSpecifications for Fiservemea { } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { - Some(&*FISERVEMEA_SUPPORTED_WEBHOOK_FLOWS) + Some(&FISERVEMEA_SUPPORTED_WEBHOOK_FLOWS) } } diff --git a/crates/hyperswitch_connectors/src/connectors/tsys.rs b/crates/hyperswitch_connectors/src/connectors/tsys.rs index 7a0fe0bdc93..d5a6fd834e2 100644 --- a/crates/hyperswitch_connectors/src/connectors/tsys.rs +++ b/crates/hyperswitch_connectors/src/connectors/tsys.rs @@ -1,5 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; + use common_enums::enums; use common_utils::{ errors::CustomResult, @@ -43,7 +45,6 @@ use hyperswitch_interfaces::{ }, webhooks, }; -use lazy_static::lazy_static; use transformers as tsys; use crate::{constants::headers, types::ResponseRouterData, utils}; @@ -645,78 +646,76 @@ impl webhooks::IncomingWebhook for Tsys { } } -lazy_static! { - static ref TSYS_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { - let supported_capture_methods = vec![ - enums::CaptureMethod::Automatic, - enums::CaptureMethod::Manual, - enums::CaptureMethod::SequentialAutomatic, - ]; - - let supported_card_network = vec![ - common_enums::CardNetwork::Mastercard, - common_enums::CardNetwork::Visa, - common_enums::CardNetwork::AmericanExpress, - common_enums::CardNetwork::Discover, - common_enums::CardNetwork::JCB, - common_enums::CardNetwork::UnionPay, - ]; - - let mut tsys_supported_payment_methods = SupportedPaymentMethods::new(); - - tsys_supported_payment_methods.add( - enums::PaymentMethod::Card, - enums::PaymentMethodType::Credit, - PaymentMethodDetails{ - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods.clone(), - specific_features: Some( - api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ - api_models::feature_matrix::CardSpecificFeatures { - three_ds: common_enums::FeatureStatus::NotSupported, - no_three_ds: common_enums::FeatureStatus::Supported, - supported_card_networks: supported_card_network.clone(), - } - }), - ), - } - ); - - tsys_supported_payment_methods.add( - enums::PaymentMethod::Card, - enums::PaymentMethodType::Debit, - PaymentMethodDetails{ - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods.clone(), - specific_features: Some( - api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ - api_models::feature_matrix::CardSpecificFeatures { - three_ds: common_enums::FeatureStatus::NotSupported, - no_three_ds: common_enums::FeatureStatus::Supported, - supported_card_networks: supported_card_network.clone(), - } - }), - ), - } - ); - - tsys_supported_payment_methods - }; - - static ref TSYS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { - display_name: "Tsys", - description: "TSYS, a Global Payments company, is the payment stack for the future, powered by unmatched expertise.", - connector_type: enums::PaymentConnectorCategory::BankAcquirer, - }; - - static ref TSYS_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); -} +static TSYS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::UnionPay, + ]; + + let mut tsys_supported_payment_methods = SupportedPaymentMethods::new(); + + tsys_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + tsys_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + tsys_supported_payment_methods +}); + +static TSYS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Tsys", + description: "TSYS, a Global Payments company, is the payment stack for the future, powered by unmatched expertise.", + connector_type: enums::PaymentConnectorCategory::BankAcquirer, +}; + +static TSYS_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Tsys { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { - Some(&*TSYS_CONNECTOR_INFO) + Some(&TSYS_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { @@ -724,6 +723,6 @@ impl ConnectorSpecifications for Tsys { } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { - Some(&*TSYS_SUPPORTED_WEBHOOK_FLOWS) + Some(&TSYS_SUPPORTED_WEBHOOK_FLOWS) } }
2025-03-12T08:31:27Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/7495) ## Description <!-- Describe your changes in detail --> Refactored the feature matrix PR by using `LazyLock` instead of `lazy_static!` ### 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)? --> Postman Test Feature API curl: ``` curl --location 'http://localhost:8080/feature_matrix' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: {{api_key}}' ``` Response: ``` { "connector_count": 3, "connectors": [ { "name": "BILLWERK", "display_name": "Billwerk", "description": "Billwerk+ Pay is an acquirer independent payment gateway that's easy to setup with more than 50 recurring and non-recurring payment methods.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "debit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "Discover", "JCB", "UnionPay", "DinersClub", "Interac", "CartesBancaires" ], "supported_countries": [ "DK", "DE", "FR", "SE" ], "supported_currencies": [ "DKK", "NOK" ] }, { "payment_method": "card", "payment_method_type": "credit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "Discover", "JCB", "UnionPay", "DinersClub", "Interac", "CartesBancaires" ], "supported_countries": [ "SE", "FR", "DE", "DK" ], "supported_currencies": [ "NOK", "DKK" ] } ], "supported_webhook_flows": [] }, { "name": "FISERVEMEA", "display_name": "Fiservemea", "description": "Fiserv powers over 6+ million merchants and 10,000+ financial institutions enabling them to accept billions of payments a year.", "category": "bank_acquirer", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "debit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "Discover", "JCB", "UnionPay", "DinersClub", "Interac", "CartesBancaires" ], "supported_countries": [ "AE", "PL", "FR", "ES", "GB", "ZA", "DE", "NL", "IT" ], "supported_currencies": [ "SSP", "BIF", "MOP", "KMF", "HNL", "SYP", "CVE", "SGD", "KHR", "MXN", "NPR", "RUB", "TMT", "BRL", "MRU", "SHP", "KPW", "KZT", "SLE", "CZK", "CAD", "VUV", "PYG", "SOS", "AFN", "MVR", "YER", "ZAR", "TTD", "CHF", "AMD", "NGN", "KYD", "ERN", "PKR", "MZN", "TJS", "BTN", "IDR", "SCR", "AED", "MUR", "CLP", "XPF", "TOP", "PHP", "THB", "AZN", "RON", "DZD", "SBD", "PAB", "HRK", "KRW", "SEK", "BOB", "LKR", "SAR", "KGS", "NIO", "RSD", "PLN", "NZD", "BYN", "SVC", "GYD", "SZL", "USD", "ISK", "BMD", "COP", "SDG", "TZS", "KWD", "UYU", "JOD", "CUP", "LYD", "LAK", "DOP", "AUD", "VES", "FJD", "CRC", "FKP", "HKD", "IRR", "BDT", "BBD", "EUR", "BHD", "UAH", "MGA", "CNY", "HTG", "ALL", "INR", "GHS", "MAD", "TWD", "MYR", "BND", "NAD", "QAR", "GIP", "GEL", "AOA", "UGX", "LSL", "XAF", "LBP", "DJF", "ETB", "TND", "XCD", "SRD", "GNF", "BGN", "GTQ", "MWK", "ZMW", "MKD", "HUF", "PEN", "RWF", "DKK", "BZD", "IQD", "ANG", "ARS", "GBP", "WST", "ZWL", "PGK", "TRY", "KES", "MDL", "MNT", "CDF", "BAM", "LRD", "JPY", "GMD", "STN", "VND", "BWP", "OMR", "NOK", "SLL", "JMD", "XOF", "MMK", "EGP", "AWG", "ILS", "UZS", "BSD" ] }, { "payment_method": "card", "payment_method_type": "credit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "Discover", "JCB", "UnionPay", "DinersClub", "Interac", "CartesBancaires" ], "supported_countries": [ "NL", "ES", "DE", "PL", "IT", "AE", "GB", "ZA", "FR" ], "supported_currencies": [ "JOD", "AED", "ALL", "BOB", "ERN", "LBP", "PAB", "HNL", "AZN", "TMT", "DKK", "AWG", "PKR", "LAK", "PGK", "JMD", "CUP", "PHP", "BAM", "THB", "FKP", "HRK", "UYU", "KZT", "BYN", "PLN", "SDG", "VND", "NZD", "KWD", "CDF", "SCR", "VUV", "CHF", "USD", "GYD", "ANG", "DOP", "MKD", "STN", "SAR", "QAR", "PEN", "RSD", "BRL", "KGS", "SGD", "TWD", "BHD", "KHR", "MOP", "GHS", "UGX", "XPF", "SSP", "CAD", "TOP", "OMR", "MXN", "BGN", "RUB", "MDL", "GNF", "PYG", "SRD", "AFN", "MNT", "NOK", "XAF", "BWP", "NGN", "GIP", "CZK", "MGA", "DZD", "YER", "DJF", "SBD", "CNY", "ZAR", "LYD", "BMD", "MUR", "NIO", "UZS", "GBP", "VES", "SVC", "CVE", "NPR", "RON", "KMF", "BZD", "KPW", "SLL", "LKR", "AUD", "LSL", "XCD", "TJS", "KYD", "UAH", "ARS", "NAD", "SEK", "GTQ", "BSD", "IDR", "WST", "AMD", "BTN", "HUF", "ZMW", "COP", "BIF", "FJD", "INR", "IRR", "GEL", "HTG", "SOS", "CLP", "ISK", "MVR", "RWF", "BBD", "KRW", "BDT", "LRD", "AOA", "MMK", "MWK", "SLE", "XOF", "MRU", "KES", "MYR", "MZN", "SYP", "SZL", "TRY", "SHP", "TTD", "GMD", "TZS", "ETB", "ILS", "IQD", "CRC", "BND", "HKD", "EGP", "JPY", "MAD", "TND", "EUR", "ZWL" ] } ], "supported_webhook_flows": [] }, { "name": "TSYS", "display_name": "Tsys", "description": "TSYS, a Global Payments company, is the payment stack for the future, powered by unmatched expertise.", "category": "bank_acquirer", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "Discover", "JCB", "UnionPay" ], "supported_countries": [ "NA" ], "supported_currencies": [ "CUP", "SZL", "GMD", "AMD", "MRU", "BWP", "SSP", "QAR", "XOF", "VES", "XAF", "BBD", "BSD", "ETB", "GBP", "BHD", "UYU", "XCD", "JPY", "VUV", "SAR", "ZAR", "MOP", "MDL", "IRR", "SGD", "MVR", "BIF", "BTN", "STN", "AED", "TTD", "TWD", "UZS", "KZT", "ALL", "UGX", "DOP", "BMD", "FJD", "KGS", "KPW", "ZMW", "IQD", "HRK", "KMF", "GTQ", "LSL", "NOK", "MWK", "CDF", "KRW", "ERN", "RUB", "GEL", "MGA", "OMR", "HUF", "HTG", "PYG", "MUR", "HKD", "BZD", "LRD", "SRD", "THB", "IDR", "TJS", "TRY", "VND", "JOD", "PKR", "GNF", "LKR", "TND", "BDT", "DJF", "SDG", "AOA", "SVC", "PEN", "KYD", "BRL", "JMD", "ISK", "COP", "BAM", "BOB", "CVE", "INR", "RWF", "SCR", "YER", "LYD", "MYR", "LBP", "CZK", "NIO", "SEK", "DKK", "UAH", "USD", "AZN", "RON", "HNL", "SYP", "CHF", "PAB", "NGN", "NPR", "AFN", "CAD", "ANG", "GYD", "MXN", "BND", "LAK", "PGK", "PLN", "SHP", "ARS", "KWD", "ILS", "TMT", "XPF", "ZWL", "FKP", "CLP", "AUD", "DZD", "GHS", "PHP", "NAD", "TZS", "CNY", "MAD", "NZD", "MNT", "WST", "KHR", "CRC", "SLE", "AWG", "GIP", "BGN", "RSD", "SOS", "MKD", "MMK", "TOP", "MZN", "BYN", "KES", "EGP", "EUR", "SBD" ] }, { "payment_method": "card", "payment_method_type": "debit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "Discover", "JCB", "UnionPay" ], "supported_countries": [ "NA" ], "supported_currencies": [ "AZN", "SAR", "ZWL", "MRU", "SZL", "TRY", "TOP", "YER", "LKR", "ISK", "NIO", "TTD", "BMD", "PAB", "MNT", "BTN", "SYP", "HUF", "CHF", "UAH", "DJF", "DOP", "XPF", "MVR", "WST", "ZMW", "TMT", "TWD", "LBP", "PGK", "XOF", "ARS", "PLN", "MUR", "MZN", "NGN", "MDL", "SDG", "SLE", "VND", "STN", "KZT", "THB", "SGD", "HRK", "AUD", "NAD", "KHR", "BSD", "GEL", "NOK", "KPW", "GNF", "GHS", "MWK", "RUB", "MAD", "GMD", "BWP", "VUV", "GTQ", "BZD", "MYR", "BND", "KMF", "CVE", "SSP", "BBD", "ALL", "UZS", "ERN", "GYD", "CUP", "TJS", "CZK", "OMR", "GIP", "XCD", "CNY", "SBD", "RON", "KES", "HKD", "IQD", "BDT", "CDF", "SEK", "JPY", "HNL", "ETB", "GBP", "VES", "TZS", "MXN", "XAF", "CLP", "AMD", "LAK", "EGP", "NZD", "SCR", "SHP", "ILS", "KRW", "SOS", "MGA", "JMD", "ZAR", "NPR", "BAM", "BIF", "EUR", "UYU", "CRC", "RSD", "TND", "PKR", "SRD", "AED", "BOB", "INR", "MOP", "USD", "PEN", "LRD", "UGX", "MMK", "KGS", "BRL", "SVC", "FKP", "ANG", "MKD", "BGN", "BHD", "PHP", "IRR", "KYD", "RWF", "LSL", "QAR", "DKK", "IDR", "DZD", "LYD", "AWG", "AFN", "KWD", "BYN", "JOD", "AOA", "HTG", "COP", "FJD", "CAD", "PYG" ] } ], "supported_webhook_flows": [] }, ] } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
662e45f0037c0aa039c1de72500c6004322f3ffb
662e45f0037c0aa039c1de72500c6004322f3ffb
juspay/hyperswitch
juspay__hyperswitch-7498
Bug: feat(analytics): modify authentication queries and add generate report for authentications hotfix Need to modify the authentication analytics queries to differentiate between frictionless flow and challenge flow through the authentication_type field. Introduce support for authentication report generation, similar to the existing reports for payments, refunds, and disputes.
diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs index a2640be6ead..bdcbdd86a94 100644 --- a/crates/analytics/src/auth_events/core.rs +++ b/crates/analytics/src/auth_events/core.rs @@ -165,6 +165,7 @@ pub async fn get_filters( .filter_map(|fil: AuthEventFilterRow| match dim { AuthEventDimensions::AuthenticationStatus => fil.authentication_status.map(|i| i.as_ref().to_string()), AuthEventDimensions::TransactionStatus => fil.trans_status.map(|i| i.as_ref().to_string()), + AuthEventDimensions::AuthenticationType => fil.authentication_type.map(|i| i.as_ref().to_string()), AuthEventDimensions::ErrorMessage => fil.error_message, AuthEventDimensions::AuthenticationConnector => fil.authentication_connector.map(|i| i.as_ref().to_string()), AuthEventDimensions::MessageVersion => fil.message_version, diff --git a/crates/analytics/src/auth_events/filters.rs b/crates/analytics/src/auth_events/filters.rs index da8e0b7cfa3..5f65eeaa279 100644 --- a/crates/analytics/src/auth_events/filters.rs +++ b/crates/analytics/src/auth_events/filters.rs @@ -1,4 +1,5 @@ use api_models::analytics::{auth_events::AuthEventDimensions, Granularity, TimeRange}; +use common_enums::DecoupledAuthenticationType; use common_utils::errors::ReportSwitchExt; use diesel_models::enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; use error_stack::ResultExt; @@ -54,6 +55,7 @@ where pub struct AuthEventFilterRow { pub authentication_status: Option<DBEnumWrapper<AuthenticationStatus>>, pub trans_status: Option<DBEnumWrapper<TransactionStatus>>, + pub authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>>, pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>>, pub message_version: Option<String>, diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index fd94aac614c..a3d0fe7b683 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -41,6 +41,7 @@ pub struct AuthEventMetricRow { pub count: Option<i64>, pub authentication_status: Option<DBEnumWrapper<storage_enums::AuthenticationStatus>>, pub trans_status: Option<DBEnumWrapper<storage_enums::TransactionStatus>>, + pub authentication_type: Option<DBEnumWrapper<storage_enums::DecoupledAuthenticationType>>, pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<storage_enums::AuthenticationConnectors>>, pub message_version: Option<String>, diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index 32c76385409..b82d1ef4c35 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -70,7 +70,10 @@ where .switch()?; query_builder - .add_negative_filter_clause("authentication_status", AuthenticationStatus::Pending) + .add_filter_in_range_clause( + "authentication_status", + &[AuthenticationStatus::Success, AuthenticationStatus::Failed], + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -103,6 +106,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_count.rs b/crates/analytics/src/auth_events/metrics/authentication_count.rs index 39df41f53aa..682e8a07f6b 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_count.rs @@ -96,6 +96,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs index cdb89b796dd..047511d477c 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs @@ -12,8 +12,8 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ query::{ - Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, - Window, + Aggregate, FilterTypes, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, + ToSql, Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -45,11 +45,9 @@ where for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } + query_builder - .add_select_column(Aggregate::Count { - field: None, - alias: Some("count"), - }) + .add_select_column("sum(sign_flag) AS count") .switch()?; query_builder @@ -94,6 +92,11 @@ where .switch()?; } + query_builder + .add_order_by_clause("count", Order::Descending) + .attach_printable("Error adding order by clause") + .switch()?; + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) @@ -112,6 +115,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs index 37f9dfd1c1f..9342e9047e0 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs @@ -107,6 +107,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index 039ef00dd6e..984350efe6b 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -101,6 +101,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index beccc093b19..5a2a9400b20 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -4,6 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; +use common_enums::{AuthenticationStatus, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -67,11 +68,17 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "C".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Challenge, + ) .switch()?; query_builder - .add_negative_filter_clause("authentication_status", "pending") + .add_filter_in_range_clause( + "authentication_status", + &[AuthenticationStatus::Success, AuthenticationStatus::Failed], + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -104,6 +111,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index 4d07cffba94..279844388f2 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -4,6 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; +use common_enums::DecoupledAuthenticationType; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -67,7 +68,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "C".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Challenge, + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -99,6 +103,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index 310a45f0530..91e8cc54289 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -4,7 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; -use common_enums::AuthenticationStatus; +use common_enums::{AuthenticationStatus, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -72,7 +72,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "C".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Challenge, + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -105,6 +108,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index 24857bfb840..b08edb10113 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -4,6 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; +use common_enums::DecoupledAuthenticationType; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -67,7 +68,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "Y".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Frictionless, + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -100,6 +104,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index 79fef8a16d0..80417ac64bf 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -4,7 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; -use common_enums::AuthenticationStatus; +use common_enums::{AuthenticationStatus, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -68,7 +68,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "Y".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Frictionless, + ) .switch()?; query_builder @@ -105,6 +108,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index f698b1161a0..89f5cbd5b9c 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -1123,6 +1123,7 @@ pub struct ReportConfig { pub payment_function: String, pub refund_function: String, pub dispute_function: String, + pub authentication_function: String, pub region: String, } @@ -1151,6 +1152,7 @@ pub enum AnalyticsFlow { GeneratePaymentReport, GenerateDisputeReport, GenerateRefundReport, + GenerateAuthenticationReport, GetApiEventMetrics, GetApiEventFilters, GetConnectorEvents, diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index d483ce43605..5effd9e70a7 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -19,7 +19,9 @@ use api_models::{ }, refunds::RefundStatus, }; -use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; +use common_enums::{ + AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, +}; use common_utils::{ errors::{CustomResult, ParsingError}, id_type::{MerchantId, OrganizationId, ProfileId}, @@ -506,6 +508,7 @@ impl_to_sql_for_to_string!( TransactionStatus, AuthenticationStatus, AuthenticationConnectors, + DecoupledAuthenticationType, Flow, &String, &bool, diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index a6db92e753f..6a6237e6783 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -4,7 +4,9 @@ use api_models::{ analytics::{frm::FrmTransactionType, refunds::RefundType}, enums::{DisputeStage, DisputeStatus}, }; -use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; +use common_enums::{ + AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, +}; use common_utils::{ errors::{CustomResult, ParsingError}, DbConnectionParams, @@ -100,6 +102,7 @@ db_type!(DisputeStatus); db_type!(AuthenticationStatus); db_type!(TransactionStatus); db_type!(AuthenticationConnectors); +db_type!(DecoupledAuthenticationType); impl<'q, Type> Encode<'q, Postgres> for DBEnumWrapper<Type> where @@ -208,6 +211,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> = + row.try_get("authentication_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -237,6 +245,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow Ok(Self { authentication_status, trans_status, + authentication_type, error_message, authentication_connector, message_version, @@ -259,6 +268,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> = + row.try_get("authentication_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -277,6 +291,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow Ok(Self { authentication_status, trans_status, + authentication_type, error_message, authentication_connector, message_version, diff --git a/crates/api_models/src/analytics/auth_events.rs b/crates/api_models/src/analytics/auth_events.rs index 5c2d4ed2064..2360e564642 100644 --- a/crates/api_models/src/analytics/auth_events.rs +++ b/crates/api_models/src/analytics/auth_events.rs @@ -3,7 +3,9 @@ use std::{ hash::{Hash, Hasher}, }; -use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; +use common_enums::{ + AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, +}; use super::{NameDescription, TimeRange}; @@ -14,6 +16,8 @@ pub struct AuthEventFilters { #[serde(default)] pub trans_status: Vec<TransactionStatus>, #[serde(default)] + pub authentication_type: Vec<DecoupledAuthenticationType>, + #[serde(default)] pub error_message: Vec<String>, #[serde(default)] pub authentication_connector: Vec<AuthenticationConnectors>, @@ -42,6 +46,7 @@ pub enum AuthEventDimensions { #[strum(serialize = "trans_status")] #[serde(rename = "trans_status")] TransactionStatus, + AuthenticationType, ErrorMessage, AuthenticationConnector, MessageVersion, @@ -101,6 +106,7 @@ pub mod metric_behaviour { pub struct ChallengeAttemptCount; pub struct ChallengeSuccessCount; pub struct AuthenticationErrorMessage; + pub struct AuthenticationFunnel; } impl From<AuthEventMetrics> for NameDescription { @@ -125,6 +131,7 @@ impl From<AuthEventDimensions> for NameDescription { pub struct AuthEventMetricsBucketIdentifier { pub authentication_status: Option<AuthenticationStatus>, pub trans_status: Option<TransactionStatus>, + pub authentication_type: Option<DecoupledAuthenticationType>, pub error_message: Option<String>, pub authentication_connector: Option<AuthenticationConnectors>, pub message_version: Option<String>, @@ -140,6 +147,7 @@ impl AuthEventMetricsBucketIdentifier { pub fn new( authentication_status: Option<AuthenticationStatus>, trans_status: Option<TransactionStatus>, + authentication_type: Option<DecoupledAuthenticationType>, error_message: Option<String>, authentication_connector: Option<AuthenticationConnectors>, message_version: Option<String>, @@ -148,6 +156,7 @@ impl AuthEventMetricsBucketIdentifier { Self { authentication_status, trans_status, + authentication_type, error_message, authentication_connector, message_version, @@ -161,6 +170,7 @@ impl Hash for AuthEventMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.authentication_status.hash(state); self.trans_status.hash(state); + self.authentication_type.hash(state); self.authentication_connector.hash(state); self.message_version.hash(state); self.error_message.hash(state); diff --git a/crates/api_models/src/analytics/sdk_events.rs b/crates/api_models/src/analytics/sdk_events.rs index b2abbbe00e1..9a749f1144e 100644 --- a/crates/api_models/src/analytics/sdk_events.rs +++ b/crates/api_models/src/analytics/sdk_events.rs @@ -114,6 +114,10 @@ pub enum SdkEventNames { ThreeDsMethod, LoaderChanged, DisplayThreeDsSdk, + ThreeDsSdkInit, + AreqParamsGeneration, + ChallengePresented, + ChallengeComplete, } pub mod metric_behaviour { diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 858c16d052f..cc242f86a5b 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -90,6 +90,10 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_merchant_payment_report)), ) + .service( + web::resource("report/authentications") + .route(web::post().to(generate_merchant_authentication_report)), + ) .service( web::resource("metrics/sdk_events") .route(web::post().to(get_sdk_event_metrics)), @@ -190,6 +194,11 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_merchant_payment_report)), ) + .service( + web::resource("report/authentications").route( + web::post().to(generate_merchant_authentication_report), + ), + ) .service( web::resource("metrics/api_events") .route(web::post().to(get_merchant_api_events_metrics)), @@ -252,6 +261,10 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_org_payment_report)), ) + .service( + web::resource("report/authentications") + .route(web::post().to(generate_org_authentication_report)), + ) .service( web::resource("metrics/sankey") .route(web::post().to(get_org_sankey)), @@ -306,6 +319,11 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_profile_payment_report)), ) + .service( + web::resource("report/authentications").route( + web::post().to(generate_profile_authentication_report), + ), + ) .service( web::resource("api_event_logs") .route(web::get().to(get_profile_api_events)), @@ -1746,6 +1764,7 @@ pub mod routes { )) .await } + #[cfg(feature = "v1")] pub async fn generate_org_payment_report( state: web::Data<AppState>, @@ -1850,6 +1869,161 @@ pub mod routes { .await } + #[cfg(feature = "v1")] + pub async fn generate_merchant_authentication_report( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<ReportRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GenerateAuthenticationReport; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { + let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) + .await + .change_context(AnalyticsError::UnknownError)?; + + let user_email = UserEmail::from_pii_email(user.email) + .change_context(AnalyticsError::UnknownError)? + .get_secret(); + + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + let lambda_req = GenerateReportRequest { + request: payload, + merchant_id: Some(merchant_id.clone()), + auth: AuthInfo::MerchantLevel { + org_id: org_id.clone(), + merchant_ids: vec![merchant_id.clone()], + }, + email: user_email, + }; + + let json_bytes = + serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; + invoke_lambda( + &state.conf.report_download_config.authentication_function, + &state.conf.report_download_config.region, + &json_bytes, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::MerchantReportRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + + #[cfg(feature = "v1")] + pub async fn generate_org_authentication_report( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<ReportRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GenerateAuthenticationReport; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { + let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) + .await + .change_context(AnalyticsError::UnknownError)?; + + let user_email = UserEmail::from_pii_email(user.email) + .change_context(AnalyticsError::UnknownError)? + .get_secret(); + + let org_id = auth.merchant_account.get_org_id(); + let lambda_req = GenerateReportRequest { + request: payload, + merchant_id: None, + auth: AuthInfo::OrgLevel { + org_id: org_id.clone(), + }, + email: user_email, + }; + + let json_bytes = + serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; + invoke_lambda( + &state.conf.report_download_config.authentication_function, + &state.conf.report_download_config.region, + &json_bytes, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::OrganizationReportRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + + #[cfg(feature = "v1")] + pub async fn generate_profile_authentication_report( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<ReportRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GenerateAuthenticationReport; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { + let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) + .await + .change_context(AnalyticsError::UnknownError)?; + + let user_email = UserEmail::from_pii_email(user.email) + .change_context(AnalyticsError::UnknownError)? + .get_secret(); + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + let profile_id = auth + .profile_id + .ok_or(report!(UserErrors::JwtProfileIdMissing)) + .change_context(AnalyticsError::AccessForbiddenError)?; + let lambda_req = GenerateReportRequest { + request: payload, + merchant_id: Some(merchant_id.clone()), + auth: AuthInfo::ProfileLevel { + org_id: org_id.clone(), + merchant_id: merchant_id.clone(), + profile_ids: vec![profile_id.clone()], + }, + email: user_email, + }; + + let json_bytes = + serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; + invoke_lambda( + &state.conf.report_download_config.authentication_function, + &state.conf.report_download_config.region, + &json_bytes, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::ProfileReportRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + /// # Panics /// /// Panics if `json_payload` array does not contain one `GetApiEventMetricRequest` element.
2025-03-12T12:08:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Hotfix PR Original PR: [https://github.com/juspay/hyperswitch/pull/7483](https://github.com/juspay/hyperswitch/pull/7483) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
b8b3bfa77055648345ba827ec03e213e66539e7f
b8b3bfa77055648345ba827ec03e213e66539e7f
juspay/hyperswitch
juspay__hyperswitch-7492
Bug: ci: paypal ci failing ref: https://developer.paypal.com/docs/multiparty/checkout/advanced/customize/3d-secure/test/ replacing visa card with the mastercard fixed it upon testing. also fixe the assertion. 65 != 60
2025-03-12T06:39:17Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> <img width="861" alt="image" src="https://github.com/user-attachments/assets/d85ea702-cd5d-444b-86bd-1f5f50363d40" /> connector throws above error when using VISA card. Replacing that with MasterCard fixes it: <img width="1206" alt="image" src="https://github.com/user-attachments/assets/de44fa13-695b-4198-ba82-d603a9bafbe1" /> ### 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). --> paypal ci is failing. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> `CYPRESS_CONNECTOR=paypal npm run cypress:payments` ![image](https://github.com/user-attachments/assets/d8f52cc9-3bbb-45f3-97fc-6cdd713f6dc1) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `npm run format` - [x] I addressed lints thrown by `npm run lint` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
833da1c3c5a0f006a689b05554c547205774c823
833da1c3c5a0f006a689b05554c547205774c823
juspay/hyperswitch
juspay__hyperswitch-7490
Bug: refactor(organization): add api version column Add api version column to organization.
diff --git a/Cargo.lock b/Cargo.lock index debcaf5d289..f0026e2d29a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6960,6 +6960,7 @@ name = "scheduler" version = "0.1.0" dependencies = [ "async-trait", + "common_types", "common_utils", "diesel_models", "error-stack", diff --git a/crates/common_types/src/consts.rs b/crates/common_types/src/consts.rs new file mode 100644 index 00000000000..3550333443f --- /dev/null +++ b/crates/common_types/src/consts.rs @@ -0,0 +1,9 @@ +//! Constants that are used in the domain level. + +/// API version +#[cfg(feature = "v1")] +pub const API_VERSION: common_enums::ApiVersion = common_enums::ApiVersion::V1; + +/// API version +#[cfg(feature = "v2")] +pub const API_VERSION: common_enums::ApiVersion = common_enums::ApiVersion::V2; diff --git a/crates/common_types/src/lib.rs b/crates/common_types/src/lib.rs index 589a77e3a50..7f3b44ecd9a 100644 --- a/crates/common_types/src/lib.rs +++ b/crates/common_types/src/lib.rs @@ -2,6 +2,7 @@ #![warn(missing_docs, missing_debug_implementations)] +pub mod consts; pub mod customers; pub mod domain; pub mod payment_methods; diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml index 94913571396..ca7e85628bd 100644 --- a/crates/diesel_models/Cargo.toml +++ b/crates/diesel_models/Cargo.toml @@ -10,8 +10,8 @@ license.workspace = true [features] default = ["kv_store"] kv_store = [] -v1 = ["common_utils/v1"] -v2 = ["common_utils/v2"] +v1 = ["common_utils/v1", "common_types/v1"] +v2 = ["common_utils/v2", "common_types/v2"] customer_v2 = [] payment_methods_v2 = [] refunds_v2 = [] diff --git a/crates/diesel_models/src/organization.rs b/crates/diesel_models/src/organization.rs index 753f1cf3c30..1ca86225934 100644 --- a/crates/diesel_models/src/organization.rs +++ b/crates/diesel_models/src/organization.rs @@ -28,6 +28,7 @@ pub struct Organization { id: Option<id_type::OrganizationId>, #[allow(dead_code)] organization_name: Option<String>, + pub version: common_enums::ApiVersion, } #[cfg(feature = "v2")] @@ -44,6 +45,7 @@ pub struct Organization { pub modified_at: time::PrimitiveDateTime, id: id_type::OrganizationId, organization_name: Option<String>, + pub version: common_enums::ApiVersion, } #[cfg(feature = "v1")] @@ -58,6 +60,7 @@ impl Organization { modified_at, id: _, organization_name: _, + version, } = org_new; Self { id: Some(org_id.clone()), @@ -68,6 +71,7 @@ impl Organization { metadata, created_at, modified_at, + version, } } } @@ -82,6 +86,7 @@ impl Organization { metadata, created_at, modified_at, + version, } = org_new; Self { id, @@ -90,6 +95,7 @@ impl Organization { metadata, created_at, modified_at, + version, } } } @@ -106,6 +112,7 @@ pub struct OrganizationNew { pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, + pub version: common_enums::ApiVersion, } #[cfg(feature = "v2")] @@ -118,6 +125,7 @@ pub struct OrganizationNew { pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, + pub version: common_enums::ApiVersion, } #[cfg(feature = "v1")] @@ -132,6 +140,7 @@ impl OrganizationNew { metadata: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), + version: common_types::consts::API_VERSION, } } } @@ -146,6 +155,7 @@ impl OrganizationNew { metadata: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), + version: common_types::consts::API_VERSION, } } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 96f734da108..56a0b670e52 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -817,6 +817,7 @@ diesel::table! { #[max_length = 32] id -> Nullable<Varchar>, organization_name -> Nullable<Text>, + version -> ApiVersion, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index dea417f36dd..4ab5b5377e1 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -796,6 +796,7 @@ diesel::table! { #[max_length = 32] id -> Varchar, organization_name -> Nullable<Text>, + version -> ApiVersion, } } diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml index c27d1f6bf96..39aadb90db6 100644 --- a/crates/hyperswitch_domain_models/Cargo.toml +++ b/crates/hyperswitch_domain_models/Cargo.toml @@ -13,8 +13,8 @@ encryption_service = [] olap = [] payouts = ["api_models/payouts"] frm = ["api_models/frm"] -v2 = ["api_models/v2", "diesel_models/v2", "common_utils/v2"] -v1 = ["api_models/v1", "diesel_models/v1", "common_utils/v1"] +v2 = ["api_models/v2", "diesel_models/v2", "common_utils/v2", "common_types/v2"] +v1 = ["api_models/v1", "diesel_models/v1", "common_utils/v1", "common_types/v1"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2"] payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2"] dummy_connector = [] diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index 5170bd3ce29..b7fa027bb06 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -15,10 +15,7 @@ use diesel_models::business_profile::{ use error_stack::ResultExt; use masking::{PeekInterface, Secret}; -use crate::{ - consts, - type_encryption::{crypto_operation, AsyncLift, CryptoOperation}, -}; +use crate::type_encryption::{crypto_operation, AsyncLift, CryptoOperation}; #[cfg(feature = "v1")] #[derive(Clone, Debug)] @@ -162,7 +159,7 @@ impl From<ProfileSetter> for Profile { .always_collect_shipping_details_from_wallet_connector, tax_connector_id: value.tax_connector_id, is_tax_connector_enabled: value.is_tax_connector_enabled, - version: consts::API_VERSION, + version: common_types::consts::API_VERSION, dynamic_routing_algorithm: value.dynamic_routing_algorithm, is_network_tokenization_enabled: value.is_network_tokenization_enabled, is_auto_retries_enabled: value.is_auto_retries_enabled, @@ -993,7 +990,7 @@ impl From<ProfileSetter> for Profile { should_collect_cvv_during_payment: value.should_collect_cvv_during_payment, tax_connector_id: value.tax_connector_id, is_tax_connector_enabled: value.is_tax_connector_enabled, - version: consts::API_VERSION, + version: common_types::consts::API_VERSION, is_network_tokenization_enabled: value.is_network_tokenization_enabled, is_click_to_pay_enabled: value.is_click_to_pay_enabled, authentication_product_ids: value.authentication_product_ids, diff --git a/crates/hyperswitch_domain_models/src/consts.rs b/crates/hyperswitch_domain_models/src/consts.rs index c2ebd839fe7..93fd63deb62 100644 --- a/crates/hyperswitch_domain_models/src/consts.rs +++ b/crates/hyperswitch_domain_models/src/consts.rs @@ -4,12 +4,6 @@ use std::collections::HashSet; use router_env::once_cell::sync::Lazy; -#[cfg(feature = "v1")] -pub const API_VERSION: common_enums::ApiVersion = common_enums::ApiVersion::V1; - -#[cfg(feature = "v2")] -pub const API_VERSION: common_enums::ApiVersion = common_enums::ApiVersion::V2; - pub static ROUTING_ENABLED_PAYMENT_METHODS: Lazy<HashSet<common_enums::PaymentMethod>> = Lazy::new(|| { let mut set = HashSet::new(); diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs index 384bc5ab427..65e17ace222 100644 --- a/crates/hyperswitch_domain_models/src/customer.rs +++ b/crates/hyperswitch_domain_models/src/customer.rs @@ -319,7 +319,7 @@ impl super::behaviour::Conversion for Customer { updated_by: self.updated_by, default_billing_address: self.default_billing_address, default_shipping_address: self.default_shipping_address, - version: crate::consts::API_VERSION, + version: common_types::consts::API_VERSION, status: self.status, }) } diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs index fef000a3954..8657af91c57 100644 --- a/crates/hyperswitch_domain_models/src/merchant_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_account.rs @@ -572,7 +572,7 @@ impl super::behaviour::Conversion for MerchantAccount { modified_at: self.modified_at, organization_id: self.organization_id, recon_status: self.recon_status, - version: crate::consts::API_VERSION, + version: common_types::consts::API_VERSION, is_platform_account: self.is_platform_account, product_type: self.product_type, }; @@ -657,7 +657,7 @@ impl super::behaviour::Conversion for MerchantAccount { modified_at: now, organization_id: self.organization_id, recon_status: self.recon_status, - version: crate::consts::API_VERSION, + version: common_types::consts::API_VERSION, is_platform_account: self.is_platform_account, product_type: self .product_type @@ -820,7 +820,7 @@ impl super::behaviour::Conversion for MerchantAccount { recon_status: self.recon_status, payment_link_config: self.payment_link_config, pm_collect_link_config: self.pm_collect_link_config, - version: crate::consts::API_VERSION, + version: common_types::consts::API_VERSION, is_platform_account: self.is_platform_account, product_type: self .product_type diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index a984db70863..6be1be4b7d3 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -402,7 +402,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { recon_status: diesel_models::enums::ReconStatus::NotRequested, payment_link_config: None, pm_collect_link_config, - version: hyperswitch_domain_models::consts::API_VERSION, + version: common_types::consts::API_VERSION, is_platform_account: false, product_type: self.product_type, }, @@ -673,7 +673,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { organization_id: organization.get_organization_id(), recon_status: diesel_models::enums::ReconStatus::NotRequested, is_platform_account: false, - version: hyperswitch_domain_models::consts::API_VERSION, + version: common_types::consts::API_VERSION, product_type: self.product_type, }), ) @@ -2608,7 +2608,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { status: connector_status, connector_wallets_details: encrypted_data.connector_wallets_details, additional_merchant_data: encrypted_data.additional_merchant_data, - version: hyperswitch_domain_models::consts::API_VERSION, + version: common_types::consts::API_VERSION, feature_metadata, }) } @@ -2813,7 +2813,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { business_label: self.business_label.clone(), business_sub_label: self.business_sub_label.clone(), additional_merchant_data: encrypted_data.additional_merchant_data, - version: hyperswitch_domain_models::consts::API_VERSION, + version: common_types::consts::API_VERSION, }) } diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index bb970a4956e..d76b338dc36 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -230,7 +230,7 @@ pub async fn add_api_key_expiry_task( api_key_expiry_tracker, None, schedule_time, - hyperswitch_domain_models::consts::API_VERSION, + common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct API key expiry process tracker task")?; diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index e9d9ffe2d75..c46cadd1e33 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -188,7 +188,7 @@ impl CustomerCreateBridge for customers::CustomerRequest { modified_at: common_utils::date_time::now(), default_payment_method_id: None, updated_by: None, - version: hyperswitch_domain_models::consts::API_VERSION, + version: common_types::consts::API_VERSION, }) } @@ -284,7 +284,7 @@ impl CustomerCreateBridge for customers::CustomerRequest { updated_by: None, default_billing_address: encrypted_customer_billing_address.map(Into::into), default_shipping_address: encrypted_customer_shipping_address.map(Into::into), - version: hyperswitch_domain_models::consts::API_VERSION, + version: common_types::consts::API_VERSION, status: common_enums::DeleteStatus::Active, }) } diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index f4ff34a2967..fee2061e675 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -495,7 +495,7 @@ pub async fn add_payment_method_status_update_task( tracking_data, None, schedule_time, - hyperswitch_domain_models::consts::API_VERSION, + common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct PAYMENT_METHOD_STATUS_UPDATE process tracker task")?; @@ -1550,7 +1550,7 @@ pub async fn create_payment_method_for_intent( last_used_at: current_time, payment_method_billing_address, updated_by: None, - version: domain::consts::API_VERSION, + version: common_types::consts::API_VERSION, locker_fingerprint_id: None, network_token_locker_id: None, network_token_payment_method_data: None, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 12e9c6e16e9..dc79cd68459 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -205,7 +205,7 @@ pub async fn create_payment_method( last_used_at: current_time, payment_method_billing_address, updated_by: None, - version: domain::consts::API_VERSION, + version: common_types::consts::API_VERSION, network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, @@ -828,7 +828,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( last_used_at: current_time, payment_method_billing_address, updated_by: None, - version: domain::consts::API_VERSION, + version: common_types::consts::API_VERSION, network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, diff --git a/crates/router/src/core/payment_methods/tokenize/card_executor.rs b/crates/router/src/core/payment_methods/tokenize/card_executor.rs index 9b7f89c5199..eb9d3d6b6c6 100644 --- a/crates/router/src/core/payment_methods/tokenize/card_executor.rs +++ b/crates/router/src/core/payment_methods/tokenize/card_executor.rs @@ -422,7 +422,7 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> { address_id: None, default_payment_method_id: None, updated_by: None, - version: hyperswitch_domain_models::consts::API_VERSION, + version: common_types::consts::API_VERSION, }; db.insert_customer( diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 8181df8c056..71d57ef7964 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1401,7 +1401,7 @@ pub async fn add_delete_tokenized_data_task( tracking_data, None, schedule_time, - hyperswitch_domain_models::consts::API_VERSION, + common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct delete tokenized data process tracker task")?; diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index e80c281fa4e..88e5cc7481f 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -5967,7 +5967,7 @@ pub async fn add_process_sync_task( tracking_data, None, schedule_time, - hyperswitch_domain_models::consts::API_VERSION, + common_types::consts::API_VERSION, ) .map_err(errors::StorageError::from)?; diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 5b7ead3f4f9..ee11dabd8a6 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1801,7 +1801,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>( address_id: None, default_payment_method_id: None, updated_by: None, - version: hyperswitch_domain_models::consts::API_VERSION, + version: common_types::consts::API_VERSION, }; metrics::CUSTOMER_CREATED.add(1, &[]); db.insert_customer(new_customer, key_manager_state, key_store, storage_scheme) diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 21a560e781b..7ddce4ccc14 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -3094,7 +3094,7 @@ pub async fn add_external_account_addition_task( tracking_data, None, schedule_time, - hyperswitch_domain_models::consts::API_VERSION, + common_types::consts::API_VERSION, ) .map_err(errors::StorageError::from)?; diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 45bd954190b..cdb021311e4 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -776,7 +776,7 @@ pub(super) async fn get_or_create_customer_details( address_id: None, default_payment_method_id: None, updated_by: None, - version: hyperswitch_domain_models::consts::API_VERSION, + version: common_types::consts::API_VERSION, }; Ok(Some( diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index 0577b532cf0..eddacce99b3 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -550,7 +550,7 @@ async fn store_bank_details_in_payment_methods( client_secret: None, payment_method_billing_address: None, updated_by: None, - version: domain::consts::API_VERSION, + version: common_types::consts::API_VERSION, network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, @@ -577,7 +577,7 @@ async fn store_bank_details_in_payment_methods( payment_method_billing_address: None, updated_by: None, locker_fingerprint_id: None, - version: domain::consts::API_VERSION, + version: common_types::consts::API_VERSION, network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 7d663a48a1a..e81c7d025ae 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -1621,7 +1621,7 @@ pub async fn add_refund_sync_task( refund_workflow_tracking_data, None, schedule_time, - hyperswitch_domain_models::consts::API_VERSION, + common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct refund sync process tracker task")?; @@ -1660,7 +1660,7 @@ pub async fn add_refund_execute_task( refund_workflow_tracking_data, None, schedule_time, - hyperswitch_domain_models::consts::API_VERSION, + common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct refund execute process tracker task")?; diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs index b5d5e7a6cd6..b558bd8cbc4 100644 --- a/crates/router/src/core/revenue_recovery.rs +++ b/crates/router/src/core/revenue_recovery.rs @@ -163,7 +163,7 @@ async fn insert_psync_pcr_task( psync_workflow_tracking_data, None, schedule_time, - hyperswitch_domain_models::consts::API_VERSION, + common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct delete tokenized data process tracker task")?; diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs index 92c29282b21..71b4e822a34 100644 --- a/crates/router/src/core/webhooks/outgoing.rs +++ b/crates/router/src/core/webhooks/outgoing.rs @@ -555,7 +555,7 @@ pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker( tracking_data, None, schedule_time, - hyperswitch_domain_models::consts::API_VERSION, + common_types::consts::API_VERSION, ) .map_err(errors::StorageError::from)?; diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index 92683beb289..213c2b19f6a 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -1680,7 +1680,7 @@ mod merchant_connector_account_cache_tests { .unwrap(), ), additional_merchant_data: None, - version: hyperswitch_domain_models::consts::API_VERSION, + version: common_types::consts::API_VERSION, }; db.insert_merchant_connector_account(key_manager_state, mca.clone(), &merchant_key) @@ -1858,7 +1858,7 @@ mod merchant_connector_account_cache_tests { .unwrap(), ), additional_merchant_data: None, - version: hyperswitch_domain_models::consts::API_VERSION, + version: common_types::consts::API_VERSION, feature_metadata: None, }; diff --git a/crates/scheduler/Cargo.toml b/crates/scheduler/Cargo.toml index 176a4a99b23..5c2bc868ab0 100644 --- a/crates/scheduler/Cargo.toml +++ b/crates/scheduler/Cargo.toml @@ -10,8 +10,8 @@ default = ["kv_store", "olap"] olap = ["storage_impl/olap", "hyperswitch_domain_models/olap"] kv_store = [] email = ["external_services/email"] -v1 = ["diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "common_utils/v1"] -v2 = ["diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "common_utils/v2"] +v1 = ["diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "common_utils/v1", "common_types/v1"] +v2 = ["diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "common_utils/v2", "common_types/v2"] [dependencies] # Third party crates @@ -31,6 +31,7 @@ uuid = { version = "1.8.0", features = ["v4"] } # First party crates common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext"] } +common_types = { version = "0.1.0", path = "../common_types" } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false } external_services = { version = "0.1.0", path = "../external_services" } hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } diff --git a/crates/scheduler/src/db/process_tracker.rs b/crates/scheduler/src/db/process_tracker.rs index 4cf516faa1e..1d721973764 100644 --- a/crates/scheduler/src/db/process_tracker.rs +++ b/crates/scheduler/src/db/process_tracker.rs @@ -101,7 +101,7 @@ impl ProcessTrackerInterface for Store { time_upper_limit, status, limit, - hyperswitch_domain_models::consts::API_VERSION, + common_types::consts::API_VERSION, ) .await .map_err(|error| report!(errors::StorageError::from(error))) diff --git a/migrations/2025-03-04-053541_add_api_version_to_organization/down.sql b/migrations/2025-03-04-053541_add_api_version_to_organization/down.sql new file mode 100644 index 00000000000..4e492ad0ef7 --- /dev/null +++ b/migrations/2025-03-04-053541_add_api_version_to_organization/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE organization DROP COLUMN version; diff --git a/migrations/2025-03-04-053541_add_api_version_to_organization/up.sql b/migrations/2025-03-04-053541_add_api_version_to_organization/up.sql new file mode 100644 index 00000000000..1569b53f9d1 --- /dev/null +++ b/migrations/2025-03-04-053541_add_api_version_to_organization/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE organization +ADD COLUMN IF NOT EXISTS version "ApiVersion" NOT NULL DEFAULT 'v1'; \ No newline at end of file
2025-03-04T09:12:22Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds version column to the organisation. ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Test sanity of organization - Create organization in v1 <img width="406" alt="image" src="https://github.com/user-attachments/assets/6c013b47-b1ac-4918-a14b-ff8a0f0725f7" /> - Create organization in v2 <img width="402" alt="image" src="https://github.com/user-attachments/assets/864caf2d-d845-4368-942b-c8fd2778876b" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
f3d6b15a2ade7dd98fec59777301f44d166f3be3
f3d6b15a2ade7dd98fec59777301f44d166f3be3
juspay/hyperswitch
juspay__hyperswitch-7486
Bug: refactor(currency_conversion): add support for expiring forex data in redis ## Description Adding a custom expiry time for Forex data saved in redis (172800 seconds ~ 2days). A new config is added as well: `redis_cache_expiry_in_seconds = 172800`
diff --git a/config/config.example.toml b/config/config.example.toml index a52f7486cf5..caeb82c805a 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -74,10 +74,11 @@ max_feed_count = 200 # The maximum number of frames that will be fe # This section provides configs for currency conversion api [forex_api] -call_delay = 21600 # Expiration time for data in cache as well as redis in seconds api_key = "" # Api key for making request to foreign exchange Api fallback_api_key = "" # Api key for the fallback service -redis_lock_timeout = 100 # Redis remains write locked for 100 s once the acquire_redis_lock is called +redis_ttl_in_seconds = 172800 # Time to expire for forex data stored in Redis +data_expiration_delay_in_seconds = 21600 # Expiration time for data in cache as well as redis in seconds +redis_lock_timeout_in_seconds = 100 # Redis remains write locked for 100 s once the acquire_redis_lock is called # Logging configuration. Logging can be either to file or console or both. @@ -888,4 +889,4 @@ primary_color = "#006DF9" # Primary color of email body background_color = "#FFFFFF" # Background color of email body [additional_revenue_recovery_details_call] -connectors_with_additional_revenue_recovery_details_call = "stripebilling" # List of connectors which has additional revenue recovery details api-call \ No newline at end of file +connectors_with_additional_revenue_recovery_details_call = "stripebilling" # List of connectors which has additional revenue recovery details api-call diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 157e0aa3a42..b2ee7f39741 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -104,10 +104,11 @@ bucket_name = "bucket" # The AWS S3 bucket name for file storage # This section provides configs for currency conversion api [forex_api] -call_delay = 21600 # Expiration time for data in cache as well as redis in seconds api_key = "" # Api key for making request to foreign exchange Api fallback_api_key = "" # Api key for the fallback service -redis_lock_timeout = 100 # Redis remains write locked for 100 s once the acquire_redis_lock is called +data_expiration_delay_in_seconds = 21600 # Expiration time for data in cache as well as redis in seconds +redis_lock_timeout_in_seconds = 100 # Redis remains write locked for 100 s once the acquire_redis_lock is called +redis_ttl_in_seconds = 172800 # Time to expire for forex data stored in Redis [jwekey] # 3 priv/pub key pair vault_encryption_key = "" # public key in pem format, corresponding private key in rust locker diff --git a/config/development.toml b/config/development.toml index 77a38f9d6e8..683b778dac2 100644 --- a/config/development.toml +++ b/config/development.toml @@ -77,10 +77,11 @@ locker_enabled = true ttl_for_storage_in_secs = 220752000 [forex_api] -call_delay = 21600 api_key = "" fallback_api_key = "" -redis_lock_timeout = 100 +data_expiration_delay_in_seconds = 21600 +redis_lock_timeout_in_seconds = 100 +redis_ttl_in_seconds = 172800 [jwekey] vault_encryption_key = """ diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 12242f485b7..9916ed0f3e1 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -30,10 +30,11 @@ dbname = "hyperswitch_db" pool_size = 5 [forex_api] -call_delay = 21600 api_key = "" fallback_api_key = "" -redis_lock_timeout = 100 +data_expiration_delay_in_seconds = 21600 +redis_lock_timeout_in_seconds = 100 +redis_ttl_in_seconds = 172800 [replica_database] username = "db_user" diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 605b4b576f3..b1c92046d0e 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -409,10 +409,9 @@ pub struct PaymentLink { pub struct ForexApi { pub api_key: Secret<String>, pub fallback_api_key: Secret<String>, - /// in s - pub call_delay: i64, - /// in s - pub redis_lock_timeout: u64, + pub data_expiration_delay_in_seconds: u32, + pub redis_lock_timeout_in_seconds: u32, + pub redis_ttl_in_seconds: u32, } #[derive(Debug, Deserialize, Clone, Default)] diff --git a/crates/router/src/core/currency.rs b/crates/router/src/core/currency.rs index 8c1a8512892..bc63dc878cc 100644 --- a/crates/router/src/core/currency.rs +++ b/crates/router/src/core/currency.rs @@ -15,7 +15,7 @@ pub async fn retrieve_forex( ) -> CustomResult<ApplicationResponse<currency::FxExchangeRatesCacheEntry>, ApiErrorResponse> { let forex_api = state.conf.forex_api.get_inner(); Ok(ApplicationResponse::Json( - get_forex_rates(&state, forex_api.call_delay) + get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds) .await .change_context(ApiErrorResponse::GenericNotFoundError { message: "Unable to fetch forex rates".to_string(), @@ -48,7 +48,7 @@ pub async fn get_forex_exchange_rates( state: SessionState, ) -> CustomResult<ExchangeRates, AnalyticsError> { let forex_api = state.conf.forex_api.get_inner(); - let rates = get_forex_rates(&state, forex_api.call_delay) + let rates = get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds) .await .change_context(AnalyticsError::ForexFetchFailed)?; diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs index 4af9f3865f4..cd56382985b 100644 --- a/crates/router/src/utils/currency.rs +++ b/crates/router/src/utils/currency.rs @@ -38,7 +38,7 @@ static FX_EXCHANGE_RATES_CACHE: Lazy<RwLock<Option<FxExchangeRatesCacheEntry>>> impl ApiEventMetric for FxExchangeRatesCacheEntry {} #[derive(Debug, Clone, thiserror::Error)] -pub enum ForexCacheError { +pub enum ForexError { #[error("API error")] ApiError, #[error("API timeout")] @@ -107,8 +107,8 @@ impl FxExchangeRatesCacheEntry { timestamp: date_time::now_unix_timestamp(), } } - fn is_expired(&self, call_delay: i64) -> bool { - self.timestamp + call_delay < date_time::now_unix_timestamp() + fn is_expired(&self, data_expiration_delay: u32) -> bool { + self.timestamp + i64::from(data_expiration_delay) < date_time::now_unix_timestamp() } } @@ -118,7 +118,7 @@ async fn retrieve_forex_from_local_cache() -> Option<FxExchangeRatesCacheEntry> async fn save_forex_data_to_local_cache( exchange_rates_cache_entry: FxExchangeRatesCacheEntry, -) -> CustomResult<(), ForexCacheError> { +) -> CustomResult<(), ForexError> { let mut local = FX_EXCHANGE_RATES_CACHE.write().await; *local = Some(exchange_rates_cache_entry); logger::debug!("forex_log: forex saved in cache"); @@ -126,17 +126,17 @@ async fn save_forex_data_to_local_cache( } impl TryFrom<DefaultExchangeRates> for ExchangeRates { - type Error = error_stack::Report<ForexCacheError>; + type Error = error_stack::Report<ForexError>; fn try_from(value: DefaultExchangeRates) -> Result<Self, Self::Error> { let mut conversion_usable: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); for (curr, conversion) in value.conversion { let enum_curr = enums::Currency::from_str(curr.as_str()) - .change_context(ForexCacheError::ConversionError) + .change_context(ForexError::ConversionError) .attach_printable("Unable to Convert currency received")?; conversion_usable.insert(enum_curr, CurrencyFactors::from(conversion)); } let base_curr = enums::Currency::from_str(value.base_currency.as_str()) - .change_context(ForexCacheError::ConversionError) + .change_context(ForexError::ConversionError) .attach_printable("Unable to convert base currency")?; Ok(Self { base_currency: base_curr, @@ -157,10 +157,10 @@ impl From<Conversion> for CurrencyFactors { #[instrument(skip_all)] pub async fn get_forex_rates( state: &SessionState, - call_delay: i64, -) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { + data_expiration_delay: u32, +) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { if let Some(local_rates) = retrieve_forex_from_local_cache().await { - if local_rates.is_expired(call_delay) { + if local_rates.is_expired(data_expiration_delay) { // expired local data logger::debug!("forex_log: Forex stored in cache is expired"); call_forex_api_and_save_data_to_cache_and_redis(state, Some(local_rates)).await @@ -171,26 +171,28 @@ pub async fn get_forex_rates( } } else { // No data in local - call_api_if_redis_forex_data_expired(state, call_delay).await + call_api_if_redis_forex_data_expired(state, data_expiration_delay).await } } async fn call_api_if_redis_forex_data_expired( state: &SessionState, - call_delay: i64, -) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { + data_expiration_delay: u32, +) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { match retrieve_forex_data_from_redis(state).await { - Ok(Some(data)) => call_forex_api_if_redis_data_expired(state, data, call_delay).await, + Ok(Some(data)) => { + call_forex_api_if_redis_data_expired(state, data, data_expiration_delay).await + } Ok(None) => { // No data in local as well as redis call_forex_api_and_save_data_to_cache_and_redis(state, None).await?; - Err(ForexCacheError::ForexDataUnavailable.into()) + Err(ForexError::ForexDataUnavailable.into()) } Err(error) => { // Error in deriving forex rates from redis logger::error!("forex_error: {:?}", error); call_forex_api_and_save_data_to_cache_and_redis(state, None).await?; - Err(ForexCacheError::ForexDataUnavailable.into()) + Err(ForexError::ForexDataUnavailable.into()) } } } @@ -198,11 +200,11 @@ async fn call_api_if_redis_forex_data_expired( async fn call_forex_api_and_save_data_to_cache_and_redis( state: &SessionState, stale_redis_data: Option<FxExchangeRatesCacheEntry>, -) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { +) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { // spawn a new thread and do the api fetch and write operations on redis. let forex_api_key = state.conf.forex_api.get_inner().api_key.peek(); if forex_api_key.is_empty() { - Err(ForexCacheError::ConfigurationError("api_keys not provided".into()).into()) + Err(ForexError::ConfigurationError("api_keys not provided".into()).into()) } else { let state = state.clone(); tokio::spawn( @@ -216,16 +218,16 @@ async fn call_forex_api_and_save_data_to_cache_and_redis( } .in_current_span(), ); - stale_redis_data.ok_or(ForexCacheError::EntryNotFound.into()) + stale_redis_data.ok_or(ForexError::EntryNotFound.into()) } } async fn acquire_redis_lock_and_call_forex_api( state: &SessionState, -) -> CustomResult<(), ForexCacheError> { +) -> CustomResult<(), ForexError> { let lock_acquired = acquire_redis_lock(state).await?; if !lock_acquired { - Err(ForexCacheError::CouldNotAcquireLock.into()) + Err(ForexError::CouldNotAcquireLock.into()) } else { logger::debug!("forex_log: redis lock acquired"); let api_rates = fetch_forex_rates_from_primary_api(state).await; @@ -250,7 +252,7 @@ async fn acquire_redis_lock_and_call_forex_api( async fn save_forex_data_to_cache_and_redis( state: &SessionState, forex: FxExchangeRatesCacheEntry, -) -> CustomResult<(), ForexCacheError> { +) -> CustomResult<(), ForexError> { save_forex_data_to_redis(state, &forex) .await .async_and_then(|_rates| release_redis_lock(state)) @@ -262,9 +264,9 @@ async fn save_forex_data_to_cache_and_redis( async fn call_forex_api_if_redis_data_expired( state: &SessionState, redis_data: FxExchangeRatesCacheEntry, - call_delay: i64, -) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { - match is_redis_expired(Some(redis_data.clone()).as_ref(), call_delay).await { + data_expiration_delay: u32, +) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { + match is_redis_expired(Some(redis_data.clone()).as_ref(), data_expiration_delay).await { Some(redis_forex) => { // Valid data present in redis let exchange_rates = FxExchangeRatesCacheEntry::new(redis_forex.as_ref().clone()); @@ -281,7 +283,7 @@ async fn call_forex_api_if_redis_data_expired( async fn fetch_forex_rates_from_primary_api( state: &SessionState, -) -> Result<FxExchangeRatesCacheEntry, error_stack::Report<ForexCacheError>> { +) -> Result<FxExchangeRatesCacheEntry, error_stack::Report<ForexError>> { let forex_api_key = state.conf.forex_api.get_inner().api_key.peek(); logger::debug!("forex_log: Primary api call for forex fetch"); @@ -301,12 +303,12 @@ async fn fetch_forex_rates_from_primary_api( false, ) .await - .change_context(ForexCacheError::ApiUnresponsive) + .change_context(ForexError::ApiUnresponsive) .attach_printable("Primary forex fetch api unresponsive")?; let forex_response = response .json::<ForexResponse>() .await - .change_context(ForexCacheError::ParsingError) + .change_context(ForexError::ParsingError) .attach_printable( "Unable to parse response received from primary api into ForexResponse", )?; @@ -347,7 +349,7 @@ async fn fetch_forex_rates_from_primary_api( pub async fn fetch_forex_rates_from_fallback_api( state: &SessionState, -) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { +) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { let fallback_forex_api_key = state.conf.forex_api.get_inner().fallback_api_key.peek(); let fallback_forex_url: String = @@ -367,13 +369,13 @@ pub async fn fetch_forex_rates_from_fallback_api( false, ) .await - .change_context(ForexCacheError::ApiUnresponsive) + .change_context(ForexError::ApiUnresponsive) .attach_printable("Fallback forex fetch api unresponsive")?; let fallback_forex_response = response .json::<FallbackForexResponse>() .await - .change_context(ForexCacheError::ParsingError) + .change_context(ForexError::ParsingError) .attach_printable( "Unable to parse response received from falback api into ForexResponse", )?; @@ -432,74 +434,76 @@ pub async fn fetch_forex_rates_from_fallback_api( async fn release_redis_lock( state: &SessionState, -) -> Result<DelReply, error_stack::Report<ForexCacheError>> { +) -> Result<DelReply, error_stack::Report<ForexError>> { logger::debug!("forex_log: Releasing redis lock"); state .store .get_redis_conn() - .change_context(ForexCacheError::RedisConnectionError)? + .change_context(ForexError::RedisConnectionError)? .delete_key(&REDIX_FOREX_CACHE_KEY.into()) .await - .change_context(ForexCacheError::RedisLockReleaseFailed) + .change_context(ForexError::RedisLockReleaseFailed) .attach_printable("Unable to release redis lock") } -async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexCacheError> { +async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexError> { let forex_api = state.conf.forex_api.get_inner(); logger::debug!("forex_log: Acquiring redis lock"); state .store .get_redis_conn() - .change_context(ForexCacheError::RedisConnectionError)? + .change_context(ForexError::RedisConnectionError)? .set_key_if_not_exists_with_expiry( &REDIX_FOREX_CACHE_KEY.into(), "", - Some( - i64::try_from(forex_api.redis_lock_timeout) - .change_context(ForexCacheError::ConversionError)?, - ), + Some(i64::from(forex_api.redis_lock_timeout_in_seconds)), ) .await .map(|val| matches!(val, redis_interface::SetnxReply::KeySet)) - .change_context(ForexCacheError::CouldNotAcquireLock) + .change_context(ForexError::CouldNotAcquireLock) .attach_printable("Unable to acquire redis lock") } async fn save_forex_data_to_redis( app_state: &SessionState, forex_exchange_cache_entry: &FxExchangeRatesCacheEntry, -) -> CustomResult<(), ForexCacheError> { +) -> CustomResult<(), ForexError> { + let forex_api = app_state.conf.forex_api.get_inner(); logger::debug!("forex_log: Saving forex to redis"); app_state .store .get_redis_conn() - .change_context(ForexCacheError::RedisConnectionError)? - .serialize_and_set_key(&REDIX_FOREX_CACHE_DATA.into(), forex_exchange_cache_entry) + .change_context(ForexError::RedisConnectionError)? + .serialize_and_set_key_with_expiry( + &REDIX_FOREX_CACHE_DATA.into(), + forex_exchange_cache_entry, + i64::from(forex_api.redis_ttl_in_seconds), + ) .await - .change_context(ForexCacheError::RedisWriteError) + .change_context(ForexError::RedisWriteError) .attach_printable("Unable to save forex data to redis") } async fn retrieve_forex_data_from_redis( app_state: &SessionState, -) -> CustomResult<Option<FxExchangeRatesCacheEntry>, ForexCacheError> { +) -> CustomResult<Option<FxExchangeRatesCacheEntry>, ForexError> { logger::debug!("forex_log: Retrieving forex from redis"); app_state .store .get_redis_conn() - .change_context(ForexCacheError::RedisConnectionError)? + .change_context(ForexError::RedisConnectionError)? .get_and_deserialize_key(&REDIX_FOREX_CACHE_DATA.into(), "FxExchangeRatesCache") .await - .change_context(ForexCacheError::EntryNotFound) + .change_context(ForexError::EntryNotFound) .attach_printable("Forex entry not found in redis") } async fn is_redis_expired( redis_cache: Option<&FxExchangeRatesCacheEntry>, - call_delay: i64, + data_expiration_delay: u32, ) -> Option<Arc<ExchangeRates>> { redis_cache.and_then(|cache| { - if cache.timestamp + call_delay > date_time::now_unix_timestamp() { + if cache.timestamp + i64::from(data_expiration_delay) > date_time::now_unix_timestamp() { Some(cache.data.clone()) } else { logger::debug!("forex_log: Forex stored in redis is expired"); @@ -514,23 +518,23 @@ pub async fn convert_currency( amount: i64, to_currency: String, from_currency: String, -) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexCacheError> { +) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexError> { let forex_api = state.conf.forex_api.get_inner(); - let rates = get_forex_rates(&state, forex_api.call_delay) + let rates = get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds) .await - .change_context(ForexCacheError::ApiError)?; + .change_context(ForexError::ApiError)?; let to_currency = enums::Currency::from_str(to_currency.as_str()) - .change_context(ForexCacheError::CurrencyNotAcceptable) + .change_context(ForexError::CurrencyNotAcceptable) .attach_printable("The provided currency is not acceptable")?; let from_currency = enums::Currency::from_str(from_currency.as_str()) - .change_context(ForexCacheError::CurrencyNotAcceptable) + .change_context(ForexError::CurrencyNotAcceptable) .attach_printable("The provided currency is not acceptable")?; let converted_amount = currency_conversion::conversion::convert(&rates.data, from_currency, to_currency, amount) - .change_context(ForexCacheError::ConversionError) + .change_context(ForexError::ConversionError) .attach_printable("Unable to perform currency conversion")?; Ok(api_models::currency::CurrencyConversionResponse { diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index a85ca141281..960d94bf7e4 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -47,10 +47,11 @@ locker_enabled = true ttl_for_storage_in_secs = 220752000 [forex_api] -call_delay = 21600 api_key = "" fallback_api_key = "" -redis_lock_timeout = 100 +data_expiration_delay_in_seconds = 21600 +redis_lock_timeout_in_seconds = 100 +redis_ttl_in_seconds = 172800 [eph_key] validity = 1
2025-03-06T19:18:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Adding a custom expiry time for Forex data saved in redis (172800 seconds ~ 2days). A new config is added as well: `redis_cache_expiry_in_seconds = 172800` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location 'http://localhost:8080/forex/rates' \ --header 'api-key: dev_Gt1XtwvVZ9bw94pn30Cvs3Oc5buVwgAxPEIyNwz1hFjyNUIYEHC7NDSWzHlFc84H' \ --data '' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
5cdfe8325481909a8a1596f967303eff44ffbcec
5cdfe8325481909a8a1596f967303eff44ffbcec
juspay/hyperswitch
juspay__hyperswitch-7488
Bug: feat(core): Add V2 Authentication to all available endpoints Introduces V2 authentication mechanisms for various admin and client-side APIs : - [ ] Add V2AdminApiAuth and modified AdminApiAuthWithMerchantIdFromRoute for V2 - [ ] Add V2ApiKeyAuth , V2AdminApiAuth and V2ClientAuth to the endpoints - [ ] Refactor functions to support V2 Auth as well as V1 Auth
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index b32fe76f5ec..d82bef27d1f 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -483,6 +483,6 @@ pub enum RevenueRecoveryError { PaymentIntentCreateFailed, #[error("Source verification failed for billing connector")] WebhookAuthenticationFailed, - #[error("Payment merchant connector account not found using acccount reference id")] + #[error("Payment merchant connector account not found using account reference id")] PaymentMerchantConnectorAccountNotFound, } diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index a38a9df72be..3cd959838a5 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -8,7 +8,7 @@ use crate::{ types::api::admin, }; -#[cfg(feature = "olap")] +#[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::OrganizationCreate))] pub async fn organization_create( state: web::Data<AppState>, @@ -27,8 +27,26 @@ pub async fn organization_create( )) .await } - -#[cfg(feature = "olap")] +#[cfg(all(feature = "olap", feature = "v2"))] +#[instrument(skip_all, fields(flow = ?Flow::OrganizationCreate))] +pub async fn organization_create( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<admin::OrganizationCreateRequest>, +) -> HttpResponse { + let flow = Flow::OrganizationCreate; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, _, req, _| create_organization(state, req), + &auth::V2AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} +#[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::OrganizationUpdate))] pub async fn organization_update( state: web::Data<AppState>, @@ -59,8 +77,38 @@ pub async fn organization_update( )) .await } - -#[cfg(feature = "olap")] +#[cfg(all(feature = "olap", feature = "v2"))] +#[instrument(skip_all, fields(flow = ?Flow::OrganizationUpdate))] +pub async fn organization_update( + state: web::Data<AppState>, + req: HttpRequest, + org_id: web::Path<common_utils::id_type::OrganizationId>, + json_payload: web::Json<admin::OrganizationUpdateRequest>, +) -> HttpResponse { + let flow = Flow::OrganizationUpdate; + let organization_id = org_id.into_inner(); + let org_id = admin::OrganizationId { + organization_id: organization_id.clone(), + }; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, _, req, _| update_organization(state, org_id.clone(), req), + auth::auth_type( + &auth::V2AdminApiAuth, + &auth::JWTAuthOrganizationFromRoute { + organization_id, + required_permission: Permission::OrganizationAccountWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} +#[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::OrganizationRetrieve))] pub async fn organization_retrieve( state: web::Data<AppState>, @@ -92,6 +140,38 @@ pub async fn organization_retrieve( .await } +#[cfg(all(feature = "olap", feature = "v2"))] +#[instrument(skip_all, fields(flow = ?Flow::OrganizationRetrieve))] +pub async fn organization_retrieve( + state: web::Data<AppState>, + req: HttpRequest, + org_id: web::Path<common_utils::id_type::OrganizationId>, +) -> HttpResponse { + let flow = Flow::OrganizationRetrieve; + let organization_id = org_id.into_inner(); + let payload = admin::OrganizationId { + organization_id: organization_id.clone(), + }; + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, _, req, _| get_organization(state, req), + auth::auth_type( + &auth::V2AdminApiAuth, + &auth::JWTAuthOrganizationFromRoute { + organization_id, + required_permission: Permission::OrganizationAccountRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountCreate))] pub async fn merchant_account_create( @@ -144,15 +224,51 @@ pub async fn merchant_account_create( &req, new_request_payload_with_org_id, |state, _, req, _| create_merchant_account(state, req), - &auth::AdminApiAuth, + &auth::V2AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } +#[cfg(feature = "v1")] +#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountRetrieve))] +pub async fn retrieve_merchant_account( + state: web::Data<AppState>, + req: HttpRequest, + mid: web::Path<common_utils::id_type::MerchantId>, +) -> HttpResponse { + let flow = Flow::MerchantsAccountRetrieve; + let merchant_id = mid.into_inner(); + let payload = admin::MerchantId { + merchant_id: merchant_id.clone(), + }; + api::server_wrap( + flow, + state, + &req, + payload, + |state, _, req, _| get_merchant_account(state, req, None), + auth::auth_type( + &auth::AdminApiAuth, + &auth::JWTAuthMerchantFromRoute { + merchant_id, + // This should ideally be MerchantAccountRead, but since FE is calling this API for + // profile level users currently keeping this as ProfileAccountRead. FE is removing + // this API call for profile level users. + // TODO: Convert this to MerchantAccountRead once FE changes are done. + required_permission: Permission::ProfileAccountRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + ) + .await +} + /// Merchant Account - Retrieve /// /// Retrieve a merchant account details. +#[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountRetrieve))] pub async fn retrieve_merchant_account( state: web::Data<AppState>, @@ -171,7 +287,7 @@ pub async fn retrieve_merchant_account( payload, |state, _, req, _| get_merchant_account(state, req, None), auth::auth_type( - &auth::AdminApiAuth, + &auth::V2AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, // This should ideally be MerchantAccountRead, but since FE is calling this API for @@ -207,7 +323,7 @@ pub async fn merchant_account_list( organization_id, |state, _, request, _| list_merchant_account(state, request), auth::auth_type( - &auth::AdminApiAuth, + &auth::V2AdminApiAuth, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountRead, }, @@ -248,6 +364,35 @@ pub async fn merchant_account_list( /// Merchant Account - Update /// /// To update an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountUpdate))] +pub async fn update_merchant_account( + state: web::Data<AppState>, + req: HttpRequest, + mid: web::Path<common_utils::id_type::MerchantId>, + json_payload: web::Json<admin::MerchantAccountUpdate>, +) -> HttpResponse { + let flow = Flow::MerchantsAccountUpdate; + let merchant_id = mid.into_inner(); + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, _, req, _| merchant_account_update(state, &merchant_id, None, req), + auth::auth_type( + &auth::V2AdminApiAuth, + &auth::JWTAuthMerchantFromRoute { + merchant_id: merchant_id.clone(), + required_permission: Permission::MerchantAccountWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} +#[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountUpdate))] pub async fn update_merchant_account( state: web::Data<AppState>, @@ -279,6 +424,30 @@ pub async fn update_merchant_account( /// Merchant Account - Delete /// /// To delete a merchant account +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountDelete))] +pub async fn delete_merchant_account( + state: web::Data<AppState>, + req: HttpRequest, + mid: web::Path<common_utils::id_type::MerchantId>, +) -> HttpResponse { + let flow = Flow::MerchantsAccountDelete; + let mid = mid.into_inner(); + + let payload = web::Json(admin::MerchantId { merchant_id: mid }).into_inner(); + api::server_wrap( + flow, + state, + &req, + payload, + |state, _, req, _| merchant_account_delete(state, req.merchant_id), + &auth::V2AdminApiAuth, + api_locking::LockAction::NotApplicable, + ) + .await +} + +#[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountDelete))] pub async fn delete_merchant_account( state: web::Data<AppState>, @@ -712,7 +881,7 @@ pub async fn connector_update( payload, |state, _, req, _| update_connector(state, &merchant_id, None, &id, req), auth::auth_type( - &auth::AdminApiAuth, + &auth::V2AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantConnectorWrite, diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index 8c0b7137662..911617753d4 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -268,7 +268,7 @@ pub async fn api_key_revoke( (&merchant_id, &key_id), |state, _, (merchant_id, key_id), _| api_keys::revoke_api_key(state, merchant_id, key_id), auth::auth_type( - &auth::AdminApiAuth, + &auth::V2AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantApiKeyWrite, diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index c793e3c85e5..c9ff466af00 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -8,7 +8,34 @@ use crate::{ services::{api, authentication as auth, authorization::permissions::Permission}, types::api::customers, }; - +#[cfg(all(feature = "v2", feature = "customer_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))] +pub async fn customers_create( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<customers::CustomerRequest>, +) -> HttpResponse { + let flow = Flow::CustomersCreate; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: auth::AuthenticationData, req, _| { + create_customer(state, auth.merchant_account, auth.key_store, req) + }, + auth::auth_type( + &auth::V2ApiKeyAuth, + &auth::JWTAuth { + permission: Permission::MerchantCustomerWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))] pub async fn customers_create( state: web::Data<AppState>, @@ -115,7 +142,42 @@ pub async fn customers_retrieve( )) .await } +#[cfg(all(feature = "v2", feature = "customer_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::CustomersList))] +pub async fn customers_list( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<customers::CustomerListRequest>, +) -> HttpResponse { + let flow = Flow::CustomersList; + let payload = query.into_inner(); + api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: auth::AuthenticationData, request, _| { + list_customers( + state, + auth.merchant_account.get_id().to_owned(), + None, + auth.key_store, + request, + ) + }, + auth::auth_type( + &auth::V2ApiKeyAuth, + &auth::JWTAuth { + permission: Permission::MerchantCustomerRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + ) + .await +} +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all, fields(flow = ?Flow::CustomersList))] pub async fn customers_list( state: web::Data<AppState>, @@ -219,7 +281,7 @@ pub async fn customers_update( ) }, auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::MerchantCustomerWrite, }, @@ -249,7 +311,7 @@ pub async fn customers_delete( delete_customer(state, auth.merchant_account, id, auth.key_store) }, auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::MerchantCustomerWrite, }, diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rs index 64b46eb2f55..5a802cb4c5a 100644 --- a/crates/router/src/routes/ephemeral_key.rs +++ b/crates/router/src/routes/ephemeral_key.rs @@ -78,7 +78,7 @@ pub async fn client_secret_create( req.headers(), ) }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -99,7 +99,7 @@ pub async fn client_secret_delete( &req, payload, |state, _: auth::AuthenticationData, req, _| helpers::delete_client_secret(state, req), - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 92f16b6c4c7..ec5e1dacf0a 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -95,7 +95,7 @@ pub async fn create_payment_method_api( )) .await }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -214,7 +214,7 @@ pub async fn payment_method_retrieve_api( auth.merchant_account, ) }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -246,7 +246,7 @@ pub async fn payment_method_delete_api( auth.merchant_account, ) }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -613,7 +613,7 @@ pub async fn list_customer_payment_method_api( ) }, auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::MerchantCustomerRead, }, diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 9708f34c53c..4e670a594a5 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -147,9 +147,9 @@ pub async fn payments_create_intent( ) }, match env::which() { - env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth), + env::Env::Production => &auth::V2ApiKeyAuth, _ => auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfilePaymentWrite, }, @@ -210,7 +210,7 @@ pub async fn payments_get_intent( auth.platform_merchant_account, ) }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -249,9 +249,9 @@ pub async fn payments_create_and_confirm_intent( ) }, match env::which() { - env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth), + env::Env::Production => &auth::V2ApiKeyAuth, _ => auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfilePaymentWrite, }, @@ -313,7 +313,7 @@ pub async fn payments_update_intent( auth.platform_merchant_account, ) }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -825,7 +825,7 @@ pub async fn payments_connector_session( tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { - global_payment_id, + global_payment_id: global_payment_id.clone(), payload: json_payload.into_inner(), }; @@ -868,7 +868,9 @@ pub async fn payments_connector_session( auth.platform_merchant_account, ) }, - &auth::HeaderAuth(auth::PublishableKeyAuth), + &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( + global_payment_id, + )), locking_action, )) .await @@ -1247,7 +1249,7 @@ pub async fn payments_list( payments::list_payments(state, auth.merchant_account, auth.key_store, req) }, auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::MerchantPaymentRead, }, @@ -2423,7 +2425,7 @@ pub async fn payment_confirm_intent( tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { - global_payment_id, + global_payment_id: global_payment_id.clone(), payload: json_payload.into_inner(), }; @@ -2468,7 +2470,9 @@ pub async fn payment_confirm_intent( )) .await }, - &auth::PublishableKeyAuth, + &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( + global_payment_id, + )), locking_action, )) .await @@ -2540,7 +2544,7 @@ pub async fn proxy_confirm_intent( header_payload.clone(), )) }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, locking_action, )) .await @@ -2611,7 +2615,7 @@ pub async fn payment_status( .await }, auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfilePaymentRead, }, @@ -2657,7 +2661,7 @@ pub async fn payment_get_intent_using_merchant_reference_id( )) .await }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -2776,7 +2780,7 @@ pub async fn payments_capture( .await }, auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfileAccountWrite, }, @@ -2802,7 +2806,7 @@ pub async fn list_payment_methods( tracing::Span::current().record("payment_id", global_payment_id.get_string_repr()); let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId { - global_payment_id, + global_payment_id: global_payment_id.clone(), payload, }; @@ -2829,7 +2833,9 @@ pub async fn list_payment_methods( &header_payload, ) }, - &auth::PublishableKeyAuth, + &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( + global_payment_id, + )), api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index ac0f997a278..04a0d331688 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -82,7 +82,7 @@ pub async fn routing_create_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfileRoutingWrite, }, @@ -170,7 +170,7 @@ pub async fn routing_link_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::ApiKeyAuth, + &auth::V2ApiKeyAuth, &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::MerchantRoutingWrite, @@ -252,7 +252,7 @@ pub async fn routing_retrieve_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfileRoutingRead, }, @@ -373,7 +373,7 @@ pub async fn routing_unlink_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::ApiKeyAuth, + &auth::V2ApiKeyAuth, &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::MerchantRoutingWrite, @@ -459,7 +459,7 @@ pub async fn routing_update_default_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::MerchantRoutingWrite, }, @@ -535,7 +535,7 @@ pub async fn routing_retrieve_default_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::MerchantRoutingRead, @@ -749,7 +749,7 @@ pub async fn upsert_decision_manager_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfileThreeDsDecisionManagerWrite, }, @@ -818,7 +818,7 @@ pub async fn retrieve_decision_manager_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuth { permission: Permission::ProfileThreeDsDecisionManagerWrite, }, @@ -976,7 +976,7 @@ pub async fn routing_retrieve_linked_config( }, #[cfg(not(feature = "release"))] auth::auth_type( - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::V2ApiKeyAuth, &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::ProfileRoutingRead, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 502ebb5099f..4eb91756661 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -1064,6 +1064,44 @@ where } } +#[derive(Debug, Default)] +pub struct V2AdminApiAuth; + +#[async_trait] +impl<A> AuthenticateAndFetch<(), A> for V2AdminApiAuth +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<((), AuthenticationType)> { + let header_map_struct = HeaderMapStruct::new(request_headers); + let auth_string = header_map_struct.get_auth_string_from_header()?; + let request_admin_api_key = auth_string + .split(',') + .find_map(|part| part.trim().strip_prefix("admin-api-key=")) + .ok_or_else(|| { + report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Unable to parse admin_api_key") + })?; + if request_admin_api_key.is_empty() { + return Err(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Admin Api key is empty"); + } + let conf = state.conf(); + + let admin_api_key = &conf.secrets.get_inner().admin_api_key; + + if request_admin_api_key != admin_api_key.peek() { + Err(report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Admin Authentication Failure"))?; + } + + Ok(((), AuthenticationType::AdminApiKey)) + } +} #[derive(Debug)] pub struct AdminApiAuthWithMerchantIdFromRoute(pub id_type::MerchantId); @@ -1130,7 +1168,7 @@ where throw_error_if_platform_merchant_authentication_required(request_headers)?; } - AdminApiAuth + V2AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; @@ -1194,7 +1232,7 @@ where throw_error_if_platform_merchant_authentication_required(request_headers)?; } - AdminApiAuth + V2AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; @@ -1400,7 +1438,7 @@ where throw_error_if_platform_merchant_authentication_required(request_headers)?; } - AdminApiAuth + V2AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; @@ -1465,7 +1503,7 @@ where throw_error_if_platform_merchant_authentication_required(request_headers)?; } - AdminApiAuth + V2AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?;
2025-03-12T04:05:17Z
## Type of Change - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This commit introduces V2 authentication mechanisms for various admin and client-side APIs : - [x] Added V2AdminApiAuth and modified AdminApiAuthWithMerchantIdFromRoute for V2 - [x] Added V2ApiKeyAuth , V2AdminApiAuth and V2ClientAuth to the endpoints - [x] Refactored functions to support V2 Auth as well as V1 Auth ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context ## How did you test it? For `/v2/merchant-accounts` Request ``` curl --location 'http://localhost:8080/v2/merchant-accounts' \ --header 'x-organization-id: org_d2lZPiRPOGbIMmFcb59A' \ --header 'Content-Type: application/json' \ --header 'Authorization: admin-api-key=test_admin' \ --data '{ "merchant_name": "cloth_seller" }' ``` Response ``` { "id": "cloth_seller_KdjFPBxrxWyX09jri2VB", "merchant_name": "cloth_seller", "merchant_details": null, "publishable_key": "pk_dev_735cafe5f43446e88d22bedec15b0139", "metadata": null, "organization_id": "org_d2lZPiRPOGbIMmFcb59A", "recon_status": "not_requested", "product_type": "orchestration" } ``` For `/v2/organization` Request ``` curl --location 'http://localhost:8080/v2/organization' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'Content-Type: application/json' \ --data '{ "organization_name": "random_org_1741776562" }' ``` Response ``` { "id": "org_m4fLYdEFb7PNHynIfmZO", "organization_name": "random_org_1741776558", "organization_details": null, "metadata": null, "modified_at": "2025-03-12 10:49:18.475431", "created_at": "2025-03-12 10:49:18.475424" } ``` This is how V2AdminApiAuth looks like ``` pub struct V2AdminApiAuth; #[async_trait] impl<A> AuthenticateAndFetch<(), A> for V2AdminApiAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<((), AuthenticationType)> { let header_map_struct = HeaderMapStruct::new(&request_headers); let auth_string = header_map_struct.get_auth_string_from_header()?; let request_admin_api_key = auth_string .split(',') .find_map(|part| part.trim().strip_prefix("admin-api-key=")) .ok_or_else(|| { report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Unable to parse admin_api_key") })?; if request_admin_api_key.is_empty() { return Err(errors::ApiErrorResponse::Unauthorized) .attach_printable("Admin Api key is empty"); } let conf = state.conf(); let admin_api_key = &conf.secrets.get_inner().admin_api_key; if request_admin_api_key != admin_api_key.peek() { Err(report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Admin Authentication Failure"))?; } Ok(((), AuthenticationType::AdminApiKey)) } } ``` ### What changes are done in authorization header How it was earlier? ``` api-key = {{api-key}} client-secret={{client_secret}} api-key = {{admin_api_key}} ``` Changed version ``` Authorization = api-key={{api-key}} Authorization = admin-api-key={{admin_api_key}} Authorization = publishable-key={{publishable_key}},client-secret={{client_secret}} ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
4f6174d1bf6dd0713b0a3d8e005671c884555144
4f6174d1bf6dd0713b0a3d8e005671c884555144
juspay/hyperswitch
juspay__hyperswitch-7469
Bug: [BUG] [WISE] Changed type of error status from i32 to String ### Bug Description While creating payouts, Hyperswitch throws an error because the connector sends an error status as String, while Hyperswitch accepts it as i32. ### Expected Behavior Hyperswitch should not throw error while creating payouts. ### Actual Behavior While creating payouts, Hyperswitch throws an error because the connector sends an error status as String, while Hyperswitch accepts it as i32. ### Steps To Reproduce Create payout for wise connector, and Hyperswitch will throw an error if error response is returned by connector. ### Context For The Bug _No response_ ### Environment Integ, Sandbox, Prod ### 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/wise/transformers.rs b/crates/router/src/connector/wise/transformers.rs index 513a762bfd3..d3e9efa0f7f 100644 --- a/crates/router/src/connector/wise/transformers.rs +++ b/crates/router/src/connector/wise/transformers.rs @@ -56,7 +56,7 @@ impl TryFrom<&types::ConnectorAuthType> for WiseAuthType { pub struct ErrorResponse { pub timestamp: Option<String>, pub errors: Option<Vec<SubError>>, - pub status: Option<i32>, + pub status: Option<String>, pub error: Option<String>, pub error_description: Option<String>, pub message: Option<String>,
2025-03-10T09:55:07Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> The error status was previously being accepted as i32, which was causing Hyperswitch to throw an error because the connector returns the status as a String. The status has been changed to type String 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). --> Issue Link: https://github.com/juspay/hyperswitch/issues/7469 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> **Postman Tests** **1. Payouts Create** -Request ``` curl --location 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_gBOBAd2KdnQ2Sicn24ETzOLMqRjdMVtjSjy17FYmjQjmj26klfRIWLOnspqQX9YW' \ --data-raw '{ "amount": 10, "currency": "GBP", "customer_id": "cus_wtc11I3P4ObeIZk0FpBR", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payout request", "payout_type": "bank", "connector": [ "wise" ], "payout_method_data": { "bank": { "bank_sort_code": "231470", "bank_account_number": "28821822", "bank_name": "Deutsche Bank", "bank_country_code": "NL", "bank_city": "Amsterdam" } }, "billing": { "address": { "line1": "1467", "city": "San Fransico", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "entity_type": "Individual", "recurring": true, "metadata": { "ref": "123" }, "confirm": true, "auto_fulfill": true, "profile_id": "pro_U84OKvi5otdXGYq6tjlx" }' ``` -Response ``` { "payout_id": "5f7ac2b0-69cb-4916-9ad5-a901770bbc72", "merchant_id": "merchant_1741598972", "amount": 10, "currency": "GBP", "connector": "wise", "payout_type": "bank", "payout_method_data": { "bank": { "bank_sort_code": "23**70", "bank_account_number": "****1822", "bank_name": "Deutsche Bank", "bank_country_code": "NL", "bank_city": "Amsterdam" } }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": null, "line3": null, "zip": "94122", "state": "CA", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "auto_fulfill": true, "customer_id": "cus_wtc11I3P4ObeIZk0FpBR", "customer": { "id": "cus_wtc11I3P4ObeIZk0FpBR", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "client_secret": "payout_5f7ac2b0-69cb-4916-9ad5-a901770bbc72_secret_B0h34yZciT2HwmmcHKgu", "return_url": null, "business_country": null, "business_label": null, "description": "Its my first payout request", "entity_type": "Individual", "recurring": true, "metadata": { "ref": "123" }, "merchant_connector_id": "mca_d6VH9HeZfA07bVki7LMf", "status": "failed", "error_message": "", "error_code": "REJECTED", "profile_id": "pro_U84OKvi5otdXGYq6tjlx", "created": "2025-03-10T09:48:10.143Z", "connector_transaction_id": "54879667", "priority": null, "payout_link": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "unified_code": null, "unified_message": null, "payout_method_id": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
617adfa33fd543131b5c4d8983319bfdcaa6c425
617adfa33fd543131b5c4d8983319bfdcaa6c425
juspay/hyperswitch
juspay__hyperswitch-7464
Bug: Handle optional fields in nexixpay payments requests. Optional billing details should be used for non-mandatory billing fields.
diff --git a/config/config.example.toml b/config/config.example.toml index ad910ef415a..a95cc7c1405 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -618,8 +618,8 @@ debit = { country = "US, CA", currency = "USD, CAD" } klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } [pm_filters.nexixpay] -credit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } -debit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } +credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } +debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } [pm_filters.square] credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 47b65efabc4..c84a68e0573 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -378,8 +378,8 @@ samsung_pay = { currency = "USD,GBP,EUR" } paze = { currency = "USD" } [pm_filters.nexixpay] -credit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } -debit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } +credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } +debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } [pm_filters.square] credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index fc4bca222a9..6d12d8b467a 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -334,8 +334,8 @@ samsung_pay = { currency = "USD,GBP,EUR" } paze = { currency = "USD" } [pm_filters.nexixpay] -credit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } -debit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } +credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } +debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } [pm_filters.square] credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 37346fc3467..58d298e9c5c 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -336,8 +336,8 @@ samsung_pay = { currency = "USD,GBP,EUR" } paze = { currency = "USD" } [pm_filters.nexixpay] -credit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } -debit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } +credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } +debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } [pm_filters.square] credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } diff --git a/config/development.toml b/config/development.toml index eab89187a46..1062cdc64f7 100644 --- a/config/development.toml +++ b/config/development.toml @@ -553,8 +553,8 @@ samsung_pay = { currency = "USD,GBP,EUR" } paze = { currency = "USD" } [pm_filters.nexixpay] -credit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } -debit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } +credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } +debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } [pm_filters.square] credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 9a24adcd5e9..1cc35e9b799 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -526,8 +526,8 @@ samsung_pay = { currency = "USD,GBP,EUR" } paze = { currency = "USD" } [pm_filters.nexixpay] -credit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } -debit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } +credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } +debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } [pm_filters.square] credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs index fd504a7a412..27eebf78dfb 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs @@ -158,18 +158,18 @@ pub struct Order { #[serde(rename_all = "camelCase")] pub struct CustomerInfo { card_holder_name: Secret<String>, - billing_address: BillingAddress, + billing_address: Option<BillingAddress>, shipping_address: Option<ShippingAddress>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BillingAddress { - name: Secret<String>, - street: Secret<String>, - city: String, - post_code: Secret<String>, - country: enums::CountryAlpha2, + name: Option<Secret<String>>, + street: Option<Secret<String>>, + city: Option<String>, + post_code: Option<Secret<String>>, + country: Option<enums::CountryAlpha2>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -445,19 +445,29 @@ impl TryFrom<&NexixpayRouterData<&PaymentsAuthorizeRouterData>> for NexixpayPaym fn try_from( item: &NexixpayRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { - let billing_address_street = format!( - "{}, {}", - item.router_data.get_billing_line1()?.expose(), - item.router_data.get_billing_line2()?.expose() - ); - - let billing_address = BillingAddress { - name: item.router_data.get_billing_full_name()?, - street: Secret::new(billing_address_street), - city: item.router_data.get_billing_city()?, - post_code: item.router_data.get_billing_zip()?, - country: item.router_data.get_billing_country()?, + let billing_address_street = match ( + item.router_data.get_optional_billing_line1(), + item.router_data.get_optional_billing_line2(), + ) { + (Some(line1), Some(line2)) => Some(Secret::new(format!( + "{}, {}", + line1.expose(), + line2.expose() + ))), + (Some(line1), None) => Some(line1), + (None, Some(line2)) => Some(line2), + (None, None) => None, }; + let billing_address = item + .router_data + .get_optional_billing() + .map(|_| BillingAddress { + name: item.router_data.get_optional_billing_full_name(), + street: billing_address_street, + city: item.router_data.get_optional_billing_city(), + post_code: item.router_data.get_optional_billing_zip(), + country: item.router_data.get_optional_billing_country(), + }); let shipping_address_street = match ( item.router_data.get_optional_shipping_line1(), item.router_data.get_optional_shipping_line2(), @@ -474,7 +484,7 @@ impl TryFrom<&NexixpayRouterData<&PaymentsAuthorizeRouterData>> for NexixpayPaym let shipping_address = item .router_data - .get_optional_billing() + .get_optional_shipping() .map(|_| ShippingAddress { name: item.router_data.get_optional_shipping_full_name(), street: shipping_address_street, @@ -995,19 +1005,29 @@ impl TryFrom<&NexixpayRouterData<&PaymentsCompleteAuthorizeRouterData>> let order_id = item.router_data.connector_request_reference_id.clone(); let amount = item.amount.clone(); - let billing_address_street = format!( - "{}, {}", - item.router_data.get_billing_line1()?.expose(), - item.router_data.get_billing_line2()?.expose() - ); - - let billing_address = BillingAddress { - name: item.router_data.get_billing_full_name()?, - street: Secret::new(billing_address_street), - city: item.router_data.get_billing_city()?, - post_code: item.router_data.get_billing_zip()?, - country: item.router_data.get_billing_country()?, + let billing_address_street = match ( + item.router_data.get_optional_billing_line1(), + item.router_data.get_optional_billing_line2(), + ) { + (Some(line1), Some(line2)) => Some(Secret::new(format!( + "{}, {}", + line1.expose(), + line2.expose() + ))), + (Some(line1), None) => Some(line1), + (None, Some(line2)) => Some(line2), + (None, None) => None, }; + let billing_address = item + .router_data + .get_optional_billing() + .map(|_| BillingAddress { + name: item.router_data.get_optional_billing_full_name(), + street: billing_address_street, + city: item.router_data.get_optional_billing_city(), + post_code: item.router_data.get_optional_billing_zip(), + country: item.router_data.get_optional_billing_country(), + }); let shipping_address_street = match ( item.router_data.get_optional_shipping_line1(), item.router_data.get_optional_shipping_line2(), @@ -1024,7 +1044,7 @@ impl TryFrom<&NexixpayRouterData<&PaymentsCompleteAuthorizeRouterData>> let shipping_address = item .router_data - .get_optional_billing() + .get_optional_shipping() .map(|_| ShippingAddress { name: item.router_data.get_optional_shipping_full_name(), street: shipping_address_street, diff --git a/crates/router/src/configs/defaults/payment_connector_required_fields.rs b/crates/router/src/configs/defaults/payment_connector_required_fields.rs index 3849054045c..f31ea0c9d80 100644 --- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs +++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs @@ -2239,42 +2239,6 @@ impl Default for settings::RequiredFields { value: None, } ), - ( - "billing.address.line1".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.line1".to_string(), - display_name: "line1".to_string(), - field_type: enums::FieldType::UserAddressLine1, - value: None, - } - ), - ( - "billing.address.line2".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.line2".to_string(), - display_name: "line1".to_string(), - field_type: enums::FieldType::UserAddressLine2, - value: None, - } - ), - ( - "billing.address.city".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.city".to_string(), - display_name: "city".to_string(), - field_type: enums::FieldType::UserAddressCity, - value: None, - } - ), - ( - "billing.address.zip".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.zip".to_string(), - display_name: "zip".to_string(), - field_type: enums::FieldType::UserAddressPincode, - value: None, - } - ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { @@ -5746,42 +5710,6 @@ impl Default for settings::RequiredFields { value: None, } ), - ( - "billing.address.line1".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.line1".to_string(), - display_name: "line1".to_string(), - field_type: enums::FieldType::UserAddressLine1, - value: None, - } - ), - ( - "billing.address.line2".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.line2".to_string(), - display_name: "line1".to_string(), - field_type: enums::FieldType::UserAddressLine2, - value: None, - } - ), - ( - "billing.address.city".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.city".to_string(), - display_name: "city".to_string(), - field_type: enums::FieldType::UserAddressCity, - value: None, - } - ), - ( - "billing.address.zip".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.zip".to_string(), - display_name: "zip".to_string(), - field_type: enums::FieldType::UserAddressPincode, - value: None, - } - ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index bdf46a8ee40..dc7a310b6b8 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -310,8 +310,8 @@ credit = { country = "US,CA", currency = "USD" } debit = { country = "US,CA", currency = "USD" } [pm_filters.nexixpay] -credit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } -debit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } +credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } +debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } [pm_filters.square] credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" }
2025-03-09T03:32:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Optional billing details should be used for non-mandatory billing fields. Billing address is optional field for making requests to nexixpay. Either billing.first_name or billing.second_name should be present mandatorily. Includes ENV changes related to support of currency and country for nexixpay connector. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Curl to test the optional billing address. ``` curl --location 'localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_RFY4WCFOFu2eEmA13QTQGzHyyjIvaTgdTqKsp2yBy4ofwyZ7fdyIMIJKHcHzGbC5' \ --data-raw '{ "amount": 3545, "currency": "EUR", "amount_to_capture": 3545, "confirm": true, "profile_id": "pro_56hlX3G8qT0Fz4qlqO2J", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "setup_future_usage": "off_session", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "phone_country_code": "+1", "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4349940199004549", "card_exp_month": "12", "card_exp_year": "30", "card_cvc": "396" } }, "billing": { "address": { "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 3545, "account_name": "transaction_processing" } ], "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "customer_acceptance": { "acceptance_type": "online", "accepted_at":"1963-05-03T04:07:52.723Z", "online": { "ip_address":"127.0.0.1", "user_agent": "amet irure esse" } }, "connector":["nexixpay"], "connector_metadata": { "noon": { "order_category": "pay" } }, "payment_link": false, "payment_link_config": { "theme": "", "logo": "", "seller_name": "", "sdk_layout": "", "display_sdk_only": false, "enabled_saved_payment_method": false }, "payment_type": "normal", "request_incremental_authorization": false, "merchant_order_reference_id": "test_ord", "session_expiry": 900 }' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
833da1c3c5a0f006a689b05554c547205774c823
833da1c3c5a0f006a689b05554c547205774c823
juspay/hyperswitch
juspay__hyperswitch-7482
Bug: feat(analytics): modify authentication queries and add generate report for authentications Need to modify the authentication analytics queries to differentiate between **frictionless flow** and **challenge flow** through the authentication_type field. Introduce support for **authentication report generation**, similar to the existing reports for payments, refunds, and disputes.
diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs index a2640be6ead..bdcbdd86a94 100644 --- a/crates/analytics/src/auth_events/core.rs +++ b/crates/analytics/src/auth_events/core.rs @@ -165,6 +165,7 @@ pub async fn get_filters( .filter_map(|fil: AuthEventFilterRow| match dim { AuthEventDimensions::AuthenticationStatus => fil.authentication_status.map(|i| i.as_ref().to_string()), AuthEventDimensions::TransactionStatus => fil.trans_status.map(|i| i.as_ref().to_string()), + AuthEventDimensions::AuthenticationType => fil.authentication_type.map(|i| i.as_ref().to_string()), AuthEventDimensions::ErrorMessage => fil.error_message, AuthEventDimensions::AuthenticationConnector => fil.authentication_connector.map(|i| i.as_ref().to_string()), AuthEventDimensions::MessageVersion => fil.message_version, diff --git a/crates/analytics/src/auth_events/filters.rs b/crates/analytics/src/auth_events/filters.rs index da8e0b7cfa3..5f65eeaa279 100644 --- a/crates/analytics/src/auth_events/filters.rs +++ b/crates/analytics/src/auth_events/filters.rs @@ -1,4 +1,5 @@ use api_models::analytics::{auth_events::AuthEventDimensions, Granularity, TimeRange}; +use common_enums::DecoupledAuthenticationType; use common_utils::errors::ReportSwitchExt; use diesel_models::enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; use error_stack::ResultExt; @@ -54,6 +55,7 @@ where pub struct AuthEventFilterRow { pub authentication_status: Option<DBEnumWrapper<AuthenticationStatus>>, pub trans_status: Option<DBEnumWrapper<TransactionStatus>>, + pub authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>>, pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>>, pub message_version: Option<String>, diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index fd94aac614c..a3d0fe7b683 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -41,6 +41,7 @@ pub struct AuthEventMetricRow { pub count: Option<i64>, pub authentication_status: Option<DBEnumWrapper<storage_enums::AuthenticationStatus>>, pub trans_status: Option<DBEnumWrapper<storage_enums::TransactionStatus>>, + pub authentication_type: Option<DBEnumWrapper<storage_enums::DecoupledAuthenticationType>>, pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<storage_enums::AuthenticationConnectors>>, pub message_version: Option<String>, diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index 32c76385409..b82d1ef4c35 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -70,7 +70,10 @@ where .switch()?; query_builder - .add_negative_filter_clause("authentication_status", AuthenticationStatus::Pending) + .add_filter_in_range_clause( + "authentication_status", + &[AuthenticationStatus::Success, AuthenticationStatus::Failed], + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -103,6 +106,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_count.rs b/crates/analytics/src/auth_events/metrics/authentication_count.rs index 39df41f53aa..682e8a07f6b 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_count.rs @@ -96,6 +96,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs index cdb89b796dd..047511d477c 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs @@ -12,8 +12,8 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ query::{ - Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, - Window, + Aggregate, FilterTypes, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, + ToSql, Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -45,11 +45,9 @@ where for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } + query_builder - .add_select_column(Aggregate::Count { - field: None, - alias: Some("count"), - }) + .add_select_column("sum(sign_flag) AS count") .switch()?; query_builder @@ -94,6 +92,11 @@ where .switch()?; } + query_builder + .add_order_by_clause("count", Order::Descending) + .attach_printable("Error adding order by clause") + .switch()?; + if let Some(granularity) = granularity { granularity .set_group_by_clause(&mut query_builder) @@ -112,6 +115,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs index 37f9dfd1c1f..9342e9047e0 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs @@ -107,6 +107,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index 039ef00dd6e..984350efe6b 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -101,6 +101,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index beccc093b19..5a2a9400b20 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -4,6 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; +use common_enums::{AuthenticationStatus, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -67,11 +68,17 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "C".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Challenge, + ) .switch()?; query_builder - .add_negative_filter_clause("authentication_status", "pending") + .add_filter_in_range_clause( + "authentication_status", + &[AuthenticationStatus::Success, AuthenticationStatus::Failed], + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -104,6 +111,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index 4d07cffba94..279844388f2 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -4,6 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; +use common_enums::DecoupledAuthenticationType; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -67,7 +68,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "C".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Challenge, + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -99,6 +103,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index 310a45f0530..91e8cc54289 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -4,7 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; -use common_enums::AuthenticationStatus; +use common_enums::{AuthenticationStatus, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -72,7 +72,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "C".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Challenge, + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -105,6 +108,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index 24857bfb840..b08edb10113 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -4,6 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; +use common_enums::DecoupledAuthenticationType; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -67,7 +68,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "Y".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Frictionless, + ) .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range @@ -100,6 +104,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index 79fef8a16d0..80417ac64bf 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -4,7 +4,7 @@ use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; -use common_enums::AuthenticationStatus; +use common_enums::{AuthenticationStatus, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -68,7 +68,10 @@ where .switch()?; query_builder - .add_filter_clause("trans_status", "Y".to_string()) + .add_filter_clause( + "authentication_type", + DecoupledAuthenticationType::Frictionless, + ) .switch()?; query_builder @@ -105,6 +108,7 @@ where AuthEventMetricsBucketIdentifier::new( i.authentication_status.as_ref().map(|i| i.0), i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index f698b1161a0..89f5cbd5b9c 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -1123,6 +1123,7 @@ pub struct ReportConfig { pub payment_function: String, pub refund_function: String, pub dispute_function: String, + pub authentication_function: String, pub region: String, } @@ -1151,6 +1152,7 @@ pub enum AnalyticsFlow { GeneratePaymentReport, GenerateDisputeReport, GenerateRefundReport, + GenerateAuthenticationReport, GetApiEventMetrics, GetApiEventFilters, GetConnectorEvents, diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index d483ce43605..5effd9e70a7 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -19,7 +19,9 @@ use api_models::{ }, refunds::RefundStatus, }; -use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; +use common_enums::{ + AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, +}; use common_utils::{ errors::{CustomResult, ParsingError}, id_type::{MerchantId, OrganizationId, ProfileId}, @@ -506,6 +508,7 @@ impl_to_sql_for_to_string!( TransactionStatus, AuthenticationStatus, AuthenticationConnectors, + DecoupledAuthenticationType, Flow, &String, &bool, diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index a6db92e753f..6a6237e6783 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -4,7 +4,9 @@ use api_models::{ analytics::{frm::FrmTransactionType, refunds::RefundType}, enums::{DisputeStage, DisputeStatus}, }; -use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; +use common_enums::{ + AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, +}; use common_utils::{ errors::{CustomResult, ParsingError}, DbConnectionParams, @@ -100,6 +102,7 @@ db_type!(DisputeStatus); db_type!(AuthenticationStatus); db_type!(TransactionStatus); db_type!(AuthenticationConnectors); +db_type!(DecoupledAuthenticationType); impl<'q, Type> Encode<'q, Postgres> for DBEnumWrapper<Type> where @@ -208,6 +211,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> = + row.try_get("authentication_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -237,6 +245,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow Ok(Self { authentication_status, trans_status, + authentication_type, error_message, authentication_connector, message_version, @@ -259,6 +268,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> = + row.try_get("authentication_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -277,6 +291,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow Ok(Self { authentication_status, trans_status, + authentication_type, error_message, authentication_connector, message_version, diff --git a/crates/api_models/src/analytics/auth_events.rs b/crates/api_models/src/analytics/auth_events.rs index 5c2d4ed2064..2360e564642 100644 --- a/crates/api_models/src/analytics/auth_events.rs +++ b/crates/api_models/src/analytics/auth_events.rs @@ -3,7 +3,9 @@ use std::{ hash::{Hash, Hasher}, }; -use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; +use common_enums::{ + AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, +}; use super::{NameDescription, TimeRange}; @@ -14,6 +16,8 @@ pub struct AuthEventFilters { #[serde(default)] pub trans_status: Vec<TransactionStatus>, #[serde(default)] + pub authentication_type: Vec<DecoupledAuthenticationType>, + #[serde(default)] pub error_message: Vec<String>, #[serde(default)] pub authentication_connector: Vec<AuthenticationConnectors>, @@ -42,6 +46,7 @@ pub enum AuthEventDimensions { #[strum(serialize = "trans_status")] #[serde(rename = "trans_status")] TransactionStatus, + AuthenticationType, ErrorMessage, AuthenticationConnector, MessageVersion, @@ -101,6 +106,7 @@ pub mod metric_behaviour { pub struct ChallengeAttemptCount; pub struct ChallengeSuccessCount; pub struct AuthenticationErrorMessage; + pub struct AuthenticationFunnel; } impl From<AuthEventMetrics> for NameDescription { @@ -125,6 +131,7 @@ impl From<AuthEventDimensions> for NameDescription { pub struct AuthEventMetricsBucketIdentifier { pub authentication_status: Option<AuthenticationStatus>, pub trans_status: Option<TransactionStatus>, + pub authentication_type: Option<DecoupledAuthenticationType>, pub error_message: Option<String>, pub authentication_connector: Option<AuthenticationConnectors>, pub message_version: Option<String>, @@ -140,6 +147,7 @@ impl AuthEventMetricsBucketIdentifier { pub fn new( authentication_status: Option<AuthenticationStatus>, trans_status: Option<TransactionStatus>, + authentication_type: Option<DecoupledAuthenticationType>, error_message: Option<String>, authentication_connector: Option<AuthenticationConnectors>, message_version: Option<String>, @@ -148,6 +156,7 @@ impl AuthEventMetricsBucketIdentifier { Self { authentication_status, trans_status, + authentication_type, error_message, authentication_connector, message_version, @@ -161,6 +170,7 @@ impl Hash for AuthEventMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.authentication_status.hash(state); self.trans_status.hash(state); + self.authentication_type.hash(state); self.authentication_connector.hash(state); self.message_version.hash(state); self.error_message.hash(state); diff --git a/crates/api_models/src/analytics/sdk_events.rs b/crates/api_models/src/analytics/sdk_events.rs index b2abbbe00e1..9a749f1144e 100644 --- a/crates/api_models/src/analytics/sdk_events.rs +++ b/crates/api_models/src/analytics/sdk_events.rs @@ -114,6 +114,10 @@ pub enum SdkEventNames { ThreeDsMethod, LoaderChanged, DisplayThreeDsSdk, + ThreeDsSdkInit, + AreqParamsGeneration, + ChallengePresented, + ChallengeComplete, } pub mod metric_behaviour { diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 858c16d052f..cc242f86a5b 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -90,6 +90,10 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_merchant_payment_report)), ) + .service( + web::resource("report/authentications") + .route(web::post().to(generate_merchant_authentication_report)), + ) .service( web::resource("metrics/sdk_events") .route(web::post().to(get_sdk_event_metrics)), @@ -190,6 +194,11 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_merchant_payment_report)), ) + .service( + web::resource("report/authentications").route( + web::post().to(generate_merchant_authentication_report), + ), + ) .service( web::resource("metrics/api_events") .route(web::post().to(get_merchant_api_events_metrics)), @@ -252,6 +261,10 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_org_payment_report)), ) + .service( + web::resource("report/authentications") + .route(web::post().to(generate_org_authentication_report)), + ) .service( web::resource("metrics/sankey") .route(web::post().to(get_org_sankey)), @@ -306,6 +319,11 @@ pub mod routes { web::resource("report/payments") .route(web::post().to(generate_profile_payment_report)), ) + .service( + web::resource("report/authentications").route( + web::post().to(generate_profile_authentication_report), + ), + ) .service( web::resource("api_event_logs") .route(web::get().to(get_profile_api_events)), @@ -1746,6 +1764,7 @@ pub mod routes { )) .await } + #[cfg(feature = "v1")] pub async fn generate_org_payment_report( state: web::Data<AppState>, @@ -1850,6 +1869,161 @@ pub mod routes { .await } + #[cfg(feature = "v1")] + pub async fn generate_merchant_authentication_report( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<ReportRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GenerateAuthenticationReport; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { + let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) + .await + .change_context(AnalyticsError::UnknownError)?; + + let user_email = UserEmail::from_pii_email(user.email) + .change_context(AnalyticsError::UnknownError)? + .get_secret(); + + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + let lambda_req = GenerateReportRequest { + request: payload, + merchant_id: Some(merchant_id.clone()), + auth: AuthInfo::MerchantLevel { + org_id: org_id.clone(), + merchant_ids: vec![merchant_id.clone()], + }, + email: user_email, + }; + + let json_bytes = + serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; + invoke_lambda( + &state.conf.report_download_config.authentication_function, + &state.conf.report_download_config.region, + &json_bytes, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::MerchantReportRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + + #[cfg(feature = "v1")] + pub async fn generate_org_authentication_report( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<ReportRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GenerateAuthenticationReport; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { + let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) + .await + .change_context(AnalyticsError::UnknownError)?; + + let user_email = UserEmail::from_pii_email(user.email) + .change_context(AnalyticsError::UnknownError)? + .get_secret(); + + let org_id = auth.merchant_account.get_org_id(); + let lambda_req = GenerateReportRequest { + request: payload, + merchant_id: None, + auth: AuthInfo::OrgLevel { + org_id: org_id.clone(), + }, + email: user_email, + }; + + let json_bytes = + serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; + invoke_lambda( + &state.conf.report_download_config.authentication_function, + &state.conf.report_download_config.region, + &json_bytes, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::OrganizationReportRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + + #[cfg(feature = "v1")] + pub async fn generate_profile_authentication_report( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<ReportRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GenerateAuthenticationReport; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + |state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move { + let user = UserInterface::find_user_by_id(&*state.global_store, &user_id) + .await + .change_context(AnalyticsError::UnknownError)?; + + let user_email = UserEmail::from_pii_email(user.email) + .change_context(AnalyticsError::UnknownError)? + .get_secret(); + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + let profile_id = auth + .profile_id + .ok_or(report!(UserErrors::JwtProfileIdMissing)) + .change_context(AnalyticsError::AccessForbiddenError)?; + let lambda_req = GenerateReportRequest { + request: payload, + merchant_id: Some(merchant_id.clone()), + auth: AuthInfo::ProfileLevel { + org_id: org_id.clone(), + merchant_id: merchant_id.clone(), + profile_ids: vec![profile_id.clone()], + }, + email: user_email, + }; + + let json_bytes = + serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?; + invoke_lambda( + &state.conf.report_download_config.authentication_function, + &state.conf.report_download_config.region, + &json_bytes, + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::ProfileReportRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + /// # Panics /// /// Panics if `json_payload` array does not contain one `GetApiEventMetricRequest` element.
2025-03-11T17:25:35Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR modifies authentication queries to improve the way we distinguish between authentication flows. Previously, `trans_status` was used for this purpose, but it has now been replaced with `authentication_type`, which more explicitly differentiates between **frictionless flow** and **challenge flow**. Additionally, this PR introduces support for **authentication report generation**, similar to the existing reports for payments, refunds, and disputes. ## Key Changes ### 1. **Updated Authentication Queries** - Replaced `trans_status` with `authentication_type` in authentication queries. - Ensures a clearer distinction between **frictionless flow** and **challenge flow** during authentication. ### 2. **Added Authentication Report Generation** - Introduced report generation for **authentications**, aligning with the existing reporting structure for `payments`, 'refunds` and `disputes`. ### Routes for the reporting service: - **Org level report**: `/analytics/v1/org/report/authentications` - **Merchant level report**: `/analytics/v1/merchant/report/authentications` - **Profile level report**: `/analytics/v1/profile/report/authentications` This PR resolves the data correctness issue raised here: [https://github.com/juspay/hyperswitch-cloud/issues/8727](https://github.com/juspay/hyperswitch-cloud/issues/8727) ### 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). --> - Using `authentication_type` instead of `trans_status` improves accuracy in flow differentiation. - Authentication reporting enables better tracking and analytics for user authentication flows. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Can check the test cases from the `How did you test it?` section from these 2 PRs: - [https://github.com/juspay/hyperswitch/pull/7451](https://github.com/juspay/hyperswitch/pull/7451) - [https://github.com/juspay/hyperswitch/pull/7433](https://github.com/juspay/hyperswitch/pull/7433) **Note**: The Response body should be validated from this PR for all the metrics: [https://github.com/juspay/hyperswitch/pull/7451](https://github.com/juspay/hyperswitch/pull/7451) Curl for Authentication Report: ```bash curl --location 'http://localhost:8080/analytics/v1/org/report/authentications' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: test_admin' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNmNkZTA0NzYtMTFlMi00NGE5LTlkMjUtOTA5M2QzNDQwZjhlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzM1MDQxMjkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczNjYwNDY3OCwib3JnX2lkIjoib3JnX2pwanI5TkFEWlhqSENNYTU5MmF3IiwicHJvZmlsZV9pZCI6InByb19QRHUydVA3aWNuM2lXY0I3V0VVSSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.7_cuWH5XygVrtIDsbh7nusrjGcQ3jbcaPKhIOo3EbM8' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDU1MmY3YzctMmNjZC00ZmU3LThkM2ItY2U1M2ExMTJhZTIwIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxNjk5OTg4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTg3MjgwMiwib3JnX2lkIjoib3JnX2hQamlOektmbmV6NG8wNjdVVlFwIiwicHJvZmlsZV9pZCI6InByb19kWWJpUm9NVkFkNDAwWEh6R3hYTiIsInRlbmFudF9pZCI6InB1YmxpYyJ9.1bsDkYwwk8FtWrDEYdMIsjmH7DqWOVejX2GVseu68ZQ' \ --data-raw '{ "timeRange": { "startTime": "2025-01-08T13:56:15Z", "endTime": "2025-01-09T13:56:15.277Z" }, "emails": [ "[email protected]" ] }' ``` Queries: #### Authentication Attempt Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_status IN ('success', 'failed') AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Authentication Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Authentication Success Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_status = 'success' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Challenge Attempt Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_type = 'challenge' AND authentication_status in ('success', 'failed') AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Challenge Flow Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_type = 'challenge' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Challenge Success Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_status = 'success' AND authentication_type = 'challenge' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Frictionless Flow Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_type = 'frictionless' AND created_at >= '1738402351' AND created_at <= '1740216751' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Frictionless Success Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_type = 'frictionless' AND authentication_status = 'success' AND created_at >= '1738402351' AND created_at <= '1740216751' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Authentication Funnel: (2nd step): ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND trans_status IS NOT NULL AND created_at >= '1738434600' AND created_at <= '1740734520' ) ``` #### Authentication Funnel: (3rd step): ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND trans_status IS NOT NULL AND authentication_status IN ('success', 'failed') AND created_at >= '1738434600' AND created_at <= '1740734520' ) ``` #### Authentication Error Message: ```bash SELECT error_message, sum(sign_flag) AS count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1741712401' AND authentication_status = 'failed' AND error_message IS NOT NULL AND created_at >= '1738434600' AND created_at <= '1740734520' ) GROUP BY error_message HAVING sum(sign_flag) >= '1' ORDER BY count desc ``` Sample Output: You should be able to receive an email with the authentication report to the email specified in the request. Similarly, just replace `org` with `merchant` and `profile` in the URL for the corresponding authentication report at the merchant and profile level. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
5cdfe8325481909a8a1596f967303eff44ffbcec
5cdfe8325481909a8a1596f967303eff44ffbcec
juspay/hyperswitch
juspay__hyperswitch-7467
Bug: [FEATURE] scheme error code and messages in /payments API response ### Feature Description If the payment is declined for a card transaction, the card scheme or issuer can send a raw response explaining why. These are the raw acquirer responses which helps in understanding why a card transaction was declined. Some connectors like Adyen supports this - [reference](https://docs.adyen.com/development-resources/raw-acquirer-responses/#search-modal). HyperSwitch today sends back `error_code` and `error_message` in the payments API response which are connector's error code and messages. Payments API response has to be extended to send back issuer specific error codes and messages. ### Possible Implementation Issuer's error code and messages are received in payments API response or through webhooks. Considering this, below steps are to be followed 1. Ensure issuer's error code and messages are sent back from connector integration to core layer in `ErrorResponse` 2. Ensure this is handled in `IncomingWebhook` flows 3. Ensure this is stored in `payment_attempt` table 4. Ensure this is sent back in payments response ##### Changes required 1. Add below fields in `payment_attempt` table - `issuer_error_code` - `issuer_error_message` 2. Add below fields to payments API response - `issuer_error_code` - `issuer_error_message` This maintains the existing naming convention. Today, HyperSwitch has - - `error_code` and `unified_code` - `error_message` and `unified_message` ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index d93208fb665..081ec577185 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -7633,6 +7633,7 @@ "globepay", "gocardless", "gpayments", + "hipay", "helcim", "inespay", "iatapay", @@ -8720,6 +8721,14 @@ } ], "nullable": true + }, + "network_tokenization": { + "allOf": [ + { + "$ref": "#/components/schemas/NetworkTokenResponse" + } + ], + "nullable": true } } }, @@ -11583,6 +11592,14 @@ "type": "object", "description": "Metadata is useful for storing additional, unstructured information about the merchant account.", "nullable": true + }, + "product_type": { + "allOf": [ + { + "$ref": "#/components/schemas/api_enums.MerchantProductType" + } + ], + "nullable": true } }, "additionalProperties": false @@ -11717,6 +11734,14 @@ }, "recon_status": { "$ref": "#/components/schemas/ReconStatus" + }, + "product_type": { + "allOf": [ + { + "$ref": "#/components/schemas/api_enums.MerchantProductType" + } + ], + "nullable": true } } }, @@ -15350,6 +15375,14 @@ }, "description": "The connector token details if available", "nullable": true + }, + "network_token": { + "allOf": [ + { + "$ref": "#/components/schemas/NetworkTokenResponse" + } + ], + "nullable": true } } }, @@ -15883,7 +15916,8 @@ "active_attempt_payment_connector_id", "billing_connector_payment_details", "payment_method_type", - "payment_method_subtype" + "payment_method_subtype", + "connector" ], "properties": { "total_retry_count": { @@ -15914,6 +15948,9 @@ }, "payment_method_subtype": { "$ref": "#/components/schemas/PaymentMethodType" + }, + "connector": { + "$ref": "#/components/schemas/Connector" } } }, @@ -20300,6 +20337,7 @@ "globalpay", "globepay", "gocardless", + "hipay", "helcim", "iatapay", "inespay", diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index c2fe52010f0..49f2c5ae3dd 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -9732,6 +9732,7 @@ "globepay", "gocardless", "gpayments", + "hipay", "helcim", "inespay", "iatapay", @@ -13921,6 +13922,14 @@ } ], "nullable": true + }, + "product_type": { + "allOf": [ + { + "$ref": "#/components/schemas/api_enums.MerchantProductType" + } + ], + "nullable": true } }, "additionalProperties": false @@ -14154,6 +14163,14 @@ } ], "nullable": true + }, + "product_type": { + "allOf": [ + { + "$ref": "#/components/schemas/api_enums.MerchantProductType" + } + ], + "nullable": true } } }, @@ -19584,6 +19601,16 @@ } ], "nullable": true + }, + "issuer_error_code": { + "type": "string", + "description": "Error code received from the issuer in case of failed payments", + "nullable": true + }, + "issuer_error_message": { + "type": "string", + "description": "Error message received from the issuer in case of failed payments", + "nullable": true } } }, @@ -20852,6 +20879,16 @@ } ], "nullable": true + }, + "issuer_error_code": { + "type": "string", + "description": "Error code received from the issuer in case of failed payments", + "nullable": true + }, + "issuer_error_message": { + "type": "string", + "description": "Error message received from the issuer in case of failed payments", + "nullable": true } } }, @@ -24131,6 +24168,16 @@ } ], "nullable": true + }, + "issuer_error_code": { + "type": "string", + "description": "Error code received from the issuer in case of failed refunds", + "nullable": true + }, + "issuer_error_message": { + "type": "string", + "description": "Error message received from the issuer in case of failed refunds", + "nullable": true } } }, @@ -24786,6 +24833,7 @@ "globalpay", "globepay", "gocardless", + "hipay", "helcim", "iatapay", "inespay", diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 651b0096566..2e21de61083 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -5036,6 +5036,12 @@ pub struct PaymentsResponse { /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, + + /// Error code received from the issuer in case of failed payments + pub issuer_error_code: Option<String>, + + /// Error message received from the issuer in case of failed payments + pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index ad09c333ea7..ece1edb72bd 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -210,6 +210,10 @@ pub struct RefundResponse { /// Charge specific fields for controlling the revert of funds from either platform or connected account #[schema(value_type = Option<SplitRefund>,)] pub split_refunds: Option<common_types::refunds::SplitRefund>, + /// Error code received from the issuer in case of failed refunds + pub issuer_error_code: Option<String>, + /// Error message received from the issuer in case of failed refunds + pub issuer_error_message: Option<String>, } #[cfg(feature = "v1")] diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 7409b722653..8fb4afeb8ed 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -187,6 +187,8 @@ pub struct PaymentAttempt { pub processor_transaction_data: Option<String>, pub card_discovery: Option<storage_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, + pub issuer_error_code: Option<String>, + pub issuer_error_message: Option<String>, } #[cfg(feature = "v1")] @@ -547,6 +549,8 @@ pub enum PaymentAttemptUpdate { connector_transaction_id: Option<String>, payment_method_data: Option<serde_json::Value>, authentication_type: Option<storage_enums::AuthenticationType>, + issuer_error_code: Option<String>, + issuer_error_message: Option<String>, }, CaptureUpdate { amount_to_capture: Option<MinorUnit>, @@ -898,6 +902,8 @@ pub struct PaymentAttemptUpdateInternal { pub processor_transaction_data: Option<String>, pub card_discovery: Option<common_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, + pub issuer_error_code: Option<String>, + pub issuer_error_message: Option<String>, } #[cfg(feature = "v1")] @@ -1082,6 +1088,8 @@ impl PaymentAttemptUpdate { connector_mandate_detail, card_discovery, charges, + issuer_error_code, + issuer_error_message, } = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source); PaymentAttempt { amount: amount.unwrap_or(source.amount), @@ -1141,6 +1149,8 @@ impl PaymentAttemptUpdate { connector_mandate_detail: connector_mandate_detail.or(source.connector_mandate_detail), card_discovery: card_discovery.or(source.card_discovery), charges: charges.or(source.charges), + issuer_error_code: issuer_error_code.or(source.issuer_error_code), + issuer_error_message: issuer_error_message.or(source.issuer_error_message), ..source } } @@ -2194,6 +2204,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::AuthenticationTypeUpdate { authentication_type, @@ -2251,6 +2263,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::ConfirmUpdate { amount, @@ -2340,6 +2354,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail, card_discovery, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::VoidUpdate { status, @@ -2398,6 +2414,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::RejectUpdate { status, @@ -2457,6 +2475,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::BlocklistUpdate { status, @@ -2516,6 +2536,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::ConnectorMandateDetailUpdate { connector_mandate_detail, @@ -2573,6 +2595,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::PaymentMethodDetailsUpdate { payment_method_id, @@ -2630,6 +2654,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::ResponseUpdate { status, @@ -2712,6 +2738,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, card_discovery: None, + issuer_error_code: None, + issuer_error_message: None, } } PaymentAttemptUpdate::ErrorUpdate { @@ -2727,6 +2755,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_transaction_id, payment_method_data, authentication_type, + issuer_error_code, + issuer_error_message, } => { let (connector_transaction_id, processor_transaction_data) = connector_transaction_id @@ -2748,6 +2778,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { payment_method_data, authentication_type, processor_transaction_data, + issuer_error_code, + issuer_error_message, amount: None, net_amount: None, currency: None, @@ -2841,6 +2873,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::UpdateTrackers { payment_token, @@ -2904,6 +2938,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::UnresolvedResponseUpdate { status, @@ -2974,6 +3010,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, } } PaymentAttemptUpdate::PreprocessingUpdate { @@ -3043,6 +3081,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, } } PaymentAttemptUpdate::CaptureUpdate { @@ -3102,6 +3142,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::AmountToCaptureUpdate { status, @@ -3160,6 +3202,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::ConnectorResponse { authentication_data, @@ -3227,6 +3271,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { order_tax_amount: None, connector_mandate_detail: None, card_discovery: None, + issuer_error_code: None, + issuer_error_message: None, } } PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { @@ -3285,6 +3331,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::AuthenticationUpdate { status, @@ -3345,6 +3393,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, PaymentAttemptUpdate::ManualUpdate { status, @@ -3414,6 +3464,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, } } PaymentAttemptUpdate::PostSessionTokensUpdate { @@ -3472,6 +3524,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail: None, card_discovery: None, charges: None, + issuer_error_code: None, + issuer_error_message: None, }, } } diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index f19c3252c60..ee598bebd2f 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -60,6 +60,8 @@ pub struct Refund { pub unified_message: Option<String>, pub processor_refund_data: Option<String>, pub processor_transaction_data: Option<String>, + pub issuer_error_code: Option<String>, + pub issuer_error_message: Option<String>, } #[derive( @@ -140,6 +142,8 @@ pub enum RefundUpdate { processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, + issuer_error_code: Option<String>, + issuer_error_message: Option<String>, }, ManualUpdate { refund_status: Option<storage_enums::RefundStatus>, @@ -165,6 +169,8 @@ pub struct RefundUpdateInternal { processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, + issuer_error_code: Option<String>, + issuer_error_message: Option<String>, } impl RefundUpdateInternal { @@ -213,6 +219,8 @@ impl From<RefundUpdate> for RefundUpdateInternal { modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, }, RefundUpdate::MetadataAndReasonUpdate { metadata, @@ -232,6 +240,8 @@ impl From<RefundUpdate> for RefundUpdateInternal { processor_refund_data: None, unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, }, RefundUpdate::StatusUpdate { connector_refund_id, @@ -253,6 +263,8 @@ impl From<RefundUpdate> for RefundUpdateInternal { modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, }, RefundUpdate::ErrorUpdate { refund_status, @@ -263,6 +275,8 @@ impl From<RefundUpdate> for RefundUpdateInternal { updated_by, connector_refund_id, processor_refund_data, + issuer_error_code, + issuer_error_message, } => Self { refund_status, refund_error_message, @@ -277,6 +291,8 @@ impl From<RefundUpdate> for RefundUpdateInternal { modified_at: common_utils::date_time::now(), unified_code, unified_message, + issuer_error_code, + issuer_error_message, }, RefundUpdate::ManualUpdate { refund_status, @@ -297,6 +313,8 @@ impl From<RefundUpdate> for RefundUpdateInternal { processor_refund_data: None, unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, }, } } @@ -318,6 +336,8 @@ impl RefundUpdate { processor_refund_data, unified_code, unified_message, + issuer_error_code, + issuer_error_message, } = self.into(); Refund { connector_refund_id: connector_refund_id.or(source.connector_refund_id), @@ -333,6 +353,8 @@ impl RefundUpdate { processor_refund_data: processor_refund_data.or(source.processor_refund_data), unified_code: unified_code.or(source.unified_code), unified_message: unified_message.or(source.unified_message), + issuer_error_code: issuer_error_code.or(source.issuer_error_code), + issuer_error_message: issuer_error_message.or(source.issuer_error_message), ..source } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index ae01a54bd43..4e2ba4811b1 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -922,6 +922,9 @@ diesel::table! { processor_transaction_data -> Nullable<Text>, card_discovery -> Nullable<CardDiscovery>, charges -> Nullable<Jsonb>, + #[max_length = 64] + issuer_error_code -> Nullable<Varchar>, + issuer_error_message -> Nullable<Text>, } } @@ -1276,6 +1279,9 @@ diesel::table! { unified_message -> Nullable<Varchar>, processor_refund_data -> Nullable<Text>, processor_transaction_data -> Nullable<Text>, + #[max_length = 64] + issuer_error_code -> Nullable<Varchar>, + issuer_error_message -> Nullable<Text>, } } diff --git a/crates/hyperswitch_connectors/src/connectors/aci.rs b/crates/hyperswitch_connectors/src/connectors/aci.rs index f4fce668ee0..8219105ed2f 100644 --- a/crates/hyperswitch_connectors/src/connectors/aci.rs +++ b/crates/hyperswitch_connectors/src/connectors/aci.rs @@ -121,6 +121,8 @@ impl ConnectorCommon for Aci { }), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/adyen.rs b/crates/hyperswitch_connectors/src/connectors/adyen.rs index 1e57cbbcf65..8e0694336b5 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Adyen { reason: Some(response.message), attempt_status: None, connector_transaction_id: response.psp_reference, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -988,6 +990,8 @@ impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResp status_code: res.status_code, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(response.psp_reference), + issuer_error_code: None, + issuer_error_message: None, }), ..data.clone() }) diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index 13a29f16a0d..793a33e1fc1 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -144,6 +144,8 @@ pub struct AdditionalData { #[cfg(feature = "payouts")] payout_eligible: Option<PayoutEligibility>, funds_availability: Option<String>, + refusal_reason_raw: Option<String>, + refusal_code_raw: Option<String>, } #[serde_with::skip_serializing_none] @@ -444,6 +446,10 @@ pub struct AdyenWebhookResponse { refusal_reason: Option<String>, refusal_reason_code: Option<String>, event_code: WebhookEventCode, + // Raw acquirer refusal code + refusal_code_raw: Option<String>, + // Raw acquirer refusal reason + refusal_reason_raw: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -453,6 +459,7 @@ pub struct RedirectionErrorResponse { refusal_reason: Option<String>, psp_reference: Option<String>, merchant_reference: Option<String>, + additional_data: Option<AdditionalData>, } #[derive(Debug, Clone, Deserialize, Serialize)] @@ -466,6 +473,7 @@ pub struct RedirectionResponse { merchant_reference: Option<String>, store: Option<String>, splits: Option<Vec<AdyenSplitData>>, + additional_data: Option<AdditionalData>, } #[derive(Debug, Clone, Deserialize, Serialize)] @@ -3461,6 +3469,14 @@ pub fn get_adyen_response( status_code, attempt_status: None, connector_transaction_id: Some(response.psp_reference.clone()), + issuer_error_code: response + .additional_data + .as_ref() + .and_then(|data| data.refusal_code_raw.clone()), + issuer_error_message: response + .additional_data + .as_ref() + .and_then(|data| data.refusal_reason_raw.clone()), }) } else { None @@ -3533,6 +3549,8 @@ pub fn get_webhook_response( status_code, attempt_status: None, connector_transaction_id: Some(response.transaction_id.clone()), + issuer_error_code: response.refusal_code_raw.clone(), + issuer_error_message: response.refusal_reason_raw.clone(), }) } else { None @@ -3598,6 +3616,14 @@ pub fn get_redirection_response( status_code, attempt_status: None, connector_transaction_id: response.psp_reference.clone(), + issuer_error_code: response + .additional_data + .as_ref() + .and_then(|data| data.refusal_code_raw.clone()), + issuer_error_message: response + .additional_data + .as_ref() + .and_then(|data| data.refusal_reason_raw.clone()), }) } else { None @@ -3674,6 +3700,8 @@ pub fn get_present_to_shopper_response( status_code, attempt_status: None, connector_transaction_id: response.psp_reference.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -3739,6 +3767,8 @@ pub fn get_qr_code_response( status_code, attempt_status: None, connector_transaction_id: response.psp_reference.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -3796,6 +3826,14 @@ pub fn get_redirection_error_response( status_code, attempt_status: None, connector_transaction_id: response.psp_reference.clone(), + issuer_error_code: response + .additional_data + .as_ref() + .and_then(|data| data.refusal_code_raw.clone()), + issuer_error_message: response + .additional_data + .as_ref() + .and_then(|data| data.refusal_reason_raw.clone()), }); // We don't get connector transaction id for redirections in Adyen. let payments_response_data = PaymentsResponseData::TransactionResponse { @@ -4307,6 +4345,10 @@ pub struct AdyenAdditionalDataWH { #[serde(rename = "recurring.recurringDetailReference")] pub recurring_detail_reference: Option<Secret<String>>, pub network_tx_reference: Option<Secret<String>>, + /// [only for cards] Enable raw acquirer from Adyen dashboard to receive this (https://docs.adyen.com/development-resources/raw-acquirer-responses/#search-modal) + pub refusal_reason_raw: Option<String>, + /// [only for cards] This is only available for Visa and Mastercard + pub refusal_code_raw: Option<String>, } #[derive(Debug, Deserialize)] @@ -4592,6 +4634,8 @@ impl From<AdyenNotificationRequestItemWH> for AdyenWebhookResponse { refusal_reason, refusal_reason_code, event_code: notif.event_code, + refusal_code_raw: notif.additional_data.refusal_code_raw, + refusal_reason_raw: notif.additional_data.refusal_reason_raw, } } } @@ -5307,6 +5351,8 @@ impl ForeignTryFrom<(&Self, AdyenDisputeResponse)> for AcceptDisputeRouterData { )?, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..data.clone() }) @@ -5345,6 +5391,8 @@ impl ForeignTryFrom<(&Self, AdyenDisputeResponse)> for SubmitEvidenceRouterData )?, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..data.clone() }) @@ -5385,6 +5433,8 @@ impl ForeignTryFrom<(&Self, AdyenDisputeResponse)> for DefendDisputeRouterData { )?, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..data.clone() }) diff --git a/crates/hyperswitch_connectors/src/connectors/airwallex.rs b/crates/hyperswitch_connectors/src/connectors/airwallex.rs index f37bef83026..c7482236264 100644 --- a/crates/hyperswitch_connectors/src/connectors/airwallex.rs +++ b/crates/hyperswitch_connectors/src/connectors/airwallex.rs @@ -122,6 +122,8 @@ impl ConnectorCommon for Airwallex { reason: response.source, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/amazonpay.rs b/crates/hyperswitch_connectors/src/connectors/amazonpay.rs index f8959541574..d383bb59b74 100644 --- a/crates/hyperswitch_connectors/src/connectors/amazonpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/amazonpay.rs @@ -145,6 +145,8 @@ impl ConnectorCommon for Amazonpay { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs index 3bd39fd38b5..de72dbe2aeb 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs @@ -1000,6 +1000,8 @@ fn get_error_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) }) .unwrap_or_else(|| ErrorResponse { @@ -1009,6 +1011,8 @@ fn get_error_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, })), Some(authorizedotnet::TransactionResponse::AuthorizedotnetTransactionResponseError(_)) | None => { @@ -1025,6 +1029,8 @@ fn get_error_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs index d7f50aa7405..6481d41748c 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs @@ -551,6 +551,8 @@ impl<F, T> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }); Ok(Self { response, @@ -1219,6 +1221,8 @@ impl<F, T> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(transaction_response.transaction_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) }); let metadata = transaction_response @@ -1310,6 +1314,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, AuthorizedotnetVoidResponse, T, Payment status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(transaction_response.transaction_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) }); let metadata = transaction_response @@ -1458,6 +1464,8 @@ impl<F> TryFrom<RefundsResponseRouterData<F, AuthorizedotnetRefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(transaction_response.transaction_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) }); @@ -1735,6 +1743,8 @@ fn get_err_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } diff --git a/crates/hyperswitch_connectors/src/connectors/bambora.rs b/crates/hyperswitch_connectors/src/connectors/bambora.rs index c4a9edea65c..1bf524392d7 100644 --- a/crates/hyperswitch_connectors/src/connectors/bambora.rs +++ b/crates/hyperswitch_connectors/src/connectors/bambora.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Bambora { reason: Some(response.message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/bamboraapac.rs b/crates/hyperswitch_connectors/src/connectors/bamboraapac.rs index f7453495077..fb9c0799124 100644 --- a/crates/hyperswitch_connectors/src/connectors/bamboraapac.rs +++ b/crates/hyperswitch_connectors/src/connectors/bamboraapac.rs @@ -163,6 +163,8 @@ impl ConnectorCommon for Bamboraapac { reason: response_data.declined_message, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_msg) => { diff --git a/crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs index 5996ba05834..525b0456cec 100644 --- a/crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs @@ -346,6 +346,8 @@ impl<F> reason: Some(declined_message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -501,6 +503,8 @@ impl<F> reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -663,6 +667,8 @@ impl<F> reason: Some(declined_message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -944,6 +950,8 @@ impl<F> reason: Some(declined_message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) diff --git a/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs index 36d12fe3fc5..c1cc1b644a7 100644 --- a/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs +++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs @@ -276,6 +276,8 @@ impl ConnectorCommon for Bankofamerica { reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } transformers::BankOfAmericaErrorResponse::AuthenticationError(response) => { @@ -286,6 +288,8 @@ impl ConnectorCommon for Bankofamerica { reason: Some(response.response.rmsg), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -434,6 +438,8 @@ impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsRespons .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -556,6 +562,8 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -746,6 +754,8 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -867,6 +877,8 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Ba .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs index 9804f6c4e6c..4b40e36a7a6 100644 --- a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs @@ -1445,6 +1445,8 @@ fn map_error_response<F, T>( status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }); match transaction_status { @@ -1486,10 +1488,10 @@ fn get_payment_response( enums::AttemptStatus, u16, ), -) -> Result<PaymentsResponseData, ErrorResponse> { +) -> Result<PaymentsResponseData, Box<ErrorResponse>> { let error_response = get_error_response_if_failure((info_response, status, http_code)); match error_response { - Some(error) => Err(error), + Some(error) => Err(Box::new(error)), None => { let mandate_reference = info_response @@ -1549,7 +1551,8 @@ impl<F> info_response.status.clone(), item.data.request.is_auto_capture()?, )); - let response = get_payment_response((&info_response, status, item.http_code)); + let response = get_payment_response((&info_response, status, item.http_code)) + .map_err(|err| *err); let connector_response = match item.data.payment_method { common_enums::PaymentMethod::Card => info_response .processor_information @@ -1648,7 +1651,8 @@ impl<F> match item.response { BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => { let status = map_boa_attempt_status((info_response.status.clone(), true)); - let response = get_payment_response((&info_response, status, item.http_code)); + let response = get_payment_response((&info_response, status, item.http_code)) + .map_err(|err| *err); Ok(Self { status, response, @@ -1684,7 +1688,8 @@ impl<F> match item.response { BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => { let status = map_boa_attempt_status((info_response.status.clone(), false)); - let response = get_payment_response((&info_response, status, item.http_code)); + let response = get_payment_response((&info_response, status, item.http_code)) + .map_err(|err| *err); Ok(Self { status, response, @@ -2244,6 +2249,8 @@ fn get_error_response( status_code, attempt_status, connector_transaction_id: Some(transaction_id.clone()), + issuer_error_code: None, + issuer_error_message: None, } } @@ -2521,6 +2528,8 @@ fn convert_to_error_response_from_error_info( status_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/billwerk.rs b/crates/hyperswitch_connectors/src/connectors/billwerk.rs index b5ddef00358..34bf83a7bd5 100644 --- a/crates/hyperswitch_connectors/src/connectors/billwerk.rs +++ b/crates/hyperswitch_connectors/src/connectors/billwerk.rs @@ -154,6 +154,8 @@ impl ConnectorCommon for Billwerk { reason: Some(response.error), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs b/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs index 9fe00bac046..e6499306d0f 100644 --- a/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs @@ -279,6 +279,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsRe status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.handle.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None diff --git a/crates/hyperswitch_connectors/src/connectors/bitpay.rs b/crates/hyperswitch_connectors/src/connectors/bitpay.rs index 4de2f422b94..992196c61d3 100644 --- a/crates/hyperswitch_connectors/src/connectors/bitpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/bitpay.rs @@ -153,6 +153,8 @@ impl ConnectorCommon for Bitpay { reason: response.message, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/bluesnap.rs b/crates/hyperswitch_connectors/src/connectors/bluesnap.rs index 29b0611c979..23720360294 100644 --- a/crates/hyperswitch_connectors/src/connectors/bluesnap.rs +++ b/crates/hyperswitch_connectors/src/connectors/bluesnap.rs @@ -168,6 +168,8 @@ impl ConnectorCommon for Bluesnap { reason: Some(reason), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } bluesnap::BluesnapErrors::Auth(error_res) => ErrorResponse { @@ -177,6 +179,8 @@ impl ConnectorCommon for Bluesnap { reason: Some(error_res.error_description), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }, bluesnap::BluesnapErrors::General(error_response) => { let (error_res, attempt_status) = if res.status_code == 403 @@ -199,6 +203,8 @@ impl ConnectorCommon for Bluesnap { reason: Some(error_res), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } }; diff --git a/crates/hyperswitch_connectors/src/connectors/boku.rs b/crates/hyperswitch_connectors/src/connectors/boku.rs index 68195979874..330e7b5ab45 100644 --- a/crates/hyperswitch_connectors/src/connectors/boku.rs +++ b/crates/hyperswitch_connectors/src/connectors/boku.rs @@ -163,6 +163,8 @@ impl ConnectorCommon for Boku { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(_) => get_xml_deserialized(res, event_builder), @@ -705,6 +707,8 @@ fn get_xml_deserialized( reason: Some(response_data), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/braintree.rs b/crates/hyperswitch_connectors/src/connectors/braintree.rs index e965e964293..67c54759152 100644 --- a/crates/hyperswitch_connectors/src/connectors/braintree.rs +++ b/crates/hyperswitch_connectors/src/connectors/braintree.rs @@ -169,6 +169,8 @@ impl ConnectorCommon for Braintree { reason: Some(response.api_error_response.message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Ok(braintree::ErrorResponses::BraintreeErrorResponse(response)) => { @@ -182,6 +184,8 @@ impl ConnectorCommon for Braintree { reason: Some(response.errors), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_msg) => { diff --git a/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs b/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs index 2a5fabb7788..dfde2e0a26d 100644 --- a/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs @@ -447,7 +447,8 @@ impl<F> ) -> Result<Self, Self::Error> { match item.response { BraintreeAuthResponse::ErrorResponse(error_response) => Ok(Self { - response: build_error_response(&error_response.errors, item.http_code), + response: build_error_response(&error_response.errors, item.http_code) + .map_err(|err| *err), ..item.data }), BraintreeAuthResponse::AuthResponse(auth_response) => { @@ -461,6 +462,8 @@ impl<F> attempt_status: None, connector_transaction_id: Some(transaction_data.id), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -513,7 +516,7 @@ impl<F> fn build_error_response<T>( response: &[ErrorDetails], http_code: u16, -) -> Result<T, hyperswitch_domain_models::router_data::ErrorResponse> { +) -> Result<T, Box<hyperswitch_domain_models::router_data::ErrorResponse>> { let error_messages = response .iter() .map(|error| error.message.to_string()) @@ -542,15 +545,19 @@ fn get_error_response<T>( error_msg: Option<String>, error_reason: Option<String>, http_code: u16, -) -> Result<T, hyperswitch_domain_models::router_data::ErrorResponse> { - Err(hyperswitch_domain_models::router_data::ErrorResponse { - code: error_code.unwrap_or_else(|| NO_ERROR_CODE.to_string()), - message: error_msg.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), - reason: error_reason, - status_code: http_code, - attempt_status: None, - connector_transaction_id: None, - }) +) -> Result<T, Box<hyperswitch_domain_models::router_data::ErrorResponse>> { + Err(Box::new( + hyperswitch_domain_models::router_data::ErrorResponse { + code: error_code.unwrap_or_else(|| NO_ERROR_CODE.to_string()), + message: error_msg.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), + reason: error_reason, + status_code: http_code, + attempt_status: None, + connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, + }, + )) } #[derive(Debug, Clone, Deserialize, Serialize, strum::Display)] @@ -624,7 +631,8 @@ impl<F> ) -> Result<Self, Self::Error> { match item.response { BraintreePaymentsResponse::ErrorResponse(error_response) => Ok(Self { - response: build_error_response(&error_response.errors.clone(), item.http_code), + response: build_error_response(&error_response.errors.clone(), item.http_code) + .map_err(|err| *err), ..item.data }), BraintreePaymentsResponse::PaymentsResponse(payment_response) => { @@ -638,6 +646,8 @@ impl<F> attempt_status: None, connector_transaction_id: Some(transaction_data.id), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -708,7 +718,8 @@ impl<F> ) -> Result<Self, Self::Error> { match item.response { BraintreeCompleteChargeResponse::ErrorResponse(error_response) => Ok(Self { - response: build_error_response(&error_response.errors.clone(), item.http_code), + response: build_error_response(&error_response.errors.clone(), item.http_code) + .map_err(|err| *err), ..item.data }), BraintreeCompleteChargeResponse::PaymentsResponse(payment_response) => { @@ -722,6 +733,8 @@ impl<F> attempt_status: None, connector_transaction_id: Some(transaction_data.id), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -773,7 +786,8 @@ impl<F> ) -> Result<Self, Self::Error> { match item.response { BraintreeCompleteAuthResponse::ErrorResponse(error_response) => Ok(Self { - response: build_error_response(&error_response.errors, item.http_code), + response: build_error_response(&error_response.errors, item.http_code) + .map_err(|err| *err), ..item.data }), BraintreeCompleteAuthResponse::AuthResponse(auth_response) => { @@ -787,6 +801,8 @@ impl<F> attempt_status: None, connector_transaction_id: Some(transaction_data.id), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -962,7 +978,7 @@ impl TryFrom<RefundsResponseRouterData<Execute, BraintreeRefundResponse>> Ok(Self { response: match item.response { BraintreeRefundResponse::ErrorResponse(error_response) => { - build_error_response(&error_response.errors, item.http_code) + build_error_response(&error_response.errors, item.http_code).map_err(|err| *err) } BraintreeRefundResponse::SuccessResponse(refund_data) => { let refund_data = refund_data.data.refund_transaction.refund; @@ -975,6 +991,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, BraintreeRefundResponse>> attempt_status: None, connector_transaction_id: Some(refund_data.id), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { @@ -1079,7 +1097,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, BraintreeRSyncResponse>> ) -> Result<Self, Self::Error> { match item.response { BraintreeRSyncResponse::ErrorResponse(error_response) => Ok(Self { - response: build_error_response(&error_response.errors, item.http_code), + response: build_error_response(&error_response.errors, item.http_code) + .map_err(|err| *err), ..item.data }), BraintreeRSyncResponse::RSyncResponse(rsync_response) => { @@ -1241,6 +1260,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, BraintreeTokenResponse, T, PaymentsResp response: match item.response { BraintreeTokenResponse::ErrorResponse(error_response) => { build_error_response(error_response.errors.as_ref(), item.http_code) + .map_err(|err| *err) } BraintreeTokenResponse::TokenResponse(token_response) => { @@ -1332,6 +1352,8 @@ impl TryFrom<PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>> attempt_status: None, connector_transaction_id: Some(transaction_data.id), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -1352,7 +1374,8 @@ impl TryFrom<PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>> }) } BraintreeCaptureResponse::ErrorResponse(error_data) => Ok(Self { - response: build_error_response(&error_data.errors, item.http_code), + response: build_error_response(&error_data.errors, item.http_code) + .map_err(|err| *err), ..item.data }), } @@ -1417,6 +1440,7 @@ impl<F> response: match item.response { BraintreeRevokeMandateResponse::ErrorResponse(error_response) => { build_error_response(error_response.errors.as_ref(), item.http_code) + .map_err(|err| *err) } BraintreeRevokeMandateResponse::RevokeMandateResponse(..) => { Ok(MandateRevokeResponseData { @@ -1515,7 +1539,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, BraintreeCancelResponse, T, PaymentsRes ) -> Result<Self, Self::Error> { match item.response { BraintreeCancelResponse::ErrorResponse(error_response) => Ok(Self { - response: build_error_response(&error_response.errors, item.http_code), + response: build_error_response(&error_response.errors, item.http_code) + .map_err(|err| *err), ..item.data }), BraintreeCancelResponse::CancelResponse(void_response) => { @@ -1529,6 +1554,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, BraintreeCancelResponse, T, PaymentsRes attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -1611,7 +1638,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, BraintreePSyncResponse, T, PaymentsResp ) -> Result<Self, Self::Error> { match item.response { BraintreePSyncResponse::ErrorResponse(error_response) => Ok(Self { - response: build_error_response(&error_response.errors, item.http_code), + response: build_error_response(&error_response.errors, item.http_code) + .map_err(|err| *err), ..item.data }), BraintreePSyncResponse::SuccessResponse(psync_response) => { @@ -1631,6 +1659,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, BraintreePSyncResponse, T, PaymentsResp attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { diff --git a/crates/hyperswitch_connectors/src/connectors/cashtocode.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs index a2a8cf9df65..edd6e54e0ce 100644 --- a/crates/hyperswitch_connectors/src/connectors/cashtocode.rs +++ b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs @@ -146,6 +146,8 @@ impl ConnectorCommon for Cashtocode { reason: Some(response.error_description), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs index 209092c6b6f..684099deb05 100644 --- a/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs @@ -253,6 +253,8 @@ impl<F> reason: Some(error_data.error_description), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ), CashtocodePaymentsResponse::CashtoCodeData(response_data) => { diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee.rs b/crates/hyperswitch_connectors/src/connectors/chargebee.rs index 73eeabe4356..bde9a165b21 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Chargebee { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/checkout.rs b/crates/hyperswitch_connectors/src/connectors/checkout.rs index 61977098476..4d151c12159 100644 --- a/crates/hyperswitch_connectors/src/connectors/checkout.rs +++ b/crates/hyperswitch_connectors/src/connectors/checkout.rs @@ -179,6 +179,8 @@ impl ConnectorCommon for Checkout { .or(response.error_type), attempt_status: None, connector_transaction_id: response.request_id, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs index 4630f00b1d5..d364e327504 100644 --- a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs @@ -705,6 +705,8 @@ impl TryFrom<PaymentsResponseRouterData<PaymentsResponse>> for PaymentsAuthorize reason: item.response.response_summary, attempt_status: None, connector_transaction_id: Some(item.response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -757,6 +759,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<PaymentsResponse>> for PaymentsSyncR reason: item.response.response_summary, attempt_status: None, connector_transaction_id: Some(item.response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None diff --git a/crates/hyperswitch_connectors/src/connectors/coinbase.rs b/crates/hyperswitch_connectors/src/connectors/coinbase.rs index cfdac514847..9e998abebbc 100644 --- a/crates/hyperswitch_connectors/src/connectors/coinbase.rs +++ b/crates/hyperswitch_connectors/src/connectors/coinbase.rs @@ -135,6 +135,8 @@ impl ConnectorCommon for Coinbase { reason: response.error.code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/coingate.rs b/crates/hyperswitch_connectors/src/connectors/coingate.rs index 81bb9116950..e426dcb2384 100644 --- a/crates/hyperswitch_connectors/src/connectors/coingate.rs +++ b/crates/hyperswitch_connectors/src/connectors/coingate.rs @@ -142,6 +142,8 @@ impl ConnectorCommon for Coingate { reason: Some(response.reason), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/cryptopay.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs index 2650d8f1e91..4c24018fcbc 100644 --- a/crates/hyperswitch_connectors/src/connectors/cryptopay.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs @@ -193,6 +193,8 @@ impl ConnectorCommon for Cryptopay { reason: response.error.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs index 98d3dd76cdd..67a67c8878d 100644 --- a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs @@ -175,6 +175,8 @@ impl<F, T> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(payment_response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { let redirection_data = item diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource.rs b/crates/hyperswitch_connectors/src/connectors/cybersource.rs index 812d0391dec..8b5e748906f 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource.rs @@ -239,6 +239,8 @@ impl ConnectorCommon for Cybersource { reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Ok(transformers::CybersourceErrorResponse::AuthenticationError(response)) => { @@ -251,6 +253,8 @@ impl ConnectorCommon for Cybersource { reason: Some(response.response.rmsg), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Ok(transformers::CybersourceErrorResponse::NotAvailableError(response)) => { @@ -275,6 +279,8 @@ impl ConnectorCommon for Cybersource { reason: Some(error_response), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_msg) => { @@ -506,6 +512,8 @@ impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsRespons .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -586,6 +594,8 @@ impl ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevoke status_code: res.status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..data.clone() }) @@ -823,6 +833,8 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1058,6 +1070,8 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1172,6 +1186,8 @@ impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Cyber .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1294,6 +1310,8 @@ impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResp .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1415,6 +1433,8 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cy .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index ea5d9b25f84..2a0ebdc9f79 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -2679,10 +2679,10 @@ fn get_error_response_if_failure( fn get_payment_response( (info_response, status, http_code): (&CybersourcePaymentsResponse, enums::AttemptStatus, u16), -) -> Result<PaymentsResponseData, ErrorResponse> { +) -> Result<PaymentsResponseData, Box<ErrorResponse>> { let error_response = get_error_response_if_failure((info_response, status, http_code)); match error_response { - Some(error) => Err(error), + Some(error) => Err(Box::new(error)), None => { let incremental_authorization_allowed = Some(status == enums::AttemptStatus::Authorized); @@ -2747,7 +2747,8 @@ impl .unwrap_or(CybersourcePaymentStatus::StatusNotReceived), item.data.request.is_auto_capture()?, ); - let response = get_payment_response((&item.response, status, item.http_code)); + let response = + get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); let connector_response = item .response .processor_information @@ -2845,6 +2846,8 @@ impl<F> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }), status: enums::AttemptStatus::AuthenticationFailed, ..item.data @@ -3255,6 +3258,8 @@ impl<F> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(error_response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }); Ok(Self { response, @@ -3292,7 +3297,8 @@ impl<F> .unwrap_or(CybersourcePaymentStatus::StatusNotReceived), item.data.request.is_auto_capture()?, ); - let response = get_payment_response((&item.response, status, item.http_code)); + let response = + get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); let connector_response = item .response .processor_information @@ -3348,7 +3354,8 @@ impl<F> .unwrap_or(CybersourcePaymentStatus::StatusNotReceived), true, ); - let response = get_payment_response((&item.response, status, item.http_code)); + let response = + get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); Ok(Self { status, response, @@ -3383,7 +3390,8 @@ impl<F> .unwrap_or(CybersourcePaymentStatus::StatusNotReceived), false, ); - let response = get_payment_response((&item.response, status, item.http_code)); + let response = + get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); Ok(Self { status, response, @@ -4131,6 +4139,8 @@ pub fn get_error_response( status_code, attempt_status, connector_transaction_id: Some(transaction_id), + issuer_error_code: None, + issuer_error_message: None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/datatrans.rs b/crates/hyperswitch_connectors/src/connectors/datatrans.rs index f06d7be8693..0f82ae28d8f 100644 --- a/crates/hyperswitch_connectors/src/connectors/datatrans.rs +++ b/crates/hyperswitch_connectors/src/connectors/datatrans.rs @@ -153,6 +153,8 @@ impl ConnectorCommon for Datatrans { reason: Some(response), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { let response: datatrans::DatatransErrorResponse = res @@ -168,6 +170,8 @@ impl ConnectorCommon for Datatrans { reason: Some(response.error.message.clone()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs b/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs index 9297f783d3e..8299b0387ae 100644 --- a/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs @@ -560,6 +560,8 @@ impl<F> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), DatatransResponse::TransactionResponse(response) => { Ok(PaymentsResponseData::TransactionResponse { @@ -629,6 +631,8 @@ impl<F> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), DatatransResponse::TransactionResponse(response) => { Ok(PaymentsResponseData::TransactionResponse { @@ -704,6 +708,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, DatatransRefundsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -733,6 +739,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, DatatransSyncResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), DatatransSyncResponse::Response(response) => Ok(RefundsResponseData { connector_refund_id: response.transaction_id.to_string(), @@ -762,6 +770,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<DatatransSyncResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }); Ok(Self { response, @@ -785,6 +795,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<DatatransSyncResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { let mandate_reference = sync_response diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs index b481c3e808d..0972eb63b9e 100644 --- a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs @@ -174,6 +174,8 @@ impl ConnectorCommon for Deutschebank { reason: Some(response.message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -304,6 +306,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: Some(response.message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), deutschebank::DeutschebankError::AccessTokenErrorResponse(response) => { Ok(ErrorResponse { @@ -313,6 +317,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: Some(response.description), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs index bf8a7fc9528..bee5d8662e1 100644 --- a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs @@ -444,7 +444,8 @@ impl reason: Some("METHOD_REQUIRED Flow is not currently supported for deutschebank 3ds payments".to_owned()), status_code: item.http_code, attempt_status: None, - connector_transaction_id: None, + connector_transaction_id: None,issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -514,6 +515,8 @@ fn get_error_response(error_code: String, error_reason: String, status_code: u16 status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs b/crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs index a58a086f5e7..55294d6a588 100644 --- a/crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs +++ b/crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs @@ -161,6 +161,8 @@ impl ConnectorCommon for Digitalvirgo { reason: response.description, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/dlocal.rs b/crates/hyperswitch_connectors/src/connectors/dlocal.rs index 60813a4ea08..965575bbe17 100644 --- a/crates/hyperswitch_connectors/src/connectors/dlocal.rs +++ b/crates/hyperswitch_connectors/src/connectors/dlocal.rs @@ -152,6 +152,8 @@ impl ConnectorCommon for Dlocal { reason: response.param, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs b/crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs index a11c608d69f..861ff22e60f 100644 --- a/crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs @@ -214,6 +214,8 @@ impl<F> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ElavonPaymentsResponse::Success(response) => { if status == enums::AttemptStatus::Failure { @@ -224,6 +226,8 @@ impl<F> attempt_status: None, connector_transaction_id: Some(response.ssl_txn_id.clone()), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -428,6 +432,8 @@ impl TryFrom<PaymentsCaptureResponseRouterData<ElavonPaymentsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ElavonPaymentsResponse::Success(response) => { if status == enums::AttemptStatus::Failure { @@ -438,6 +444,8 @@ impl TryFrom<PaymentsCaptureResponseRouterData<ElavonPaymentsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -478,6 +486,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, ElavonPaymentsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ElavonPaymentsResponse::Success(response) => { if status == enums::RefundStatus::Failure { @@ -488,6 +498,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, ElavonPaymentsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { diff --git a/crates/hyperswitch_connectors/src/connectors/fiserv.rs b/crates/hyperswitch_connectors/src/connectors/fiserv.rs index 50eebb99518..14374a8e18a 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiserv.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiserv.rs @@ -178,6 +178,8 @@ impl ConnectorCommon for Fiserv { status_code: res.status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) }) .unwrap_or(ErrorResponse { @@ -187,6 +189,8 @@ impl ConnectorCommon for Fiserv { status_code: res.status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, })) } } diff --git a/crates/hyperswitch_connectors/src/connectors/fiservemea.rs b/crates/hyperswitch_connectors/src/connectors/fiservemea.rs index b124949c078..d129ed69554 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiservemea.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiservemea.rs @@ -236,6 +236,8 @@ impl ConnectorCommon for Fiservemea { }, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } None => Ok(ErrorResponse { @@ -248,6 +250,8 @@ impl ConnectorCommon for Fiservemea { reason: response.response_type, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), } } diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu.rs b/crates/hyperswitch_connectors/src/connectors/fiuu.rs index 7e9bb8c120c..4069d6af8f9 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu.rs @@ -235,6 +235,8 @@ impl ConnectorCommon for Fiuu { reason: Some(response.error_desc.clone()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index 8b1296a0159..181574b54bb 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -828,6 +828,8 @@ impl<F> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -898,6 +900,8 @@ impl<F> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(data.txn_id), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -944,6 +948,8 @@ impl<F> status_code: item.http_code, attempt_status: None, connector_transaction_id: recurring_response.tran_id.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -1077,6 +1083,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, FiuuRefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -1101,6 +1109,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, FiuuRefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(refund_data.refund_id.to_string()), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -1240,6 +1250,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy reason: response.error_desc, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(txn_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1305,6 +1317,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy reason: response.error_desc.clone(), attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(txn_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1474,6 +1488,8 @@ impl TryFrom<PaymentsCaptureResponseRouterData<PaymentCaptureResponse>> ), attempt_status: None, connector_transaction_id: Some(item.response.tran_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1587,6 +1603,8 @@ impl TryFrom<PaymentsCancelResponseRouterData<FiuuPaymentCancelResponse>> ), attempt_status: None, connector_transaction_id: Some(item.response.tran_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1682,6 +1700,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, FiuuRefundSyncResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), diff --git a/crates/hyperswitch_connectors/src/connectors/forte.rs b/crates/hyperswitch_connectors/src/connectors/forte.rs index 1068922faa7..2356fae53c3 100644 --- a/crates/hyperswitch_connectors/src/connectors/forte.rs +++ b/crates/hyperswitch_connectors/src/connectors/forte.rs @@ -165,6 +165,8 @@ impl ConnectorCommon for Forte { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/getnet.rs b/crates/hyperswitch_connectors/src/connectors/getnet.rs index 557dfbeaca3..0f0ee9e32c3 100644 --- a/crates/hyperswitch_connectors/src/connectors/getnet.rs +++ b/crates/hyperswitch_connectors/src/connectors/getnet.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Getnet { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay.rs b/crates/hyperswitch_connectors/src/connectors/globalpay.rs index 6d233bcfc33..641e9fd5f3d 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay.rs @@ -148,6 +148,8 @@ impl ConnectorCommon for Globalpay { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -376,6 +378,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs index 27ff359a7ad..57cf5d0f287 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs @@ -268,7 +268,7 @@ fn get_payment_response( status: common_enums::AttemptStatus, response: GlobalpayPaymentsResponse, redirection_data: Option<RedirectForm>, -) -> Result<PaymentsResponseData, ErrorResponse> { +) -> Result<PaymentsResponseData, Box<ErrorResponse>> { let mandate_reference = response.payment_method.as_ref().and_then(|pm| { pm.card .as_ref() @@ -281,13 +281,13 @@ fn get_payment_response( }) }); match status { - common_enums::AttemptStatus::Failure => Err(ErrorResponse { + common_enums::AttemptStatus::Failure => Err(Box::new(ErrorResponse { message: response .payment_method .and_then(|pm| pm.message) .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), ..Default::default() - }), + })), _ => Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(response.id), redirection_data: Box::new(redirection_data), @@ -327,7 +327,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, GlobalpayPaymentsResponse, T, PaymentsR let redirection_data = redirect_url.map(|url| RedirectForm::from((url, Method::Get))); Ok(Self { status, - response: get_payment_response(status, item.response, redirection_data), + response: get_payment_response(status, item.response, redirection_data) + .map_err(|err| *err), ..item.data }) } diff --git a/crates/hyperswitch_connectors/src/connectors/globepay.rs b/crates/hyperswitch_connectors/src/connectors/globepay.rs index f11b7b5977f..cca5e99bccd 100644 --- a/crates/hyperswitch_connectors/src/connectors/globepay.rs +++ b/crates/hyperswitch_connectors/src/connectors/globepay.rs @@ -154,6 +154,8 @@ impl ConnectorCommon for Globepay { reason: Some(response.return_msg), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs index a3c027cb5a2..89686f199ad 100644 --- a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs @@ -325,6 +325,8 @@ fn get_error_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/gocardless.rs b/crates/hyperswitch_connectors/src/connectors/gocardless.rs index a953e01dce0..a36ffdd9e34 100644 --- a/crates/hyperswitch_connectors/src/connectors/gocardless.rs +++ b/crates/hyperswitch_connectors/src/connectors/gocardless.rs @@ -158,6 +158,8 @@ impl ConnectorCommon for Gocardless { reason: Some(error_reason.join("; ")), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/helcim.rs b/crates/hyperswitch_connectors/src/connectors/helcim.rs index 79b950063c3..65927bb0f35 100644 --- a/crates/hyperswitch_connectors/src/connectors/helcim.rs +++ b/crates/hyperswitch_connectors/src/connectors/helcim.rs @@ -181,6 +181,8 @@ impl ConnectorCommon for Helcim { reason: Some(error_string), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/hipay.rs b/crates/hyperswitch_connectors/src/connectors/hipay.rs index 1575e361a5b..be1a829efb3 100644 --- a/crates/hyperswitch_connectors/src/connectors/hipay.rs +++ b/crates/hyperswitch_connectors/src/connectors/hipay.rs @@ -244,6 +244,8 @@ impl ConnectorCommon for Hipay { reason: response.description, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs index cefa332bc8f..b121b0698cd 100644 --- a/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs @@ -582,6 +582,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<HipaySyncResponse>> for PaymentsSync attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }); Ok(Self { status: enums::AttemptStatus::Failure, @@ -606,6 +608,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<HipaySyncResponse>> for PaymentsSync status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { diff --git a/crates/hyperswitch_connectors/src/connectors/iatapay.rs b/crates/hyperswitch_connectors/src/connectors/iatapay.rs index f9ab2f3159f..b5ea844fb2e 100644 --- a/crates/hyperswitch_connectors/src/connectors/iatapay.rs +++ b/crates/hyperswitch_connectors/src/connectors/iatapay.rs @@ -155,6 +155,8 @@ impl ConnectorCommon for Iatapay { reason: Some(CONNECTOR_UNAUTHORIZED_ERROR.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } else { let response: iatapay::IatapayErrorResponse = res @@ -171,6 +173,8 @@ impl ConnectorCommon for Iatapay { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } }; Ok(response_error_message) @@ -288,6 +292,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs index e41057fb8e6..0c5c9fc6786 100644 --- a/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs @@ -343,6 +343,8 @@ fn get_iatpay_response( status_code, attempt_status: Some(status), connector_transaction_id: response.iata_payment_id.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -527,6 +529,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRout status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.iata_refund_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { @@ -563,6 +567,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouter status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.iata_refund_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { diff --git a/crates/hyperswitch_connectors/src/connectors/inespay.rs b/crates/hyperswitch_connectors/src/connectors/inespay.rs index 41ae798ade3..e0bd27d47b1 100644 --- a/crates/hyperswitch_connectors/src/connectors/inespay.rs +++ b/crates/hyperswitch_connectors/src/connectors/inespay.rs @@ -151,6 +151,8 @@ impl ConnectorCommon for Inespay { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs index 3922929892e..508e91438ef 100644 --- a/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs @@ -142,6 +142,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsRes attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ), }; @@ -267,6 +269,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, InespayPSyncResponse, T, PaymentsRespon attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -359,6 +363,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, InespayRefundsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -403,6 +409,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, InespayRSyncResponse>> for Refunds attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), }; Ok(Self { diff --git a/crates/hyperswitch_connectors/src/connectors/itaubank.rs b/crates/hyperswitch_connectors/src/connectors/itaubank.rs index 34956ace644..e31f86b0385 100644 --- a/crates/hyperswitch_connectors/src/connectors/itaubank.rs +++ b/crates/hyperswitch_connectors/src/connectors/itaubank.rs @@ -176,6 +176,8 @@ impl ConnectorCommon for Itaubank { reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -296,6 +298,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: response.detail.or(response.user_message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/jpmorgan.rs b/crates/hyperswitch_connectors/src/connectors/jpmorgan.rs index 9d6037877f2..68529f725a8 100644 --- a/crates/hyperswitch_connectors/src/connectors/jpmorgan.rs +++ b/crates/hyperswitch_connectors/src/connectors/jpmorgan.rs @@ -167,6 +167,8 @@ impl ConnectorCommon for Jpmorgan { reason: Some(response_message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs b/crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs index cbe7881c536..6dd867421a9 100644 --- a/crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs +++ b/crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs @@ -187,6 +187,8 @@ impl ConnectorCommon for Juspaythreedsserver { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/klarna.rs b/crates/hyperswitch_connectors/src/connectors/klarna.rs index 86ad19d7dc2..50a830fdba2 100644 --- a/crates/hyperswitch_connectors/src/connectors/klarna.rs +++ b/crates/hyperswitch_connectors/src/connectors/klarna.rs @@ -126,6 +126,8 @@ impl ConnectorCommon for Klarna { reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/mifinity.rs b/crates/hyperswitch_connectors/src/connectors/mifinity.rs index 3b597597e38..eaaa94b4290 100644 --- a/crates/hyperswitch_connectors/src/connectors/mifinity.rs +++ b/crates/hyperswitch_connectors/src/connectors/mifinity.rs @@ -154,6 +154,8 @@ impl ConnectorCommon for Mifinity { reason: Some(CONNECTOR_UNAUTHORIZED_ERROR.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { let response: Result< @@ -189,6 +191,8 @@ impl ConnectorCommon for Mifinity { ), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } diff --git a/crates/hyperswitch_connectors/src/connectors/mollie.rs b/crates/hyperswitch_connectors/src/connectors/mollie.rs index 325c031c33f..b043dbdd8cc 100644 --- a/crates/hyperswitch_connectors/src/connectors/mollie.rs +++ b/crates/hyperswitch_connectors/src/connectors/mollie.rs @@ -135,6 +135,8 @@ impl ConnectorCommon for Mollie { reason: response.field, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/moneris.rs b/crates/hyperswitch_connectors/src/connectors/moneris.rs index c8f542c1bad..3562a2e838e 100644 --- a/crates/hyperswitch_connectors/src/connectors/moneris.rs +++ b/crates/hyperswitch_connectors/src/connectors/moneris.rs @@ -174,6 +174,8 @@ impl ConnectorCommon for Moneris { reason: Some(reason), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -298,6 +300,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: response.error_description, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs index 3e632e048a2..e11ac59e75f 100644 --- a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs @@ -1045,6 +1045,8 @@ pub fn populate_error_reason( status_code: http_code, attempt_status, connector_transaction_id, + issuer_error_code: None, + issuer_error_message: None, } } // REFUND : @@ -1150,6 +1152,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, MultisafepayRefundResponse>> status_code: item.http_code, attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) diff --git a/crates/hyperswitch_connectors/src/connectors/nexinets.rs b/crates/hyperswitch_connectors/src/connectors/nexinets.rs index f93eef65724..69a8543286d 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexinets.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexinets.rs @@ -162,6 +162,8 @@ impl ConnectorCommon for Nexinets { reason: Some(connector_reason), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs index 8a9c804cbf2..264bca6b5a9 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs @@ -203,6 +203,8 @@ impl ConnectorCommon for Nexixpay { reason: concatenated_descriptions, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/nomupay.rs b/crates/hyperswitch_connectors/src/connectors/nomupay.rs index a6a5b0357e1..075b955be49 100644 --- a/crates/hyperswitch_connectors/src/connectors/nomupay.rs +++ b/crates/hyperswitch_connectors/src/connectors/nomupay.rs @@ -285,6 +285,8 @@ impl ConnectorCommon for Nomupay { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), (None, None, Some(nomupay_inner_error), _, _) => { match ( @@ -298,6 +300,8 @@ impl ConnectorCommon for Nomupay { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), (_, Some(validation_errors)) => Ok(ErrorResponse { status_code: res.status_code, @@ -314,6 +318,8 @@ impl ConnectorCommon for Nomupay { ), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), (None, None) => Ok(ErrorResponse { status_code: res.status_code, @@ -322,6 +328,8 @@ impl ConnectorCommon for Nomupay { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), } } @@ -335,6 +343,8 @@ impl ConnectorCommon for Nomupay { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), _ => Ok(ErrorResponse { status_code: res.status_code, @@ -343,6 +353,8 @@ impl ConnectorCommon for Nomupay { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), } } diff --git a/crates/hyperswitch_connectors/src/connectors/noon.rs b/crates/hyperswitch_connectors/src/connectors/noon.rs index c4f2eef275d..3f3de600063 100644 --- a/crates/hyperswitch_connectors/src/connectors/noon.rs +++ b/crates/hyperswitch_connectors/src/connectors/noon.rs @@ -178,6 +178,8 @@ impl ConnectorCommon for Noon { reason: Some(noon_error_response.message), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_message) => { diff --git a/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs b/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs index b2128b990c1..81dc0186356 100644 --- a/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs @@ -596,6 +596,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, NoonPaymentsResponse, T, PaymentsRespon status_code: item.http_code, attempt_status: Some(status), connector_transaction_id: Some(order.id.to_string()), + issuer_error_code: None, + issuer_error_message: None, }), _ => { let connector_response_reference_id = @@ -826,6 +828,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRout reason: Some(response.message.clone()), attempt_status: None, connector_transaction_id: Some(response.result.transaction.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { @@ -892,6 +896,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, RefundSyncResponse>> for RefundsRo reason: Some(response.message.clone()), attempt_status: None, connector_transaction_id: Some(noon_transaction.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet.rs b/crates/hyperswitch_connectors/src/connectors/novalnet.rs index 0a47c8ccfba..a6f2e2fc643 100644 --- a/crates/hyperswitch_connectors/src/connectors/novalnet.rs +++ b/crates/hyperswitch_connectors/src/connectors/novalnet.rs @@ -153,6 +153,8 @@ impl ConnectorCommon for Novalnet { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs index 44f84bf475d..607acb37fb0 100644 --- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs @@ -589,6 +589,8 @@ pub fn get_error_response(result: ResultData, status_code: u16) -> ErrorResponse status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 0bfd3af7e99..cbc4a244d8c 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -1543,17 +1543,14 @@ fn build_error_response<T>( http_code: u16, ) -> Option<Result<T, ErrorResponse>> { match response.status { - NuveiPaymentStatus::Error => Some(get_error_response( - response.err_code, - &response.reason, - http_code, - )), + NuveiPaymentStatus::Error => Some( + get_error_response(response.err_code, &response.reason, http_code).map_err(|err| *err), + ), _ => { - let err = Some(get_error_response( - response.gw_error_code, - &response.gw_error_reason, - http_code, - )); + let err = Some( + get_error_response(response.gw_error_code, &response.gw_error_reason, http_code) + .map_err(|err| *err), + ); match response.transaction_status { Some(NuveiTransactionStatus::Error) | Some(NuveiTransactionStatus::Declined) => err, _ => match response @@ -1709,7 +1706,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, NuveiPaymentsResponse>> item.response .transaction_id .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, - ), + ) + .map_err(|err| *err), ..item.data }) } @@ -1729,7 +1727,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, NuveiPaymentsResponse>> item.response .transaction_id .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, - ), + ) + .map_err(|err| *err), ..item.data }) } @@ -1783,7 +1782,7 @@ fn get_refund_response( response: NuveiPaymentsResponse, http_code: u16, txn_id: String, -) -> Result<RefundsResponseData, ErrorResponse> { +) -> Result<RefundsResponseData, Box<ErrorResponse>> { let refund_status = response .transaction_status .clone() @@ -1809,8 +1808,8 @@ fn get_error_response<T>( error_code: Option<i64>, error_msg: &Option<String>, http_code: u16, -) -> Result<T, ErrorResponse> { - Err(ErrorResponse { +) -> Result<T, Box<ErrorResponse>> { + Err(Box::new(ErrorResponse { code: error_code .map(|c| c.to_string()) .unwrap_or_else(|| NO_ERROR_CODE.to_string()), @@ -1821,7 +1820,9 @@ fn get_error_response<T>( status_code: http_code, attempt_status: None, connector_transaction_id: None, - }) + issuer_error_code: None, + issuer_error_message: None, + })) } #[derive(Debug, Default, Serialize, Deserialize)] diff --git a/crates/hyperswitch_connectors/src/connectors/opayo.rs b/crates/hyperswitch_connectors/src/connectors/opayo.rs index b2aadda37f7..eef0da72a2c 100644 --- a/crates/hyperswitch_connectors/src/connectors/opayo.rs +++ b/crates/hyperswitch_connectors/src/connectors/opayo.rs @@ -139,6 +139,8 @@ impl ConnectorCommon for Opayo { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/opennode.rs b/crates/hyperswitch_connectors/src/connectors/opennode.rs index fefd2f77768..56e30ac3426 100644 --- a/crates/hyperswitch_connectors/src/connectors/opennode.rs +++ b/crates/hyperswitch_connectors/src/connectors/opennode.rs @@ -135,6 +135,8 @@ impl ConnectorCommon for Opennode { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/paybox.rs b/crates/hyperswitch_connectors/src/connectors/paybox.rs index 395fc73808c..0c8577a29d4 100644 --- a/crates/hyperswitch_connectors/src/connectors/paybox.rs +++ b/crates/hyperswitch_connectors/src/connectors/paybox.rs @@ -156,6 +156,8 @@ impl ConnectorCommon for Paybox { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs index ef4e308d968..7da6b6e95ea 100644 --- a/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/paybox/transformers.rs @@ -715,6 +715,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayboxCaptureResponse, T, PaymentsRespo status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transaction_number), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -773,6 +775,8 @@ impl<F> TryFrom<ResponseRouterData<F, PayboxResponse, PaymentsAuthorizeData, Pay status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(response.transaction_number), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -802,6 +806,8 @@ impl<F> TryFrom<ResponseRouterData<F, PayboxResponse, PaymentsAuthorizeData, Pay status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -845,6 +851,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayboxSyncResponse, T, PaymentsResponse status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transaction_number), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -933,6 +941,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, PayboxSyncResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transaction_number), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -964,6 +974,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, TransactionResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transaction_number), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -1033,6 +1045,8 @@ impl<F> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(response.transaction_number), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), diff --git a/crates/hyperswitch_connectors/src/connectors/payeezy.rs b/crates/hyperswitch_connectors/src/connectors/payeezy.rs index 5621b9d1230..b6266d30d21 100644 --- a/crates/hyperswitch_connectors/src/connectors/payeezy.rs +++ b/crates/hyperswitch_connectors/src/connectors/payeezy.rs @@ -149,6 +149,8 @@ impl ConnectorCommon for Payeezy { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/payme.rs b/crates/hyperswitch_connectors/src/connectors/payme.rs index 9c1a94ad3c0..80dd60c172b 100644 --- a/crates/hyperswitch_connectors/src/connectors/payme.rs +++ b/crates/hyperswitch_connectors/src/connectors/payme.rs @@ -149,6 +149,8 @@ impl ConnectorCommon for Payme { )), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_msg) => { diff --git a/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs index 8dd83d1ebd7..180d22b2a75 100644 --- a/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs @@ -232,6 +232,8 @@ fn get_pay_sale_error_response( status_code: http_code, attempt_status: None, connector_transaction_id: Some(pay_sale_response.payme_sale_id.clone()), + issuer_error_code: None, + issuer_error_message: None, } } @@ -314,6 +316,8 @@ fn get_sale_query_error_response( status_code: http_code, attempt_status: None, connector_transaction_id: Some(sale_query_response.sale_payme_id.clone()), + issuer_error_code: None, + issuer_error_message: None, } } @@ -1033,6 +1037,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, PaymeRefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: payme_response.payme_transaction_id.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { @@ -1104,6 +1110,8 @@ impl TryFrom<PaymentsCancelResponseRouterData<PaymeVoidResponse>> for PaymentsCa status_code: item.http_code, attempt_status: None, connector_transaction_id: payme_response.payme_transaction_id.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { // Since we are not receiving payme_sale_id, we are not populating the transaction response @@ -1158,6 +1166,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PaymeQueryTransactionResponse, T, Refun status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(pay_sale_response.payme_transaction_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(RefundsResponseData { diff --git a/crates/hyperswitch_connectors/src/connectors/paypal.rs b/crates/hyperswitch_connectors/src/connectors/paypal.rs index 1859deeaad1..76283fad3a2 100644 --- a/crates/hyperswitch_connectors/src/connectors/paypal.rs +++ b/crates/hyperswitch_connectors/src/connectors/paypal.rs @@ -178,6 +178,8 @@ impl Paypal { reason: error_reason.or(Some(response.message)), attempt_status: None, connector_transaction_id: response.debug_id, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -350,6 +352,8 @@ impl ConnectorCommon for Paypal { reason, attempt_status: None, connector_transaction_id: response.debug_id, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -488,6 +492,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: Some(response.error_description), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1235,6 +1241,8 @@ impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResp .unwrap_or(paypal::AuthenticationStatus::Null), )), status_code: res.status_code, + issuer_error_code: None, + issuer_error_message: None, }), ..data.clone() }), diff --git a/crates/hyperswitch_connectors/src/connectors/paystack.rs b/crates/hyperswitch_connectors/src/connectors/paystack.rs index 6d6ce2ff83a..2f15b1541a5 100644 --- a/crates/hyperswitch_connectors/src/connectors/paystack.rs +++ b/crates/hyperswitch_connectors/src/connectors/paystack.rs @@ -143,6 +143,8 @@ impl ConnectorCommon for Paystack { reason: Some(response.message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs index 2ced7d44d54..4117f689cb6 100644 --- a/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs @@ -144,6 +144,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PaystackPaymentsResponse, T, PaymentsRe attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ) } @@ -251,6 +253,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PaystackPSyncResponse, T, PaymentsRespo attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -348,6 +352,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, PaystackRefundsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -388,6 +394,8 @@ impl TryFrom<RefundsResponseRouterData<RSync, PaystackRefundsResponse>> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) diff --git a/crates/hyperswitch_connectors/src/connectors/payu.rs b/crates/hyperswitch_connectors/src/connectors/payu.rs index cd8c99b6151..6d09c85d917 100644 --- a/crates/hyperswitch_connectors/src/connectors/payu.rs +++ b/crates/hyperswitch_connectors/src/connectors/payu.rs @@ -139,6 +139,8 @@ impl ConnectorCommon for Payu { reason: response.status.code_literal, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -339,6 +341,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/placetopay.rs b/crates/hyperswitch_connectors/src/connectors/placetopay.rs index 6e593c53e16..54d8ffadf34 100644 --- a/crates/hyperswitch_connectors/src/connectors/placetopay.rs +++ b/crates/hyperswitch_connectors/src/connectors/placetopay.rs @@ -134,6 +134,8 @@ impl ConnectorCommon for Placetopay { reason: Some(response.status.message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/powertranz.rs b/crates/hyperswitch_connectors/src/connectors/powertranz.rs index 6d88ac368a0..52db1eb49d2 100644 --- a/crates/hyperswitch_connectors/src/connectors/powertranz.rs +++ b/crates/hyperswitch_connectors/src/connectors/powertranz.rs @@ -147,6 +147,8 @@ impl ConnectorCommon for Powertranz { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs index 03eaa27281c..04df8ee5e54 100644 --- a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs @@ -459,6 +459,8 @@ fn build_error_response(item: &PowertranzBaseResponse, status_code: u16) -> Opti ), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } }) } else if !ISO_SUCCESS_CODES.contains(&item.iso_response_code.as_str()) { @@ -470,6 +472,8 @@ fn build_error_response(item: &PowertranzBaseResponse, status_code: u16) -> Opti reason: Some(item.response_message.clone()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { None diff --git a/crates/hyperswitch_connectors/src/connectors/prophetpay.rs b/crates/hyperswitch_connectors/src/connectors/prophetpay.rs index 245eaf73e75..2518f08c69b 100644 --- a/crates/hyperswitch_connectors/src/connectors/prophetpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/prophetpay.rs @@ -141,6 +141,8 @@ impl ConnectorCommon for Prophetpay { reason: Some(response.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs index cb93caded2c..28f0e4981be 100644 --- a/crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs @@ -425,6 +425,8 @@ impl<F> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -473,6 +475,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, ProphetpaySyncResponse, T, PaymentsResp status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -521,6 +525,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, ProphetpayVoidResponse, T, PaymentsResp status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -629,6 +635,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, ProphetpayRefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -669,6 +677,8 @@ impl<T> TryFrom<RefundsResponseRouterData<T, ProphetpayRefundSyncResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) diff --git a/crates/hyperswitch_connectors/src/connectors/rapyd.rs b/crates/hyperswitch_connectors/src/connectors/rapyd.rs index d5473b260f9..b777aff4d9d 100644 --- a/crates/hyperswitch_connectors/src/connectors/rapyd.rs +++ b/crates/hyperswitch_connectors/src/connectors/rapyd.rs @@ -140,6 +140,8 @@ impl ConnectorCommon for Rapyd { reason: response_data.status.message, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_msg) => { diff --git a/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs b/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs index 7d4517e00bd..236d9e55b5a 100644 --- a/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs @@ -451,6 +451,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, RapydPaymentsResponse, T, PaymentsRespo reason: data.failure_message.to_owned(), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ), _ => { @@ -495,6 +497,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, RapydPaymentsResponse, T, PaymentsRespo reason: item.response.status.message, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ), }; diff --git a/crates/hyperswitch_connectors/src/connectors/razorpay.rs b/crates/hyperswitch_connectors/src/connectors/razorpay.rs index 435ff983c8b..fc7cdeb69ab 100644 --- a/crates/hyperswitch_connectors/src/connectors/razorpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/razorpay.rs @@ -160,6 +160,8 @@ impl ConnectorCommon for Razorpay { ), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } razorpay::ErrorResponse::RazorpayStringError(error_string) => { @@ -170,6 +172,8 @@ impl ConnectorCommon for Razorpay { reason: Some(error_string.clone()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs index af9e67f8dbe..214102e42f3 100644 --- a/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs @@ -817,6 +817,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, RazorpayPaymentsResponse, T, PaymentsRe status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -1273,6 +1275,8 @@ impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.refund.unique_request_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }), }; Ok(Self { diff --git a/crates/hyperswitch_connectors/src/connectors/recurly.rs b/crates/hyperswitch_connectors/src/connectors/recurly.rs index c16810a6ab7..99714dd55f4 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Recurly { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/redsys.rs b/crates/hyperswitch_connectors/src/connectors/redsys.rs index 501182dec07..97f4b4c4b4b 100644 --- a/crates/hyperswitch_connectors/src/connectors/redsys.rs +++ b/crates/hyperswitch_connectors/src/connectors/redsys.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Redsys { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/shift4.rs b/crates/hyperswitch_connectors/src/connectors/shift4.rs index 0bf8c4094b1..b85c2472e58 100644 --- a/crates/hyperswitch_connectors/src/connectors/shift4.rs +++ b/crates/hyperswitch_connectors/src/connectors/shift4.rs @@ -140,6 +140,8 @@ impl ConnectorCommon for Shift4 { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/square.rs b/crates/hyperswitch_connectors/src/connectors/square.rs index 9615d4afdd7..6ac3420219d 100644 --- a/crates/hyperswitch_connectors/src/connectors/square.rs +++ b/crates/hyperswitch_connectors/src/connectors/square.rs @@ -158,6 +158,8 @@ impl ConnectorCommon for Square { reason: Some(reason), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/stax.rs b/crates/hyperswitch_connectors/src/connectors/stax.rs index 27be4d309dc..57b8ce1a282 100644 --- a/crates/hyperswitch_connectors/src/connectors/stax.rs +++ b/crates/hyperswitch_connectors/src/connectors/stax.rs @@ -135,6 +135,8 @@ impl ConnectorCommon for Stax { ), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs index e05fb8b8e33..f3d63ed9ea4 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs @@ -141,6 +141,8 @@ impl ConnectorCommon for Stripebilling { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/taxjar.rs b/crates/hyperswitch_connectors/src/connectors/taxjar.rs index 30b92d9ceb8..4420384e87f 100644 --- a/crates/hyperswitch_connectors/src/connectors/taxjar.rs +++ b/crates/hyperswitch_connectors/src/connectors/taxjar.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Taxjar { reason: Some(response.detail), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/thunes.rs b/crates/hyperswitch_connectors/src/connectors/thunes.rs index b26c0e67fec..3e2e2fec33c 100644 --- a/crates/hyperswitch_connectors/src/connectors/thunes.rs +++ b/crates/hyperswitch_connectors/src/connectors/thunes.rs @@ -144,6 +144,8 @@ impl ConnectorCommon for Thunes { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay.rs b/crates/hyperswitch_connectors/src/connectors/trustpay.rs index b3f2c1f9c3e..fed5c109460 100644 --- a/crates/hyperswitch_connectors/src/connectors/trustpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/trustpay.rs @@ -177,6 +177,8 @@ impl ConnectorCommon for Trustpay { .or(response_data.payment_description), attempt_status: None, connector_transaction_id: response_data.instance_id, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_msg) => { @@ -333,6 +335,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: response.result_info.additional_info, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs index e8da94fae34..0b94b816196 100644 --- a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs @@ -732,6 +732,8 @@ fn handle_cards_response( status_code, attempt_status: None, connector_transaction_id: Some(response.instance_id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -797,6 +799,8 @@ fn handle_bank_redirects_error_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }); let payment_response_data = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, @@ -849,6 +853,8 @@ fn handle_bank_redirects_sync_response( .payment_request_id .clone(), ), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -903,6 +909,8 @@ pub fn handle_webhook_response( status_code, attempt_status: None, connector_transaction_id: payment_information.references.payment_request_id.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1011,6 +1019,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, TrustpayAuthUpdateResponse, T, AccessTo status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }), @@ -1482,6 +1492,8 @@ fn handle_cards_refund_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1515,6 +1527,8 @@ fn handle_webhooks_refund_response( status_code, attempt_status: None, connector_transaction_id: response.references.payment_request_id.clone(), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1543,6 +1557,8 @@ fn handle_bank_redirects_refund_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1579,6 +1595,8 @@ fn handle_bank_redirects_refund_sync_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1602,6 +1620,8 @@ fn handle_bank_redirects_refund_sync_error_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }); //unreachable case as we are sending error as Some() let refund_response_data = RefundsResponseData { diff --git a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs index c2c99c88439..a0e014fd159 100644 --- a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs @@ -238,6 +238,8 @@ fn get_error_response( status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs index ac634d58aea..61e29203979 100644 --- a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs +++ b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs @@ -149,6 +149,8 @@ impl ConnectorCommon for UnifiedAuthenticationService { reason: Some(response.error), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/volt.rs b/crates/hyperswitch_connectors/src/connectors/volt.rs index cec1194f281..ae3699bcc20 100644 --- a/crates/hyperswitch_connectors/src/connectors/volt.rs +++ b/crates/hyperswitch_connectors/src/connectors/volt.rs @@ -171,6 +171,8 @@ impl ConnectorCommon for Volt { reason: Some(reason), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -275,6 +277,8 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> reason: Some(response.message), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs index 3841b7e33b4..33d174d5db8 100644 --- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs @@ -354,6 +354,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponseData, T, PaymentsRe status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(payment_response.id), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -395,6 +397,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponseData, T, PaymentsRe status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(webhook_response.payment.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { diff --git a/crates/hyperswitch_connectors/src/connectors/wellsfargo.rs b/crates/hyperswitch_connectors/src/connectors/wellsfargo.rs index 8566ec70341..e58b9d4439a 100644 --- a/crates/hyperswitch_connectors/src/connectors/wellsfargo.rs +++ b/crates/hyperswitch_connectors/src/connectors/wellsfargo.rs @@ -222,6 +222,8 @@ impl ConnectorCommon for Wellsfargo { reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Ok(transformers::WellsfargoErrorResponse::AuthenticationError(response)) => { @@ -234,6 +236,8 @@ impl ConnectorCommon for Wellsfargo { reason: Some(response.response.rmsg), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Ok(transformers::WellsfargoErrorResponse::NotAvailableError(response)) => { @@ -258,6 +262,8 @@ impl ConnectorCommon for Wellsfargo { reason: Some(error_response), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(error_msg) => { @@ -482,6 +488,8 @@ impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsRespons .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -562,6 +570,8 @@ impl ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevoke status_code: res.status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), ..data.clone() }) @@ -696,6 +706,8 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -890,6 +902,8 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1011,6 +1025,8 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for We .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs b/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs index 10c381fa857..b346d396866 100644 --- a/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs @@ -1708,10 +1708,10 @@ fn get_error_response_if_failure( fn get_payment_response( (info_response, status, http_code): (&WellsfargoPaymentsResponse, enums::AttemptStatus, u16), -) -> Result<PaymentsResponseData, ErrorResponse> { +) -> Result<PaymentsResponseData, Box<ErrorResponse>> { let error_response = get_error_response_if_failure((info_response, status, http_code)); match error_response { - Some(error) => Err(error), + Some(error) => Err(Box::new(error)), None => { let incremental_authorization_allowed = Some(status == enums::AttemptStatus::Authorized); @@ -1776,7 +1776,8 @@ impl .unwrap_or(WellsfargoPaymentStatus::StatusNotReceived), item.data.request.is_auto_capture()?, ); - let response = get_payment_response((&item.response, status, item.http_code)); + let response = + get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); let connector_response = item .response .processor_information @@ -1832,7 +1833,8 @@ impl<F> .unwrap_or(WellsfargoPaymentStatus::StatusNotReceived), true, ); - let response = get_payment_response((&item.response, status, item.http_code)); + let response = + get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); Ok(Self { status, response, @@ -1862,7 +1864,8 @@ impl<F> .unwrap_or(WellsfargoPaymentStatus::StatusNotReceived), false, ); - let response = get_payment_response((&item.response, status, item.http_code)); + let response = + get_payment_response((&item.response, status, item.http_code)).map_err(|err| *err); Ok(Self { status, response, @@ -2376,6 +2379,8 @@ pub fn get_error_response( status_code, attempt_status, connector_transaction_id: Some(transaction_id.clone()), + issuer_error_code: None, + issuer_error_message: None, } } pub fn get_error_reason( diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay.rs b/crates/hyperswitch_connectors/src/connectors/worldpay.rs index 41b2207b175..b261343c5b1 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay.rs @@ -156,6 +156,8 @@ impl ConnectorCommon for Worldpay { reason: response.validation_errors.map(|e| e.to_string()), attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -483,6 +485,8 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Wor reason: response.validation_errors.map(|e| e.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs index 65c884601de..61621b3cc93 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs @@ -786,6 +786,8 @@ impl<F, T> status_code: router_data.http_code, attempt_status: Some(status), connector_transaction_id: optional_correlation_id, + issuer_error_code: None, + issuer_error_message: None, }), (_, Some((code, message))) => Err(ErrorResponse { code, @@ -794,6 +796,8 @@ impl<F, T> status_code: router_data.http_code, attempt_status: Some(status), connector_transaction_id: optional_correlation_id, + issuer_error_code: None, + issuer_error_message: None, }), }; Ok(Self { diff --git a/crates/hyperswitch_connectors/src/connectors/xendit.rs b/crates/hyperswitch_connectors/src/connectors/xendit.rs index f1872e31ae7..cd65b25fda4 100644 --- a/crates/hyperswitch_connectors/src/connectors/xendit.rs +++ b/crates/hyperswitch_connectors/src/connectors/xendit.rs @@ -154,6 +154,8 @@ impl ConnectorCommon for Xendit { status_code: res.status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs b/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs index 47936d43065..30b023e6dc4 100644 --- a/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs @@ -330,6 +330,8 @@ impl<F> attempt_status: None, connector_transaction_id: Some(item.response.id.clone()), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { let charges = match item.data.request.split_payments.as_ref() { @@ -439,6 +441,8 @@ impl<F> attempt_status: None, connector_transaction_id: None, status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { @@ -572,6 +576,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<XenditResponse>> for PaymentsSyncRou attempt_status: None, connector_transaction_id: Some(payment_response.id.clone()), status_code: item.http_code, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { diff --git a/crates/hyperswitch_connectors/src/connectors/zen.rs b/crates/hyperswitch_connectors/src/connectors/zen.rs index 70703b31643..71ca8c7758d 100644 --- a/crates/hyperswitch_connectors/src/connectors/zen.rs +++ b/crates/hyperswitch_connectors/src/connectors/zen.rs @@ -146,6 +146,8 @@ impl ConnectorCommon for Zen { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs index 305c8518c8e..bec1f6be0a4 100644 --- a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs @@ -939,6 +939,8 @@ fn get_zen_response( status_code, attempt_status: Some(status), connector_transaction_id: Some(response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -1085,6 +1087,8 @@ fn get_zen_refund_response( status_code, attempt_status: None, connector_transaction_id: Some(response.id.clone()), + issuer_error_code: None, + issuer_error_message: None, }) } else { None diff --git a/crates/hyperswitch_connectors/src/connectors/zsl.rs b/crates/hyperswitch_connectors/src/connectors/zsl.rs index d7c0152b7a6..7ed2a660822 100644 --- a/crates/hyperswitch_connectors/src/connectors/zsl.rs +++ b/crates/hyperswitch_connectors/src/connectors/zsl.rs @@ -123,6 +123,8 @@ impl ConnectorCommon for Zsl { reason: Some(error_reason), attempt_status: Some(common_enums::AttemptStatus::Failure), connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs index 8a39901e5de..66bd3eda1d1 100644 --- a/crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs @@ -349,6 +349,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, ZslPaymentsResponse, T, PaymentsRespons status_code: item.http_code, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(item.response.mer_ref.clone()), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -365,6 +367,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, ZslPaymentsResponse, T, PaymentsRespons status_code: item.http_code, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(item.response.mer_ref.clone()), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) @@ -443,6 +447,8 @@ impl<F> TryFrom<ResponseRouterData<F, ZslWebhookResponse, PaymentsSyncData, Paym status_code: item.http_code, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(item.response.mer_ref.clone()), + issuer_error_code: None, + issuer_error_message: None, }), ..item.data }) diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index b082962e400..97c27539c67 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -336,6 +336,8 @@ pub(crate) fn handle_json_response_deserialization_failure( reason: Some(response_data), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs index fd8e144f4f2..733c6a73c93 100644 --- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs +++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs @@ -702,6 +702,8 @@ impl From<ApiErrorResponse> for router_data::ErrorResponse { }, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 70926056957..2dc4eec15f1 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -846,6 +846,8 @@ pub struct PaymentAttempt { pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<common_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, + pub issuer_error_code: Option<String>, + pub issuer_error_message: Option<String>, } #[cfg(feature = "v1")] @@ -1239,6 +1241,8 @@ pub enum PaymentAttemptUpdate { connector_transaction_id: Option<String>, payment_method_data: Option<serde_json::Value>, authentication_type: Option<storage_enums::AuthenticationType>, + issuer_error_code: Option<String>, + issuer_error_message: Option<String>, }, CaptureUpdate { amount_to_capture: Option<MinorUnit>, @@ -1542,6 +1546,8 @@ impl PaymentAttemptUpdate { connector_transaction_id, payment_method_data, authentication_type, + issuer_error_code, + issuer_error_message, } => DieselPaymentAttemptUpdate::ErrorUpdate { connector, status, @@ -1555,6 +1561,8 @@ impl PaymentAttemptUpdate { connector_transaction_id, payment_method_data, authentication_type, + issuer_error_code, + issuer_error_message, }, Self::CaptureUpdate { multiple_capture_count, @@ -1824,6 +1832,8 @@ impl behaviour::Conversion for PaymentAttempt { processor_transaction_data, card_discovery: self.card_discovery, charges: self.charges, + issuer_error_code: self.issuer_error_code, + issuer_error_message: self.issuer_error_message, // Below fields are deprecated. Please add any new fields above this line. connector_transaction_data: None, }) @@ -1912,6 +1922,8 @@ impl behaviour::Conversion for PaymentAttempt { capture_before: storage_model.capture_before, card_discovery: storage_model.card_discovery, charges: storage_model.charges, + issuer_error_code: storage_model.issuer_error_code, + issuer_error_message: storage_model.issuer_error_message, }) } .await diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index 7f1278414ea..6618d2fbc80 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -399,6 +399,8 @@ pub struct ErrorResponse { pub status_code: u16, pub attempt_status: Option<common_enums::enums::AttemptStatus>, pub connector_transaction_id: Option<String>, + pub issuer_error_code: Option<String>, + pub issuer_error_message: Option<String>, } impl Default for ErrorResponse { @@ -410,6 +412,8 @@ impl Default for ErrorResponse { status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } } @@ -423,6 +427,8 @@ impl ErrorResponse { status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, } } } @@ -601,6 +607,8 @@ impl status_code: _, attempt_status, connector_transaction_id, + issuer_error_code: _, + issuer_error_message: _, } = error_response.clone(); let attempt_status = attempt_status.unwrap_or(self.status); @@ -798,6 +806,8 @@ impl status_code: _, attempt_status, connector_transaction_id, + issuer_error_code: _, + issuer_error_message: _, } = error_response.clone(); let attempt_status = attempt_status.unwrap_or(self.status); @@ -1013,6 +1023,8 @@ impl status_code: _, attempt_status, connector_transaction_id, + issuer_error_code: _, + issuer_error_message: _, } = error_response.clone(); let attempt_status = attempt_status.unwrap_or(common_enums::AttemptStatus::Failure); @@ -1256,6 +1268,8 @@ impl status_code: _, attempt_status, connector_transaction_id, + issuer_error_code: _, + issuer_error_message: _, } = error_response.clone(); let attempt_status = attempt_status.unwrap_or(self.status); diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs index b70d326feb6..78fdba32c9b 100644 --- a/crates/hyperswitch_interfaces/src/api.rs +++ b/crates/hyperswitch_interfaces/src/api.rs @@ -198,6 +198,8 @@ pub trait ConnectorIntegration<T, Req, Resp>: status_code: res.status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } @@ -286,6 +288,8 @@ pub trait ConnectorCommon { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/hyperswitch_interfaces/src/connector_integration_v2.rs b/crates/hyperswitch_interfaces/src/connector_integration_v2.rs index bc18f5c6639..e0974f5d04d 100644 --- a/crates/hyperswitch_interfaces/src/connector_integration_v2.rs +++ b/crates/hyperswitch_interfaces/src/connector_integration_v2.rs @@ -158,6 +158,8 @@ pub trait ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp>: status_code: res.status_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } diff --git a/crates/router/src/connector/adyenplatform.rs b/crates/router/src/connector/adyenplatform.rs index f95e9cd4d64..5ff89721cb4 100644 --- a/crates/router/src/connector/adyenplatform.rs +++ b/crates/router/src/connector/adyenplatform.rs @@ -99,6 +99,8 @@ impl ConnectorCommon for Adyenplatform { reason: response.detail, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/dummyconnector.rs b/crates/router/src/connector/dummyconnector.rs index 226067cef96..f2058c17f6c 100644 --- a/crates/router/src/connector/dummyconnector.rs +++ b/crates/router/src/connector/dummyconnector.rs @@ -125,6 +125,8 @@ impl<const T: u8> ConnectorCommon for DummyConnector<T> { reason: response.error.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/ebanx.rs b/crates/router/src/connector/ebanx.rs index 01db54c1f67..b38297ed5c7 100644 --- a/crates/router/src/connector/ebanx.rs +++ b/crates/router/src/connector/ebanx.rs @@ -124,6 +124,8 @@ impl ConnectorCommon for Ebanx { reason: response.message, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/gpayments.rs b/crates/router/src/connector/gpayments.rs index 1febbfa7885..2d3b1c37d58 100644 --- a/crates/router/src/connector/gpayments.rs +++ b/crates/router/src/connector/gpayments.rs @@ -123,6 +123,8 @@ impl ConnectorCommon for Gpayments { reason: response.error_detail, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/netcetera.rs b/crates/router/src/connector/netcetera.rs index 459ac93e068..f1fc94bd482 100644 --- a/crates/router/src/connector/netcetera.rs +++ b/crates/router/src/connector/netcetera.rs @@ -111,6 +111,8 @@ impl ConnectorCommon for Netcetera { reason: response.error_details.error_detail, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/netcetera/transformers.rs b/crates/router/src/connector/netcetera/transformers.rs index 886dbc18ad4..1169f29563e 100644 --- a/crates/router/src/connector/netcetera/transformers.rs +++ b/crates/router/src/connector/netcetera/transformers.rs @@ -110,6 +110,8 @@ impl status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } }; @@ -179,6 +181,8 @@ impl status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), }; Ok(Self { diff --git a/crates/router/src/connector/nmi.rs b/crates/router/src/connector/nmi.rs index 73aaec55e57..d0cc0f156d7 100644 --- a/crates/router/src/connector/nmi.rs +++ b/crates/router/src/connector/nmi.rs @@ -103,6 +103,8 @@ impl ConnectorCommon for Nmi { code: response.response_code, attempt_status: None, connector_transaction_id: Some(response.transactionid), + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index d6f1cb1962f..da2649cc444 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -224,6 +224,8 @@ impl status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transactionid), + issuer_error_code: None, + issuer_error_message: None, }), enums::AttemptStatus::Failure, ), @@ -401,6 +403,8 @@ impl ForeignFrom<(NmiCompleteResponse, u16)> for types::ErrorResponse { status_code: http_code, attempt_status: None, connector_transaction_id: Some(response.transactionid), + issuer_error_code: None, + issuer_error_message: None, } } } @@ -905,6 +909,8 @@ impl ForeignFrom<(StandardResponse, u16)> for types::ErrorResponse { status_code: http_code, attempt_status: None, connector_transaction_id: Some(response.transactionid), + issuer_error_code: None, + issuer_error_message: None, } } } diff --git a/crates/router/src/connector/payone.rs b/crates/router/src/connector/payone.rs index 58b179e5799..2e7656f08cf 100644 --- a/crates/router/src/connector/payone.rs +++ b/crates/router/src/connector/payone.rs @@ -210,6 +210,8 @@ impl ConnectorCommon for Payone { ), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), None => Ok(ErrorResponse { status_code: res.status_code, @@ -218,6 +220,8 @@ impl ConnectorCommon for Payone { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), } } diff --git a/crates/router/src/connector/plaid.rs b/crates/router/src/connector/plaid.rs index f24d7bd8d6d..b5428fba4d3 100644 --- a/crates/router/src/connector/plaid.rs +++ b/crates/router/src/connector/plaid.rs @@ -133,6 +133,8 @@ impl ConnectorCommon for Plaid { reason: response.display_message, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/plaid/transformers.rs b/crates/router/src/connector/plaid/transformers.rs index 4e4fb1863ee..ebab8c185af 100644 --- a/crates/router/src/connector/plaid/transformers.rs +++ b/crates/router/src/connector/plaid/transformers.rs @@ -302,6 +302,8 @@ impl<F, T> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.payment_id), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(types::PaymentsResponseData::TransactionResponse { @@ -388,6 +390,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PlaidSyncResponse, T, types::Pay status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.payment_id), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(types::PaymentsResponseData::TransactionResponse { diff --git a/crates/router/src/connector/riskified.rs b/crates/router/src/connector/riskified.rs index 1268e041603..a9585e5d3fd 100644 --- a/crates/router/src/connector/riskified.rs +++ b/crates/router/src/connector/riskified.rs @@ -147,6 +147,8 @@ impl ConnectorCommon for Riskified { message: response.error.message.clone(), reason: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/signifyd.rs b/crates/router/src/connector/signifyd.rs index 21452819c39..857dce8c2e3 100644 --- a/crates/router/src/connector/signifyd.rs +++ b/crates/router/src/connector/signifyd.rs @@ -108,6 +108,8 @@ impl ConnectorCommon for Signifyd { reason: Some(response.errors.to_string()), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index a971bd96741..3971ecc7db8 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -129,6 +129,8 @@ impl ConnectorCommon for Stripe { reason: response.error.message, attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -331,6 +333,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -463,6 +467,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -591,6 +597,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -744,6 +752,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -914,6 +924,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1164,6 +1176,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1291,6 +1305,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1451,6 +1467,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1620,6 +1638,8 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1754,6 +1774,8 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -1908,6 +1930,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -2021,6 +2045,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -2152,6 +2178,8 @@ impl }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 41fb23e7e9e..39d43bd2e06 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -3158,6 +3158,8 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.id), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(types::RefundsResponseData { @@ -3193,6 +3195,8 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.id), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(types::RefundsResponseData { @@ -3549,6 +3553,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, ChargesResponse, T, types::Payme status_code: item.http_code, attempt_status: Some(status), connector_transaction_id: Some(item.response.id), + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(types::PaymentsResponseData::TransactionResponse { @@ -4169,6 +4175,8 @@ impl ForeignTryFrom<(&Option<ErrorDetails>, u16, String)> for types::PaymentsRes status_code: http_code, attempt_status: None, connector_transaction_id: Some(response_id), + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/threedsecureio.rs b/crates/router/src/connector/threedsecureio.rs index aec8f780451..09d232c7471 100644 --- a/crates/router/src/connector/threedsecureio.rs +++ b/crates/router/src/connector/threedsecureio.rs @@ -122,6 +122,8 @@ impl ConnectorCommon for Threedsecureio { reason: response.error_description, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } Err(err) => { diff --git a/crates/router/src/connector/threedsecureio/transformers.rs b/crates/router/src/connector/threedsecureio/transformers.rs index dc1a90f36e7..faf72a2951b 100644 --- a/crates/router/src/connector/threedsecureio/transformers.rs +++ b/crates/router/src/connector/threedsecureio/transformers.rs @@ -124,6 +124,8 @@ impl status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } }; @@ -205,6 +207,8 @@ impl status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } ThreedsecureioErrorResponseWrapper::ErrorString(error) => { @@ -215,6 +219,8 @@ impl status_code: item.http_code, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } }, diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 8a186e0291a..5009eaf4daa 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -2621,6 +2621,8 @@ impl status_code: http_code, attempt_status, connector_transaction_id, + issuer_error_code: None, + issuer_error_message: None, } } } diff --git a/crates/router/src/connector/wellsfargopayout.rs b/crates/router/src/connector/wellsfargopayout.rs index 33111ee7be0..5caf3c689b2 100644 --- a/crates/router/src/connector/wellsfargopayout.rs +++ b/crates/router/src/connector/wellsfargopayout.rs @@ -132,6 +132,8 @@ impl ConnectorCommon for Wellsfargopayout { reason: response.reason, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/connector/wise.rs b/crates/router/src/connector/wise.rs index e4493f5016f..a1d75f18b2a 100644 --- a/crates/router/src/connector/wise.rs +++ b/crates/router/src/connector/wise.rs @@ -113,6 +113,8 @@ impl ConnectorCommon for Wise { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { Ok(types::ErrorResponse { @@ -122,6 +124,8 @@ impl ConnectorCommon for Wise { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } @@ -132,6 +136,8 @@ impl ConnectorCommon for Wise { reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }), } } @@ -338,6 +344,8 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs index 7d56c2ccb91..22f1b593f13 100644 --- a/crates/router/src/core/payments/access_token.rs +++ b/crates/router/src/core/payments/access_token.rs @@ -233,6 +233,8 @@ pub async fn refresh_connector_auth( status_code: 504, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }; Ok(Err(error_response)) diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index bcf0d624ff9..409fccf5e63 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -1436,6 +1436,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( connector_transaction_id: err.connector_transaction_id, payment_method_data: additional_payment_method_data, authentication_type: auth_update, + issuer_error_code: err.issuer_error_code, + issuer_error_message: err.issuer_error_message, }), ) } @@ -1473,6 +1475,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( connector_transaction_id, payment_method_data: None, authentication_type: auth_update, + issuer_error_code: None, + issuer_error_message: None, }), ) } diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 5fdf14dbf5a..24a3ac2ec86 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -537,6 +537,8 @@ where connector_transaction_id: error_response.connector_transaction_id.clone(), payment_method_data: additional_payment_method_data, authentication_type: auth_update, + issuer_error_code: error_response.issuer_error_code.clone(), + issuer_error_message: error_response.issuer_error_message.clone(), }; #[cfg(feature = "v1")] diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index a34c137dbda..7f5f7858a3a 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -2569,6 +2569,8 @@ where capture_before: payment_attempt.capture_before, extended_authorization_applied: payment_attempt.extended_authorization_applied, card_discovery: payment_attempt.card_discovery, + issuer_error_code: payment_attempt.issuer_error_code, + issuer_error_message: payment_attempt.issuer_error_message, }; services::ApplicationResponse::JsonWithHeaders((payments_response, headers)) @@ -2827,7 +2829,9 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay order_tax_amount: None, connector_mandate_id:None, shipping_cost: None, - card_discovery: pa.card_discovery + card_discovery: pa.card_discovery, + issuer_error_code: pa.issuer_error_code, + issuer_error_message: pa.issuer_error_message, } } } diff --git a/crates/router/src/core/payouts/access_token.rs b/crates/router/src/core/payouts/access_token.rs index e5e9b47e4ff..52c31e8fa94 100644 --- a/crates/router/src/core/payouts/access_token.rs +++ b/crates/router/src/core/payouts/access_token.rs @@ -172,6 +172,8 @@ pub async fn refresh_connector_auth( status_code: 504, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }; Ok(Err(error_response)) diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index b850420dfd7..7d663a48a1a 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -238,6 +238,8 @@ pub async fn trigger_refund_to_gateway( processor_refund_data: None, unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, }) } errors::ConnectorError::NotSupported { message, connector } => { @@ -252,6 +254,8 @@ pub async fn trigger_refund_to_gateway( processor_refund_data: None, unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, }) } _ => None, @@ -335,6 +339,8 @@ pub async fn trigger_refund_to_gateway( processor_refund_data: None, unified_code: Some(unified_code), unified_message: Some(unified_message), + issuer_error_code: err.issuer_error_code, + issuer_error_message: err.issuer_error_message, } } Ok(response) => { @@ -366,6 +372,8 @@ pub async fn trigger_refund_to_gateway( processor_refund_data, unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, } } Ok(()) => { @@ -680,6 +688,8 @@ pub async fn sync_refund_with_gateway( processor_refund_data: None, unified_code: None, unified_message: None, + issuer_error_code: error_message.issuer_error_code, + issuer_error_message: error_message.issuer_error_message, } } Ok(response) => match router_data_res.integrity_check.clone() { @@ -710,6 +720,8 @@ pub async fn sync_refund_with_gateway( processor_refund_data, unified_code: None, unified_message: None, + issuer_error_code: None, + issuer_error_message: None, } } Ok(()) => { @@ -1265,6 +1277,8 @@ impl ForeignFrom<storage::Refund> for api::RefundResponse { split_refunds: refund.split_refunds, unified_code: refund.unified_code, unified_message: refund.unified_message, + issuer_error_code: refund.issuer_error_code, + issuer_error_message: refund.issuer_error_message, } } } diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 07bdfa3f77d..1f54eeb5fdc 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -439,6 +439,8 @@ mod storage { unified_message: None, processor_refund_data: new.processor_refund_data.clone(), processor_transaction_data: new.processor_transaction_data.clone(), + issuer_error_code: None, + issuer_error_message: None, // Below fields are deprecated. Please add any new fields above this line. connector_refund_data: None, connector_transaction_data: None, @@ -939,6 +941,8 @@ impl RefundInterface for MockDb { unified_message: None, processor_refund_data: new.processor_refund_data.clone(), processor_transaction_data: new.processor_transaction_data.clone(), + issuer_error_code: None, + issuer_error_message: None, // Below fields are deprecated. Please add any new fields above this line. connector_refund_data: None, connector_transaction_data: None, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index df33e803ab8..e8af5b3b773 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -170,6 +170,8 @@ where reason: None, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } else { None @@ -359,6 +361,8 @@ where status_code: 504, attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }; router_data.response = Err(error_response); router_data.connector_http_status_code = Some(504); diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index f9ef4880924..59ee4e4fb38 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -699,6 +699,8 @@ pub fn handle_json_response_deserialization_failure( reason: Some(response_data), attempt_status: None, connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, }) } } diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index 64c4853d14b..dac001bac9d 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -154,6 +154,8 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow { connector_transaction_id: None, payment_method_data: None, authentication_type: None, + issuer_error_code: None, + issuer_error_message: None, }; payment_data.payment_attempt = db diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index 94dcba750af..0e57540e0ea 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -454,6 +454,8 @@ async fn payments_create_core() { connector_mandate_id: None, shipping_cost: None, card_discovery: None, + issuer_error_code: None, + issuer_error_message: None, }; let expected_response = services::ApplicationResponse::JsonWithHeaders((expected_response, vec![])); @@ -721,6 +723,8 @@ async fn payments_create_core_adyen_no_redirect() { connector_mandate_id: None, shipping_cost: None, card_discovery: None, + issuer_error_code: None, + issuer_error_message: None, }, vec![], )); diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index 66cd41dbc74..19281b45019 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -215,6 +215,8 @@ async fn payments_create_core() { connector_mandate_id: None, shipping_cost: None, card_discovery: None, + issuer_error_code: None, + issuer_error_message: None, }; let expected_response = @@ -491,6 +493,8 @@ async fn payments_create_core_adyen_no_redirect() { connector_mandate_id: None, shipping_cost: None, card_discovery: None, + issuer_error_code: None, + issuer_error_message: None, }, vec![], )); diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 1e4efb2b350..2a637a77e23 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -229,6 +229,8 @@ impl PaymentAttemptInterface for MockDb { capture_before: payment_attempt.capture_before, card_discovery: payment_attempt.card_discovery, charges: None, + issuer_error_code: None, + issuer_error_message: None, }; payment_attempts.push(payment_attempt.clone()); Ok(payment_attempt) diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 076b120c2d0..aaa709e7fa7 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -647,6 +647,8 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { capture_before: payment_attempt.capture_before, card_discovery: payment_attempt.card_discovery, charges: None, + issuer_error_code: None, + issuer_error_message: None, }; let field = format!("pa_{}", created_attempt.attempt_id); @@ -1648,6 +1650,8 @@ impl DataModelExt for PaymentAttempt { processor_transaction_data, card_discovery: self.card_discovery, charges: self.charges, + issuer_error_code: self.issuer_error_code, + issuer_error_message: self.issuer_error_message, // Below fields are deprecated. Please add any new fields above this line. connector_transaction_data: None, } @@ -1731,6 +1735,8 @@ impl DataModelExt for PaymentAttempt { capture_before: storage_model.capture_before, card_discovery: storage_model.card_discovery, charges: storage_model.charges, + issuer_error_code: storage_model.issuer_error_code, + issuer_error_message: storage_model.issuer_error_message, } } } diff --git a/migrations/2025-03-10-060950_add_issuer_code_and_message_in_payment_attempt/down.sql b/migrations/2025-03-10-060950_add_issuer_code_and_message_in_payment_attempt/down.sql new file mode 100644 index 00000000000..06abb6aefbd --- /dev/null +++ b/migrations/2025-03-10-060950_add_issuer_code_and_message_in_payment_attempt/down.sql @@ -0,0 +1,7 @@ +ALTER TABLE payment_attempt +DROP COLUMN IF EXISTS issuer_error_code, +DROP COLUMN IF EXISTS issuer_error_message; + +ALTER TABLE refund +DROP COLUMN IF EXISTS issuer_error_code, +DROP COLUMN IF EXISTS issuer_error_message; \ No newline at end of file diff --git a/migrations/2025-03-10-060950_add_issuer_code_and_message_in_payment_attempt/up.sql b/migrations/2025-03-10-060950_add_issuer_code_and_message_in_payment_attempt/up.sql new file mode 100644 index 00000000000..80c1bc3742e --- /dev/null +++ b/migrations/2025-03-10-060950_add_issuer_code_and_message_in_payment_attempt/up.sql @@ -0,0 +1,7 @@ +ALTER TABLE payment_attempt +ADD COLUMN IF NOT EXISTS issuer_error_code VARCHAR(64) DEFAULT NULL, +ADD COLUMN IF NOT EXISTS issuer_error_message TEXT DEFAULT NULL; + +ALTER TABLE refund +ADD COLUMN IF NOT EXISTS issuer_error_code VARCHAR(64) DEFAULT NULL, +ADD COLUMN IF NOT EXISTS issuer_error_message TEXT DEFAULT NULL; \ No newline at end of file diff --git a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql index b0a3f007eee..cbb2b264d45 100644 --- a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql +++ b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql @@ -89,7 +89,9 @@ ALTER TABLE payment_attempt DROP COLUMN attempt_id, DROP COLUMN authentication_data, DROP COLUMN payment_method_billing_address_id, DROP COLUMN connector_mandate_detail, - DROP COLUMN charge_id; + DROP COLUMN charge_id, + DROP COLUMN issuer_error_code, + DROP COLUMN issuer_error_message; ALTER TABLE payment_methods @@ -113,7 +115,9 @@ DROP TYPE IF EXISTS "PaymentMethodIssuerCode"; -- Run below queries only when V1 is deprecated ALTER TABLE refund DROP COLUMN connector_refund_data, - DROP COLUMN connector_transaction_data; + DROP COLUMN connector_transaction_data, + DROP COLUMN issuer_error_code, + DROP COLUMN issuer_error_message; -- Run below queries only when V1 is deprecated ALTER TABLE captures DROP COLUMN connector_capture_data;
2025-03-16T14:34:27Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR introduces - - Core functionality to read and store raw acquirer responses for `payment` and `refund` operations. - Read raw acquirer response from connector integration - Store in `PaymentAttempt` and `Refund` tables - Updates Adyen connector integration to read raw acquirer response. - Exposes these fields in `/payments` and `/refunds` API response. Described in #7467 ### 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 Helps HS consumer look at issuer specific error responses - these can be enabled on demand from connector's end. ## How did you test it? Not possible to test raw acquirer codes in connector sandbox env. Can only be enabled and tested in production. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
c39ecda79a9b1df1ccb4e469111e0dfb92a3d82c
c39ecda79a9b1df1ccb4e469111e0dfb92a3d82c
juspay/hyperswitch
juspay__hyperswitch-7463
Bug: feat(router):add connector field to PaymentRevenueRecoveryMetadata and update related logic Add connector field in PaymentRevenueRecoveryMetadata and make insert_execute_pcr_task function which creates and inserts a process tracker entry for executing a PCR (Payment Control & Reconciliation) workflow. It generates a unique process_tracker_id, fetches the schedule time for retrying MIT payments, and validates the presence of a payment_attempt_id. If any step fails, it returns an Internal Server Error. After constructing a PcrWorkflowTrackingData object with payment details, it inserts the process tracker entry into the database. If successful, it increments a task metrics counter and returns the inserted entry; otherwise, it returns an error.
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index f9540fd08fc..c55ef483287 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -7473,6 +7473,15 @@ pub struct FeatureMetadata { pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } +#[cfg(feature = "v2")] +impl FeatureMetadata { + pub fn get_retry_count(&self) -> Option<u16> { + self.payment_revenue_recovery_metadata + .as_ref() + .map(|metadata| metadata.total_retry_count) + } +} + /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] @@ -8378,6 +8387,9 @@ pub struct PaymentRevenueRecoveryMetadata { /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, + /// The name of the payment connector through which the payment attempt was made. + #[schema(value_type = Connector, example = "stripe")] + pub connector: common_enums::connector_enums::Connector, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs index 64b9a66afba..294fb33c662 100644 --- a/crates/diesel_models/src/process_tracker.rs +++ b/crates/diesel_models/src/process_tracker.rs @@ -69,12 +69,14 @@ pub struct ProcessTrackerNew { } impl ProcessTrackerNew { + #[allow(clippy::too_many_arguments)] pub fn new<T>( process_tracker_id: impl Into<String>, task: impl Into<String>, runner: ProcessTrackerRunner, tag: impl IntoIterator<Item = impl Into<String>>, tracking_data: T, + retry_count: Option<i32>, schedule_time: PrimitiveDateTime, api_version: ApiVersion, ) -> StorageResult<Self> @@ -87,7 +89,7 @@ impl ProcessTrackerNew { name: Some(task.into()), tag: tag.into_iter().map(Into::into).collect(), runner: Some(runner.to_string()), - retry_count: 0, + retry_count: retry_count.unwrap_or(0), schedule_time: Some(schedule_time), rule: String::new(), tracking_data: tracking_data diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs index b79974c33fd..b1fa2197034 100644 --- a/crates/diesel_models/src/types.rs +++ b/crates/diesel_models/src/types.rs @@ -159,6 +159,8 @@ pub struct PaymentRevenueRecoveryMetadata { pub payment_method_type: common_enums::enums::PaymentMethod, /// PaymentMethod Subtype pub payment_method_subtype: common_enums::enums::PaymentMethodType, + /// The name of the payment connector through which the payment attempt was made. + pub connector: common_enums::connector_enums::Connector, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index f2dddf39b03..bb8cc6b50ca 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -272,6 +272,7 @@ impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentReven ), payment_method_type: from.payment_method_type, payment_method_subtype: from.payment_method_subtype, + connector: from.connector, } } @@ -286,6 +287,7 @@ impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentReven .convert_back(), payment_method_type: self.payment_method_type, payment_method_subtype: self.payment_method_subtype, + connector: self.connector, } } } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 36cc1c5f808..9921cee8a63 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -424,24 +424,6 @@ impl PaymentIntent { .and_then(|metadata| metadata.get_payment_method_type()) } - pub fn set_payment_connector_transmission( - &self, - feature_metadata: Option<FeatureMetadata>, - status: bool, - ) -> Option<Box<FeatureMetadata>> { - feature_metadata.map(|fm| { - let mut updated_metadata = fm; - if let Some(ref mut rrm) = updated_metadata.payment_revenue_recovery_metadata { - rrm.payment_connector_transmission = if status { - common_enums::PaymentConnectorTransmission::ConnectorCallFailed - } else { - common_enums::PaymentConnectorTransmission::ConnectorCallSucceeded - }; - } - Box::new(updated_metadata) - }) - } - pub fn get_connector_customer_id_from_feature_metadata(&self) -> Option<String> { self.feature_metadata .as_ref() @@ -774,11 +756,13 @@ where let payment_intent_feature_metadata = self.payment_intent.get_feature_metadata(); let revenue_recovery = self.payment_intent.get_revenue_recovery_metadata(); - - let payment_revenue_recovery_metadata = - Some(diesel_models::types::PaymentRevenueRecoveryMetadata { + let payment_attempt_connector = self.payment_attempt.connector.clone(); + let payment_revenue_recovery_metadata = match payment_attempt_connector { + Some(connector) => Some(diesel_models::types::PaymentRevenueRecoveryMetadata { // Update retry count by one. - total_retry_count: revenue_recovery.map_or(1, |data| (data.total_retry_count + 1)), + total_retry_count: revenue_recovery + .as_ref() + .map_or(1, |data| (data.total_retry_count + 1)), // Since this is an external system call, marking this payment_connector_transmission to ConnectorCallSucceeded. payment_connector_transmission: common_enums::PaymentConnectorTransmission::ConnectorCallSucceeded, @@ -799,7 +783,14 @@ where }, payment_method_type: self.payment_attempt.payment_method_type, payment_method_subtype: self.payment_attempt.payment_method_subtype, - }); + connector: connector.parse().map_err(|err| { + router_env::logger::error!(?err, "Failed to parse connector string to enum"); + errors::api_error_response::ApiErrorResponse::InternalServerError + })?, + }), + None => Err(errors::api_error_response::ApiErrorResponse::InternalServerError) + .attach_printable("Connector not found in payment attempt")?, + }; Ok(Some(FeatureMetadata { redirect_response: payment_intent_feature_metadata .as_ref() diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs index 8adf5676f97..3e1bc93d91c 100644 --- a/crates/hyperswitch_domain_models/src/revenue_recovery.rs +++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs @@ -61,7 +61,6 @@ pub enum RecoveryAction { /// Invalid event has been received. InvalidAction, } - pub struct RecoveryPaymentIntent { pub payment_id: id_type::GlobalPaymentId, pub status: common_enums::IntentStatus, @@ -75,10 +74,11 @@ pub struct RecoveryPaymentAttempt { } impl RecoveryPaymentAttempt { - pub fn get_attempt_triggered_by(self) -> Option<common_enums::TriggeredBy> { - self.feature_metadata.and_then(|metadata| { + pub fn get_attempt_triggered_by(&self) -> Option<common_enums::TriggeredBy> { + self.feature_metadata.as_ref().and_then(|metadata| { metadata .revenue_recovery + .as_ref() .map(|recovery| recovery.attempt_triggered_by) }) } diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index ae17e69710a..7eb8a8091aa 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -475,12 +475,24 @@ impl ) -> PaymentIntentUpdate { let amount_captured = self.get_captured_amount(payment_data); let status = payment_data.payment_attempt.status.is_terminal_status(); - let updated_feature_metadata = payment_data - .payment_intent - .set_payment_connector_transmission( - payment_data.payment_intent.feature_metadata.clone(), - status, - ); + let updated_feature_metadata = + payment_data + .payment_intent + .feature_metadata + .clone() + .map(|mut feature_metadata| { + if let Some(ref mut payment_revenue_recovery_metadata) = + feature_metadata.payment_revenue_recovery_metadata + { + payment_revenue_recovery_metadata.payment_connector_transmission = + if self.response.is_ok() { + common_enums::PaymentConnectorTransmission::ConnectorCallSucceeded + } else { + common_enums::PaymentConnectorTransmission::ConnectorCallFailed + }; + } + Box::new(feature_metadata) + }); match self.response { Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate { diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index fc87a490b65..bb970a4956e 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -228,6 +228,7 @@ pub async fn add_api_key_expiry_task( API_KEY_EXPIRY_RUNNER, [API_KEY_EXPIRY_TAG], api_key_expiry_tracker, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index b32fe76f5ec..d922a9bc526 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -475,6 +475,8 @@ pub enum RevenueRecoveryError { PaymentIntentFetchFailed, #[error("Failed to fetch payment attempt")] PaymentAttemptFetchFailed, + #[error("Failed to fetch payment attempt")] + PaymentAttemptIdNotFound, #[error("Failed to get revenue recovery invoice webhook")] InvoiceWebhookProcessingFailed, #[error("Failed to get revenue recovery invoice transaction")] @@ -485,4 +487,10 @@ pub enum RevenueRecoveryError { WebhookAuthenticationFailed, #[error("Payment merchant connector account not found using acccount reference id")] PaymentMerchantConnectorAccountNotFound, + #[error("Failed to fetch primitive date_time")] + ScheduleTimeFetchFailed, + #[error("Failed to create process tracker")] + ProcessTrackerCreationError, + #[error("Failed to get the response from process tracker")] + ProcessTrackerResponseError, } diff --git a/crates/router/src/core/passive_churn_recovery.rs b/crates/router/src/core/passive_churn_recovery.rs index 958baeee3f9..3b4ca0d7af6 100644 --- a/crates/router/src/core/passive_churn_recovery.rs +++ b/crates/router/src/core/passive_churn_recovery.rs @@ -142,6 +142,7 @@ async fn insert_psync_pcr_task( runner, tag, psync_workflow_tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index f9a6f9a9eb9..85b66f291d8 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -493,6 +493,7 @@ pub async fn add_payment_method_status_update_task( runner, tag, tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index f65f048885c..93c61793c16 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1401,6 +1401,7 @@ pub async fn add_delete_tokenized_data_task( runner, tag, tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index d072463020a..0ab33dedf68 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -5941,6 +5941,7 @@ pub async fn add_process_sync_task( runner, tag, tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/payments/operations/proxy_payments_intent.rs b/crates/router/src/core/payments/operations/proxy_payments_intent.rs index c029f1439e1..bdf20635dfa 100644 --- a/crates/router/src/core/payments/operations/proxy_payments_intent.rs +++ b/crates/router/src/core/payments/operations/proxy_payments_intent.rs @@ -160,12 +160,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ProxyPaymentsR self.validate_status_for_operation(payment_intent.status)?; - let client_secret = header_payload - .client_secret - .as_ref() - .get_required_value("client_secret header")?; - payment_intent.validate_client_secret(client_secret)?; - let cell_id = state.conf.cell_information.id.clone(); let batch_encrypted_data = domain_types::crypto_operation( diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index f1c8d29ca61..21a560e781b 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -3092,6 +3092,7 @@ pub async fn add_external_account_addition_task( runner, tag, tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 1057f47b4c5..b850420dfd7 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -1605,6 +1605,7 @@ pub async fn add_refund_sync_task( runner, tag, refund_workflow_tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) @@ -1643,6 +1644,7 @@ pub async fn add_refund_execute_task( runner, tag, refund_workflow_tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs index 595171114f7..92c29282b21 100644 --- a/crates/router/src/core/webhooks/outgoing.rs +++ b/crates/router/src/core/webhooks/outgoing.rs @@ -553,6 +553,7 @@ pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker( runner, tag, tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs index f27ee47d6aa..60e06ab0782 100644 --- a/crates/router/src/core/webhooks/recovery_incoming.rs +++ b/crates/router/src/core/webhooks/recovery_incoming.rs @@ -1,18 +1,22 @@ use api_models::{payments as api_payments, webhooks}; -use common_utils::ext_traits::AsyncExt; +use common_utils::{ext_traits::AsyncExt, id_type}; +use diesel_models::{process_tracker as storage, schema::process_tracker::retry_count}; use error_stack::{report, ResultExt}; -use hyperswitch_domain_models::revenue_recovery; +use hyperswitch_domain_models::{errors::api_error_response, revenue_recovery}; use hyperswitch_interfaces::webhooks as interface_webhooks; use router_env::{instrument, tracing}; +use serde_with::rust::unwrap_or_skip; use crate::{ core::{ errors::{self, CustomResult}, payments, }, - routes::{app::ReqState, SessionState}, + db::StorageInterface, + routes::{app::ReqState, metrics, SessionState}, services::{self, connector_integration_interface}, - types::{api, domain}, + types::{api, domain, storage::passive_churn_recovery as storage_churn_recovery}, + workflows::passive_churn_recovery_workflow, }; #[allow(clippy::too_many_arguments)] @@ -122,6 +126,7 @@ pub async fn recovery_incoming_webhook_flow( }; let attempt_triggered_by = payment_attempt + .as_ref() .and_then(revenue_recovery::RecoveryPaymentAttempt::get_attempt_triggered_by); let action = revenue_recovery::RecoveryAction::get_action(event_type, attempt_triggered_by); @@ -129,10 +134,21 @@ pub async fn recovery_incoming_webhook_flow( match action { revenue_recovery::RecoveryAction::CancelInvoice => todo!(), revenue_recovery::RecoveryAction::ScheduleFailedPayment => { - todo!() + Ok(RevenueRecoveryAttempt::insert_execute_pcr_task( + &*state.store, + merchant_account.get_id().to_owned(), + payment_intent, + business_profile.get_id().to_owned(), + payment_attempt.map(|attempt| attempt.attempt_id.clone()), + storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, + ) + .await + .change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed)?) } revenue_recovery::RecoveryAction::SuccessPaymentExternal => { - todo!() + // Need to add recovery stop flow for this scenario + router_env::logger::info!("Payment has been succeeded via external system"); + Ok(webhooks::WebhookResponseTracker::NoEffect) } revenue_recovery::RecoveryAction::PendingPayment => { router_env::logger::info!( @@ -217,8 +233,7 @@ impl RevenueRecoveryInvoice { key_store: &domain::MerchantKeyStore, ) -> CustomResult<revenue_recovery::RecoveryPaymentIntent, errors::RevenueRecoveryError> { let payload = api_payments::PaymentsCreateIntentRequest::from(&self.0); - let global_payment_id = - common_utils::id_type::GlobalPaymentId::generate(&state.conf.cell_information.id); + let global_payment_id = id_type::GlobalPaymentId::generate(&state.conf.cell_information.id); let create_intent_response = Box::pin(payments::payments_intent_core::< hyperswitch_domain_models::router_flow_types::payments::PaymentCreateIntent, @@ -264,7 +279,7 @@ impl RevenueRecoveryAttempt { merchant_account: &domain::MerchantAccount, profile: &domain::Profile, key_store: &domain::MerchantKeyStore, - payment_id: common_utils::id_type::GlobalPaymentId, + payment_id: id_type::GlobalPaymentId, ) -> CustomResult<Option<revenue_recovery::RecoveryPaymentAttempt>, errors::RevenueRecoveryError> { let attempt_response = Box::pin(payments::payments_core::< @@ -332,8 +347,8 @@ impl RevenueRecoveryAttempt { merchant_account: &domain::MerchantAccount, profile: &domain::Profile, key_store: &domain::MerchantKeyStore, - payment_id: common_utils::id_type::GlobalPaymentId, - billing_connector_account_id: &common_utils::id_type::MerchantConnectorAccountId, + payment_id: id_type::GlobalPaymentId, + billing_connector_account_id: &id_type::MerchantConnectorAccountId, payment_connector_account: Option<domain::MerchantConnectorAccount>, ) -> CustomResult<revenue_recovery::RecoveryPaymentAttempt, errors::RevenueRecoveryError> { let request_payload = self @@ -372,7 +387,7 @@ impl RevenueRecoveryAttempt { pub fn create_payment_record_request( &self, - billing_merchant_connector_account_id: &common_utils::id_type::MerchantConnectorAccountId, + billing_merchant_connector_account_id: &id_type::MerchantConnectorAccountId, payment_merchant_connector_account: Option<domain::MerchantConnectorAccount>, ) -> api_payments::PaymentsAttemptRecordRequest { let amount_details = api_payments::PaymentAttemptAmountDetails::from(&self.0); @@ -431,4 +446,80 @@ impl RevenueRecoveryAttempt { )?; Ok(payment_merchant_connector_account) } + + async fn insert_execute_pcr_task( + db: &dyn StorageInterface, + merchant_id: id_type::MerchantId, + payment_intent: revenue_recovery::RecoveryPaymentIntent, + profile_id: id_type::ProfileId, + payment_attempt_id: Option<id_type::GlobalAttemptId>, + runner: storage::ProcessTrackerRunner, + ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { + let task = "EXECUTE_WORKFLOW"; + + let payment_id = payment_intent.payment_id.clone(); + + let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr()); + + let total_retry_count = payment_intent + .feature_metadata + .and_then(|feature_metadata| feature_metadata.get_retry_count()) + .unwrap_or(0); + + let schedule_time = + passive_churn_recovery_workflow::get_schedule_time_to_retry_mit_payments( + db, + &merchant_id, + (total_retry_count + 1).into(), + ) + .await + .map_or_else( + || { + Err( + report!(errors::RevenueRecoveryError::ScheduleTimeFetchFailed) + .attach_printable("Failed to get schedule time for pcr workflow"), + ) + }, + Ok, // Simply returns `time` wrapped in `Ok` + )?; + + let payment_attempt_id = payment_attempt_id + .ok_or(report!( + errors::RevenueRecoveryError::PaymentAttemptIdNotFound + )) + .attach_printable("payment attempt id is required for pcr workflow tracking")?; + + let execute_workflow_tracking_data = storage_churn_recovery::PcrWorkflowTrackingData { + global_payment_id: payment_id.clone(), + merchant_id, + profile_id, + payment_attempt_id, + }; + + let tag = ["PCR"]; + + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + execute_workflow_tracking_data, + Some(total_retry_count.into()), + schedule_time, + common_enums::ApiVersion::V2, + ) + .change_context(errors::RevenueRecoveryError::ProcessTrackerCreationError) + .attach_printable("Failed to construct process tracker entry")?; + + db.insert_process(process_tracker_entry) + .await + .change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError) + .attach_printable("Failed to enter process_tracker_entry in DB")?; + metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "ExecutePCR"))); + + Ok(webhooks::WebhookResponseTracker::Payment { + payment_id, + status: payment_intent.status, + }) + } }
2025-03-08T10:28:12Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Dependency updates - [ ] Refactoring - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Added connector field in `PaymentRevenueRecoveryMetadata` and made `insert_execute_pcr_task` function which creates and inserts a process tracker entry for executing a PCR (Payment Control & Reconciliation) workflow. It generates a unique `process_tracker_id`, fetches the schedule time for retrying MIT payments, and validates the presence of a payment_attempt_id. If any step fails, it returns an Internal Server Error. After constructing a `PcrWorkflowTrackingData` object with payment details, it inserts the process tracker entry into the database. If successful, it increments a task metrics counter and returns the inserted entry; otherwise, it returns an 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). --> ## 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)? --> Testcase 1: create payment connector mca ``` curl --location 'http://localhost:8080/v2/connector-accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: cloth_seller_FFzEuYGiJhp3SfL7AXoZ' \ --header 'x-profile-id: pro_upiJkbJOOOTQny6DRwAF' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "stripe apikey" }, "connector_webhook_details": { "merchant_secret": "" }, "profile_id": "pro_upiJkbJOOOTQny6DRwAF" }' ``` response : ``` { "connector_type": "payment_processor", "connector_name": "stripe", "connector_label": "stripe_business", "id": "mca_LGU3THy8GsYCwNmIY226", "profile_id": "pro_upiJkbJOOOTQny6DRwAF", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "{{*****************}}" }, "payment_methods_enabled": null, "connector_webhook_details": { "merchant_secret": "", "additional_secret": null }, "metadata": null, "disabled": false, "frm_configs": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null, "feature_metadata": null } ``` get the payment connector mca and create billing connector mca Create billing connector mca:- ``` curl --location 'http://localhost:8080/v2/connector-accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: cloth_seller_43a1PFUTB0Ga8Fk4pMfy' \ --header 'x-profile-id: pro_upiJkbJOOOTQny6DRwAF' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "billing_processor", "connector_name": "chargebee", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "{{connector_api_key}}" }, "connector_webhook_details": { "merchant_secret": "chargebee", "additional_secret" : "password" }, "profile_id": "pro_upiJkbJOOOTQny6DRwAF", "feature_metadata" : { "revenue_recovery" : { "max_retry_count" : 27, "billing_connector_retry_threshold" : 16, "billing_account_reference" :{ "mca_LGU3THy8GsYCwNmIY226" : "gw_17BlyOUaPA0eq12MZ" } } } }' ``` response:- ``` { "connector_type": "billing_processor", "connector_name": "chargebee", "connector_label": "chargebee_business", "id": "mca_JbxRy7MozRPhluRWOcWs", "profile_id": "pro_U7N6Id4cHXirpSZfTG08", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "{{*****************}}" }, "payment_methods_enabled": null, "connector_webhook_details": { "merchant_secret": "chargebee", "additional_secret": "password" }, "metadata": null, "disabled": false, "frm_configs": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null, "feature_metadata": { "revenue_recovery": { "max_retry_count": 27, "billing_connector_retry_threshold": 16, "billing_account_reference": { "mca_B16pBbm16yn5Ud2pnOQx": "gw_16BlyOUaPA0eq12MZ" } } } } ``` Send chargebee simulated webhook either from dashboard or postman request : ``` curl --location 'http://localhost:8080/v2/webhooks/cloth_seller_nIw80EwT6E01JF4OC7SQ/pro_U7N6Id4cHXirpSZfTG08/mca_JbxRy7MozRPhluRWOcWs' \ --header 'Content-Type: application/json' \ --header 'Authorization: ••••••' \ --data-raw '{ "id": "ev_169vy3UaPFn4L4mf", "occurred_at": 1737361021, "source": "admin_console", "user": "[email protected]", "object": "event", "api_version": "v2", "content": { "transaction": { "id": "txn_169vy3UaPFmC44me", "customer_id": "Azq8o5UaLqWWvyGd", "subscription_id": "Azq8o5UaLr2WnyHG", "gateway_account_id": "gw_16BlyOUaPA0eq12MZ", "payment_source_id": "pm_169vy3UaPDo0t4hL", "payment_method": "card", "gateway": "stripe", "type": "payment", "date": 1737361019, "exchange_rate": 1, "amount": 5, "id_at_gateway": "ch_3QjGAJSHworDX2hs0B120C0A", "status": "failure", "updated_at": 1737361021, "fraud_reason": "Payment complete.", "resource_version": 1737361021397, "deleted": false, "object": "transaction", "masked_card_number": "************4242", "currency_code": "INR", "base_currency_code": "INR", "amount_unused": 0, "linked_invoices": [ { "invoice_id": "9", "applied_amount": 500000, "applied_at": 1737361021, "invoice_date": 1737361018, "invoice_total": 500000, "invoice_status": "paid" } ], "linked_refunds": [], "initiator_type": "merchant", "three_d_secure": false, "payment_method_details": "{\"card\":{\"first_name\":\"test2\",\"last_name\":\"name2\",\"iin\":\"424242\",\"last4\":\"4242\",\"funding_type\":\"credit\",\"expiry_month\":12,\"expiry_year\":2026,\"billing_addr1\":\"asdf\",\"billing_addr2\":\"asd\",\"billing_city\":\"asdf\",\"billing_state\":\"asdfaf\",\"billing_country\":\"AF\",\"billing_zip\":\"12345\",\"masked_number\":\"************4242\",\"object\":\"card\",\"brand\":\"visa\"}}" }, "invoice": { "id": "invoice_1234", "customer_id": "Azq8o5UaLqWWvyGd", "subscription_id": "Azq8o5UaLr2WnyHG", "recurring": false, "status": "paid", "price_type": "tax_exclusive", "date": 1737361018, "due_date": 1737361018, "net_term_days": 0, "exchange_rate": 1, "total": 5, "amount_paid": 0, "amount_adjusted": 0, "write_off_amount": 0, "credits_applied": 0, "amount_due": 0, "paid_at": 1737361019, "updated_at": 1737361021, "resource_version": 1737361021401, "deleted": false, "object": "invoice", "first_invoice": false, "amount_to_collect": 0, "round_off_amount": 0, "has_advance_charges": false, "currency_code": "INR", "base_currency_code": "INR", "generated_at": 1737361018, "is_gifted": false, "term_finalized": true, "channel": "web", "tax": 0, "line_items": [ { "id": "li_169vy3UaPFmBR4md", "date_from": 1737361004, "date_to": 1737361004, "unit_amount": 500000, "quantity": 1, "amount": 500000, "pricing_model": "flat_fee", "is_taxed": false, "tax_amount": 0, "object": "line_item", "subscription_id": "Azq8o5UaLr2WnyHG", "customer_id": "Azq8o5UaLqWWvyGd", "description": "Implementation Charge", "entity_type": "charge_item_price", "entity_id": "cbdemo_implementation-charge-INR", "tax_exempt_reason": "tax_not_configured", "discount_amount": 0, "item_level_discount_amount": 0 } ], "sub_total": 500000, "linked_payments": [ { "txn_id": "txn_169vy3UaPFmC44me", "applied_amount": 500000, "applied_at": 1737361021, "txn_status": "success", "txn_date": 1737361019, "txn_amount": 500000 } ], "applied_credits": [], "adjustment_credit_notes": [], "issued_credit_notes": [], "linked_orders": [], "dunning_attempts": [], "billing_address": { "first_name": "test1", "last_name": "name", "email": "[email protected]", "company": "johndoe", "phone": "+91 83 17 575848", "line1": "asdf", "line2": "asd", "line3": "ahjkd", "city": "asdf", "state_code": "TG", "state": "Telangana", "country": "IN", "zip": "561432", "validation_status": "not_validated", "object": "billing_address" }, "site_details_at_creation": { "timezone": "Asia/Calcutta" } }, "customer": { "id": "Azq8o5UaLqWWvyGd", "first_name": "john", "last_name": "doe", "email": "[email protected]", "phone": "831 757 5848", "company": "johndoe", "auto_collection": "on", "net_term_days": 0, "allow_direct_debit": false, "created_at": 1737310670, "created_from_ip": "205.254.163.189", "taxability": "taxable", "updated_at": 1737360899, "pii_cleared": "active", "channel": "web", "resource_version": 1737360899990, "deleted": false, "object": "customer", "billing_address": { "first_name": "test1", "last_name": "name", "email": "[email protected]", "company": "johndoe", "phone": "+91 83 17 575848", "line1": "asdf", "line2": "asd", "line3": "ahjkd", "city": "asdf", "state_code": "TG", "state": "Telangana", "country": "IN", "zip": "561432", "validation_status": "not_validated", "object": "billing_address" }, "card_status": "valid", "promotional_credits": 0, "refundable_credits": 0, "excess_payments": 0, "unbilled_charges": 0, "preferred_currency_code": "INR", "mrr": 0, "primary_payment_source_id": "pm_169vy3UaPDo0t4hL", "payment_method": { "object": "payment_method", "type": "card", "reference_id": "cus_RcUo8xTwe0sHP7/card_1QjG2dSHworDX2hs6YIjKdML", "gateway": "stripe", "gateway_account_id": "gw_16BlyOUaPA0eq12MZ", "status": "valid" } }, "subscription": { "id": "Azq8o5UaLr2WnyHG", "billing_period": 1, "billing_period_unit": "month", "customer_id": "Azq8o5UaLqWWvyGd", "status": "active", "current_term_start": 1737310793, "current_term_end": 1739989193, "next_billing_at": 1739989193, "created_at": 1737310793, "started_at": 1737310793, "activated_at": 1737310793, "created_from_ip": "205.254.163.189", "updated_at": 1737310799, "has_scheduled_changes": false, "channel": "web", "resource_version": 1737310799688, "deleted": false, "object": "subscription", "currency_code": "INR", "subscription_items": [ { "item_price_id": "cbdemo_premium-INR-monthly", "item_type": "plan", "quantity": 1, "unit_price": 100000, "amount": 0, "free_quantity": 3, "object": "subscription_item" } ], "shipping_address": { "first_name": "test1", "last_name": "name", "email": "[email protected]", "company": "johndoe", "phone": "+91 83 17 575848", "line1": "asdf", "line2": "asd", "line3": "ahjkd", "city": "asdf", "state_code": "TG", "state": "Telangana", "country": "IN", "zip": "561432", "validation_status": "not_validated", "object": "shipping_address" }, "due_invoices_count": 0, "mrr": 0, "exchange_rate": 1, "base_currency_code": "INR", "has_scheduled_advance_invoices": false } }, "event_type": "payment_failed", "webhook_status": "scheduled", "webhooks": [ { "id": "whv2_6oZfZUaLmtchA5Bl", "webhook_status": "scheduled", "object": "webhook" } ] }' ``` Response:- 200 OK (Postman) This should create Payment intent, payment attempt in our system with right values in DB Payment intent details in DB <img width="1199" alt="Screenshot 2025-03-10 at 14 08 56" src="https://github.com/user-attachments/assets/baa26e0f-dd6b-42bb-90d8-2f0ce6a1aab7" /> Payment attempt details in DB <img width="1138" alt="Screenshot 2025-03-10 at 14 09 53" src="https://github.com/user-attachments/assets/101f79e1-67a8-4aad-b8f7-dd20c565bfcc" /> Test case 2 : change the transaction id in above simulated webhooks and hit the request again, it should create new payment attempt but update the payment intent feature metadata. <img width="1177" alt="Screenshot 2025-03-10 at 14 26 53" src="https://github.com/user-attachments/assets/29873c6d-79b8-43b4-8ec8-fec1bb755d8f" /> Scheduling to failed payments in log(schedule_time: Some(2025-03-10 8:46:43.815835)):- <img width="858" alt="Screenshot 2025-03-10 at 14 52 45" src="https://github.com/user-attachments/assets/c9b7f9b2-41c3-44f7-9249-a34747fe0b28" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
d1f53036c75771d8387a9579a544c1e2b3c17353
d1f53036c75771d8387a9579a544c1e2b3c17353
juspay/hyperswitch
juspay__hyperswitch-7452
Bug: feat(analytics): add new filters, dimensions and metrics for authentication analytics hotfix Add support for filters and dimensions for authentication analytics. Create new metrics: - Authentication Error Message - Authentication Funnel
diff --git a/crates/analytics/src/auth_events.rs b/crates/analytics/src/auth_events.rs index e708c3c8830..3aa23d0793d 100644 --- a/crates/analytics/src/auth_events.rs +++ b/crates/analytics/src/auth_events.rs @@ -1,6 +1,8 @@ pub mod accumulator; mod core; +pub mod filters; pub mod metrics; +pub mod types; pub use accumulator::{AuthEventMetricAccumulator, AuthEventMetricsAccumulator}; -pub use self::core::get_metrics; +pub use self::core::{get_filters, get_metrics}; diff --git a/crates/analytics/src/auth_events/accumulator.rs b/crates/analytics/src/auth_events/accumulator.rs index 446ac6ac8c2..13818d2bd43 100644 --- a/crates/analytics/src/auth_events/accumulator.rs +++ b/crates/analytics/src/auth_events/accumulator.rs @@ -6,12 +6,14 @@ use super::metrics::AuthEventMetricRow; pub struct AuthEventMetricsAccumulator { pub authentication_count: CountAccumulator, pub authentication_attempt_count: CountAccumulator, + pub authentication_error_message: AuthenticationErrorMessageAccumulator, pub authentication_success_count: CountAccumulator, pub challenge_flow_count: CountAccumulator, pub challenge_attempt_count: CountAccumulator, pub challenge_success_count: CountAccumulator, pub frictionless_flow_count: CountAccumulator, pub frictionless_success_count: CountAccumulator, + pub authentication_funnel: CountAccumulator, } #[derive(Debug, Default)] @@ -20,6 +22,11 @@ pub struct CountAccumulator { pub count: Option<i64>, } +#[derive(Debug, Default)] +pub struct AuthenticationErrorMessageAccumulator { + pub count: Option<i64>, +} + pub trait AuthEventMetricAccumulator { type MetricOutput; @@ -44,6 +51,22 @@ impl AuthEventMetricAccumulator for CountAccumulator { } } +impl AuthEventMetricAccumulator for AuthenticationErrorMessageAccumulator { + type MetricOutput = Option<u64>; + #[inline] + fn add_metrics_bucket(&mut self, metrics: &AuthEventMetricRow) { + 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 AuthEventMetricsAccumulator { pub fn collect(self) -> AuthEventMetricsBucketValue { AuthEventMetricsBucketValue { @@ -55,6 +78,8 @@ impl AuthEventMetricsAccumulator { challenge_success_count: self.challenge_success_count.collect(), frictionless_flow_count: self.frictionless_flow_count.collect(), frictionless_success_count: self.frictionless_success_count.collect(), + error_message_count: self.authentication_error_message.collect(), + authentication_funnel: self.authentication_funnel.collect(), } } } diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs index 75bdf4de149..a2640be6ead 100644 --- a/crates/analytics/src/auth_events/core.rs +++ b/crates/analytics/src/auth_events/core.rs @@ -1,13 +1,20 @@ use std::collections::HashMap; use api_models::analytics::{ - auth_events::{AuthEventMetrics, AuthEventMetricsBucketIdentifier, MetricsBucketResponse}, - AnalyticsMetadata, GetAuthEventMetricRequest, MetricsResponse, + auth_events::{ + AuthEventDimensions, AuthEventMetrics, AuthEventMetricsBucketIdentifier, + MetricsBucketResponse, + }, + AuthEventFilterValue, AuthEventFiltersResponse, AuthEventMetricsResponse, + AuthEventsAnalyticsMetadata, GetAuthEventFilterRequest, GetAuthEventMetricRequest, }; -use error_stack::ResultExt; +use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; -use super::AuthEventMetricsAccumulator; +use super::{ + filters::{get_auth_events_filter_for_dimension, AuthEventFilterRow}, + AuthEventMetricsAccumulator, +}; use crate::{ auth_events::AuthEventMetricAccumulator, errors::{AnalyticsError, AnalyticsResult}, @@ -19,7 +26,7 @@ pub async fn get_metrics( pool: &AnalyticsProvider, merchant_id: &common_utils::id_type::MerchantId, req: GetAuthEventMetricRequest, -) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> { +) -> AnalyticsResult<AuthEventMetricsResponse<MetricsBucketResponse>> { let mut metrics_accumulator: HashMap< AuthEventMetricsBucketIdentifier, AuthEventMetricsAccumulator, @@ -34,7 +41,9 @@ pub async fn get_metrics( let data = pool .get_auth_event_metrics( &metric_type, + &req.group_by_names.clone(), &merchant_id_scoped, + &req.filters, req.time_series.map(|t| t.granularity), &req.time_range, ) @@ -77,22 +86,94 @@ pub async fn get_metrics( AuthEventMetrics::FrictionlessSuccessCount => metrics_builder .frictionless_success_count .add_metrics_bucket(&value), + AuthEventMetrics::AuthenticationErrorMessage => metrics_builder + .authentication_error_message + .add_metrics_bucket(&value), + AuthEventMetrics::AuthenticationFunnel => metrics_builder + .authentication_funnel + .add_metrics_bucket(&value), } } } + let mut total_error_message_count = 0; let query_data: Vec<MetricsBucketResponse> = metrics_accumulator .into_iter() - .map(|(id, val)| MetricsBucketResponse { - values: val.collect(), - dimensions: id, + .map(|(id, val)| { + let collected_values = val.collect(); + if let Some(count) = collected_values.error_message_count { + total_error_message_count += count; + } + MetricsBucketResponse { + values: collected_values, + dimensions: id, + } }) .collect(); - - Ok(MetricsResponse { + Ok(AuthEventMetricsResponse { query_data, - meta_data: [AnalyticsMetadata { - current_time_range: req.time_range, + meta_data: [AuthEventsAnalyticsMetadata { + total_error_message_count: Some(total_error_message_count), }], }) } + +pub async fn get_filters( + pool: &AnalyticsProvider, + req: GetAuthEventFilterRequest, + merchant_id: &common_utils::id_type::MerchantId, +) -> AnalyticsResult<AuthEventFiltersResponse> { + let mut res = AuthEventFiltersResponse::default(); + for dim in req.group_by_names { + let values = match pool { + AnalyticsProvider::Sqlx(_pool) => { + Err(report!(AnalyticsError::UnknownError)) + } + AnalyticsProvider::Clickhouse(pool) => { + get_auth_events_filter_for_dimension(dim, merchant_id, &req.time_range, pool) + .await + .map_err(|e| e.change_context(AnalyticsError::UnknownError)) + } + AnalyticsProvider::CombinedCkh(sqlx_pool, ckh_pool) | AnalyticsProvider::CombinedSqlx(sqlx_pool, ckh_pool) => { + let ckh_result = get_auth_events_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + ckh_pool, + ) + .await + .map_err(|e| e.change_context(AnalyticsError::UnknownError)); + let sqlx_result = get_auth_events_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + sqlx_pool, + ) + .await + .map_err(|e| e.change_context(AnalyticsError::UnknownError)); + match (&sqlx_result, &ckh_result) { + (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { + router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres refunds analytics filters") + }, + _ => {} + }; + ckh_result + } + } + .change_context(AnalyticsError::UnknownError)? + .into_iter() + .filter_map(|fil: AuthEventFilterRow| match dim { + AuthEventDimensions::AuthenticationStatus => fil.authentication_status.map(|i| i.as_ref().to_string()), + AuthEventDimensions::TransactionStatus => fil.trans_status.map(|i| i.as_ref().to_string()), + AuthEventDimensions::ErrorMessage => fil.error_message, + AuthEventDimensions::AuthenticationConnector => fil.authentication_connector.map(|i| i.as_ref().to_string()), + AuthEventDimensions::MessageVersion => fil.message_version, + }) + .collect::<Vec<String>>(); + res.query_data.push(AuthEventFilterValue { + dimension: dim, + values, + }) + } + Ok(res) +} diff --git a/crates/analytics/src/auth_events/filters.rs b/crates/analytics/src/auth_events/filters.rs new file mode 100644 index 00000000000..da8e0b7cfa3 --- /dev/null +++ b/crates/analytics/src/auth_events/filters.rs @@ -0,0 +1,60 @@ +use api_models::analytics::{auth_events::AuthEventDimensions, Granularity, TimeRange}; +use common_utils::errors::ReportSwitchExt; +use diesel_models::enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; +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 AuthEventFilterAnalytics: LoadRow<AuthEventFilterRow> {} + +pub async fn get_auth_events_filter_for_dimension<T>( + dimension: AuthEventDimensions, + merchant_id: &common_utils::id_type::MerchantId, + time_range: &TimeRange, + pool: &T, +) -> FiltersResult<Vec<AuthEventFilterRow>> +where + T: AnalyticsDataSource + AuthEventFilterAnalytics, + 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::Authentications); + + 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_id) + .switch()?; + + query_builder.set_distinct(); + + query_builder + .execute_query::<AuthEventFilterRow, _>(pool) + .await + .change_context(FiltersError::QueryBuildingError)? + .change_context(FiltersError::QueryExecutionFailure) +} + +#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] +pub struct AuthEventFilterRow { + pub authentication_status: Option<DBEnumWrapper<AuthenticationStatus>>, + pub trans_status: Option<DBEnumWrapper<TransactionStatus>>, + pub error_message: Option<String>, + pub authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>>, + pub message_version: Option<String>, +} diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index f3f0354818c..fd94aac614c 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -1,18 +1,23 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::{AuthEventMetrics, AuthEventMetricsBucketIdentifier}, + auth_events::{ + AuthEventDimensions, AuthEventFilters, AuthEventMetrics, AuthEventMetricsBucketIdentifier, + }, Granularity, TimeRange, }; +use diesel_models::enums as storage_enums; use time::PrimitiveDateTime; use crate::{ query::{Aggregate, GroupByClause, ToSql, Window}, - types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, MetricsResult}, + types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, }; mod authentication_attempt_count; mod authentication_count; +mod authentication_error_message; +mod authentication_funnel; mod authentication_success_count; mod challenge_attempt_count; mod challenge_flow_count; @@ -22,6 +27,8 @@ mod frictionless_success_count; use authentication_attempt_count::AuthenticationAttemptCount; use authentication_count::AuthenticationCount; +use authentication_error_message::AuthenticationErrorMessage; +use authentication_funnel::AuthenticationFunnel; use authentication_success_count::AuthenticationSuccessCount; use challenge_attempt_count::ChallengeAttemptCount; use challenge_flow_count::ChallengeFlowCount; @@ -32,7 +39,15 @@ use frictionless_success_count::FrictionlessSuccessCount; #[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)] pub struct AuthEventMetricRow { pub count: Option<i64>, - pub time_bucket: Option<String>, + pub authentication_status: Option<DBEnumWrapper<storage_enums::AuthenticationStatus>>, + pub trans_status: Option<DBEnumWrapper<storage_enums::TransactionStatus>>, + pub error_message: Option<String>, + pub authentication_connector: Option<DBEnumWrapper<storage_enums::AuthenticationConnectors>>, + pub message_version: Option<String>, + #[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 AuthEventMetricAnalytics: LoadRow<AuthEventMetricRow> {} @@ -45,6 +60,8 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, @@ -64,6 +81,8 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, @@ -71,42 +90,122 @@ where match self { Self::AuthenticationCount => { AuthenticationCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::AuthenticationAttemptCount => { AuthenticationAttemptCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::AuthenticationSuccessCount => { AuthenticationSuccessCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::ChallengeFlowCount => { ChallengeFlowCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::ChallengeAttemptCount => { ChallengeAttemptCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::ChallengeSuccessCount => { ChallengeSuccessCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::FrictionlessFlowCount => { FrictionlessFlowCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::FrictionlessSuccessCount => { FrictionlessSuccessCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::AuthenticationErrorMessage => { + AuthenticationErrorMessage + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::AuthenticationFunnel => { + AuthenticationFunnel + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } } diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index 2d34344905e..32c76385409 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; @@ -10,7 +11,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -30,6 +31,8 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, @@ -37,6 +40,10 @@ where let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + query_builder .add_select_column(Aggregate::Count { field: None, @@ -65,12 +72,19 @@ where query_builder .add_negative_filter_clause("authentication_status", AuthenticationStatus::Pending) .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -86,7 +100,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/metrics/authentication_count.rs b/crates/analytics/src/auth_events/metrics/authentication_count.rs index 9f2311f5638..39df41f53aa 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -9,7 +10,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -29,13 +30,17 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); - + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } query_builder .add_select_column(Aggregate::Count { field: None, @@ -60,12 +65,19 @@ where query_builder .add_filter_clause("merchant_id", merchant_id) .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -81,7 +93,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs new file mode 100644 index 00000000000..cdb89b796dd --- /dev/null +++ b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs @@ -0,0 +1,138 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_enums::AuthenticationStatus; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::AuthEventMetricRow; +use crate::{ + query::{ + Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, + Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct AuthenticationErrorMessage; + +#[async_trait::async_trait] +impl<T> super::AuthEventMetric<T> for AuthenticationErrorMessage +where + T: AnalyticsDataSource + super::AuthEventMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, + granularity: Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::Authentications); + 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()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + + query_builder + .add_filter_clause("authentication_status", AuthenticationStatus::Failed) + .switch()?; + + query_builder + .add_custom_filter_clause( + AuthEventDimensions::ErrorMessage, + "NULL", + FilterTypes::IsNotNull, + ) + .switch()?; + filters.set_filter_clause(&mut query_builder).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 { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<AuthEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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< + HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs new file mode 100644 index 00000000000..37f9dfd1c1f --- /dev/null +++ b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs @@ -0,0 +1,133 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::AuthEventMetricRow; +use crate::{ + query::{ + Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, + Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct AuthenticationFunnel; + +#[async_trait::async_trait] +impl<T> super::AuthEventMetric<T> for AuthenticationFunnel +where + T: AnalyticsDataSource + super::AuthEventMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, + granularity: Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::Authentications); + 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()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + + query_builder + .add_custom_filter_clause( + AuthEventDimensions::TransactionStatus, + "NULL", + FilterTypes::IsNotNull, + ) + .switch()?; + filters.set_filter_clause(&mut query_builder).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 { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<AuthEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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< + HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index e887807f41c..039ef00dd6e 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; @@ -10,7 +11,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -30,13 +31,17 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); - + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } query_builder .add_select_column(Aggregate::Count { field: None, @@ -65,12 +70,19 @@ where query_builder .add_filter_clause("authentication_status", AuthenticationStatus::Success) .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -86,7 +98,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index f1f6a397994..beccc093b19 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -9,7 +10,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -29,13 +30,17 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); - + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } query_builder .add_select_column(Aggregate::Count { field: None, @@ -68,12 +73,19 @@ where query_builder .add_negative_filter_clause("authentication_status", "pending") .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -89,7 +101,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index c08618cc0d0..4d07cffba94 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -9,7 +10,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -29,13 +30,17 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); - + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } query_builder .add_select_column(Aggregate::Count { field: None, @@ -64,12 +69,18 @@ where query_builder .add_filter_clause("trans_status", "C".to_string()) .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -85,7 +96,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index 3fb75efd562..310a45f0530 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; @@ -10,7 +11,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -30,13 +31,17 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); - + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } query_builder .add_select_column(Aggregate::Count { field: None, @@ -69,12 +74,19 @@ where query_builder .add_filter_clause("trans_status", "C".to_string()) .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -90,7 +102,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index 8859c60fc37..24857bfb840 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -9,7 +10,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -29,13 +30,17 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); - + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } query_builder .add_select_column(Aggregate::Count { field: None, @@ -64,12 +69,19 @@ where query_builder .add_filter_clause("trans_status", "Y".to_string()) .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -85,7 +97,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index 3d5d894e7dd..79fef8a16d0 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; @@ -10,7 +11,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -30,13 +31,17 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); - + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } query_builder .add_select_column(Aggregate::Count { field: None, @@ -69,12 +74,19 @@ where query_builder .add_filter_clause("authentication_status", AuthenticationStatus::Success) .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -90,7 +102,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/types.rs b/crates/analytics/src/auth_events/types.rs new file mode 100644 index 00000000000..ac7ee2462ee --- /dev/null +++ b/crates/analytics/src/auth_events/types.rs @@ -0,0 +1,58 @@ +use api_models::analytics::auth_events::{AuthEventDimensions, AuthEventFilters}; +use error_stack::ResultExt; + +use crate::{ + query::{QueryBuilder, QueryFilter, QueryResult, ToSql}, + types::{AnalyticsCollection, AnalyticsDataSource}, +}; + +impl<T> QueryFilter<T> for AuthEventFilters +where + T: AnalyticsDataSource, + AnalyticsCollection: ToSql<T>, +{ + fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> { + if !self.authentication_status.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::AuthenticationStatus, + &self.authentication_status, + ) + .attach_printable("Error adding authentication status filter")?; + } + + if !self.trans_status.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::TransactionStatus, + &self.trans_status, + ) + .attach_printable("Error adding transaction status filter")?; + } + + if !self.error_message.is_empty() { + builder + .add_filter_in_range_clause(AuthEventDimensions::ErrorMessage, &self.error_message) + .attach_printable("Error adding error message filter")?; + } + + if !self.authentication_connector.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::AuthenticationConnector, + &self.authentication_connector, + ) + .attach_printable("Error adding authentication connector filter")?; + } + + if !self.message_version.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::MessageVersion, + &self.message_version, + ) + .attach_printable("Error adding message version filter")?; + } + Ok(()) + } +} diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index 1c86e7cbcf6..1d52cc9e761 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -28,6 +28,7 @@ use crate::{ filters::ApiEventFilter, metrics::{latency::LatencyAvg, ApiEventMetricRow}, }, + auth_events::filters::AuthEventFilterRow, connector_events::events::ConnectorEventsResult, disputes::{filters::DisputeFilterRow, metrics::DisputeMetricRow}, outgoing_webhook_event::events::OutgoingWebhookLogsResult, @@ -181,6 +182,7 @@ impl super::sdk_events::metrics::SdkEventMetricAnalytics for ClickhouseClient {} impl super::sdk_events::events::SdkEventsFilterAnalytics for ClickhouseClient {} impl super::active_payments::metrics::ActivePaymentsMetricAnalytics for ClickhouseClient {} impl super::auth_events::metrics::AuthEventMetricAnalytics for ClickhouseClient {} +impl super::auth_events::filters::AuthEventFilterAnalytics for ClickhouseClient {} impl super::api_event::events::ApiLogsFilterAnalytics for ClickhouseClient {} impl super::api_event::filters::ApiEventFilterAnalytics for ClickhouseClient {} impl super::api_event::metrics::ApiEventMetricAnalytics for ClickhouseClient {} @@ -403,6 +405,16 @@ impl TryInto<AuthEventMetricRow> for serde_json::Value { } } +impl TryInto<AuthEventFilterRow> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<AuthEventFilterRow, Self::Error> { + serde_json::from_value(self).change_context(ParsingError::StructParseFailure( + "Failed to parse AuthEventFilterRow in clickhouse results", + )) + } +} + impl TryInto<ApiEventFilter> for serde_json::Value { type Error = Report<ParsingError>; diff --git a/crates/analytics/src/core.rs b/crates/analytics/src/core.rs index 0e3ced7993d..980e17bc90a 100644 --- a/crates/analytics/src/core.rs +++ b/crates/analytics/src/core.rs @@ -34,7 +34,7 @@ pub async fn get_domain_info( AnalyticsDomain::AuthEvents => GetInfoResponse { metrics: utils::get_auth_event_metrics_info(), download_dimensions: None, - dimensions: Vec::new(), + dimensions: utils::get_auth_event_dimensions(), }, AnalyticsDomain::ApiEvents => GetInfoResponse { metrics: utils::get_api_event_metrics_info(), diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index ef7108e8ef7..f698b1161a0 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -41,7 +41,9 @@ use api_models::analytics::{ api_event::{ ApiEventDimensions, ApiEventFilters, ApiEventMetrics, ApiEventMetricsBucketIdentifier, }, - auth_events::{AuthEventMetrics, AuthEventMetricsBucketIdentifier}, + auth_events::{ + AuthEventDimensions, AuthEventFilters, AuthEventMetrics, AuthEventMetricsBucketIdentifier, + }, disputes::{DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier}, frm::{FrmDimensions, FrmFilters, FrmMetrics, FrmMetricsBucketIdentifier}, payment_intents::{ @@ -908,7 +910,9 @@ impl AnalyticsProvider { pub async fn get_auth_event_metrics( &self, metric: &AuthEventMetrics, + dimensions: &[AuthEventDimensions], merchant_id: &common_utils::id_type::MerchantId, + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { @@ -916,13 +920,22 @@ impl AnalyticsProvider { Self::Sqlx(_pool) => Err(report!(MetricsError::NotImplemented)), Self::Clickhouse(pool) => { metric - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::CombinedCkh(_sqlx_pool, ckh_pool) | Self::CombinedSqlx(_sqlx_pool, ckh_pool) => { metric .load_metrics( merchant_id, + dimensions, + filters, granularity, // Since API events are ckh only use ckh here time_range, @@ -1126,6 +1139,7 @@ pub enum AnalyticsFlow { GetFrmMetrics, GetSdkMetrics, GetAuthMetrics, + GetAuthEventFilters, GetActivePaymentsMetrics, GetPaymentFilters, GetPaymentIntentFilters, diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index 59cb8743448..d483ce43605 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -4,7 +4,7 @@ use api_models::{ analytics::{ self as analytics_api, api_event::ApiEventDimensions, - auth_events::AuthEventFlows, + auth_events::{AuthEventDimensions, AuthEventFlows}, disputes::DisputeDimensions, frm::{FrmDimensions, FrmTransactionType}, payment_intents::PaymentIntentDimensions, @@ -19,7 +19,7 @@ use api_models::{ }, refunds::RefundStatus, }; -use common_enums::{AuthenticationStatus, TransactionStatus}; +use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; use common_utils::{ errors::{CustomResult, ParsingError}, id_type::{MerchantId, OrganizationId, ProfileId}, @@ -505,6 +505,7 @@ impl_to_sql_for_to_string!( FrmTransactionType, TransactionStatus, AuthenticationStatus, + AuthenticationConnectors, Flow, &String, &bool, @@ -522,7 +523,9 @@ impl_to_sql_for_to_string!( ApiEventDimensions, &DisputeDimensions, DisputeDimensions, - DisputeStage + DisputeStage, + AuthEventDimensions, + &AuthEventDimensions ); #[derive(Debug, Clone, Copy)] diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index f3143840f34..a6db92e753f 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -4,6 +4,7 @@ use api_models::{ analytics::{frm::FrmTransactionType, refunds::RefundType}, enums::{DisputeStage, DisputeStatus}, }; +use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; use common_utils::{ errors::{CustomResult, ParsingError}, DbConnectionParams, @@ -96,6 +97,9 @@ db_type!(FraudCheckStatus); db_type!(FrmTransactionType); db_type!(DisputeStage); db_type!(DisputeStatus); +db_type!(AuthenticationStatus); +db_type!(TransactionStatus); +db_type!(AuthenticationConnectors); impl<'q, Type> Encode<'q, Postgres> for DBEnumWrapper<Type> where @@ -159,6 +163,8 @@ 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 {} +impl super::auth_events::metrics::AuthEventMetricAnalytics for SqlxClient {} +impl super::auth_events::filters::AuthEventFilterAnalytics for SqlxClient {} #[async_trait::async_trait] impl AnalyticsDataSource for SqlxClient { @@ -190,6 +196,94 @@ impl HealthCheck for SqlxClient { } } +impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow { + fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { + let authentication_status: Option<DBEnumWrapper<AuthenticationStatus>> = + row.try_get("authentication_status").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let trans_status: Option<DBEnumWrapper<TransactionStatus>> = + row.try_get("trans_status").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>> = row + .try_get("authentication_connector") + .or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let message_version: Option<String> = + row.try_get("message_version").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 { + authentication_status, + trans_status, + error_message, + authentication_connector, + message_version, + count, + start_bucket, + end_bucket, + }) + } +} + +impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow { + fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { + let authentication_status: Option<DBEnumWrapper<AuthenticationStatus>> = + row.try_get("authentication_status").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let trans_status: Option<DBEnumWrapper<TransactionStatus>> = + row.try_get("trans_status").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>> = row + .try_get("authentication_connector") + .or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let message_version: Option<String> = + row.try_get("message_version").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + Ok(Self { + authentication_status, + trans_status, + error_message, + authentication_connector, + message_version, + }) + } +} + impl<'a> FromRow<'a, PgRow> for super::refunds::metrics::RefundMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs index fc21bf09819..a0ddead1363 100644 --- a/crates/analytics/src/utils.rs +++ b/crates/analytics/src/utils.rs @@ -1,6 +1,6 @@ use api_models::analytics::{ api_event::{ApiEventDimensions, ApiEventMetrics}, - auth_events::AuthEventMetrics, + auth_events::{AuthEventDimensions, AuthEventMetrics}, disputes::{DisputeDimensions, DisputeMetrics}, frm::{FrmDimensions, FrmMetrics}, payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics}, @@ -47,6 +47,16 @@ pub fn get_payment_intent_dimensions() -> Vec<NameDescription> { .collect() } +pub fn get_auth_event_dimensions() -> Vec<NameDescription> { + vec![ + AuthEventDimensions::AuthenticationConnector, + AuthEventDimensions::MessageVersion, + ] + .into_iter() + .map(Into::into) + .collect() +} + pub fn get_refund_dimensions() -> Vec<NameDescription> { RefundDimensions::iter().map(Into::into).collect() } diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 132272f0e49..71d7f80eb7c 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -7,7 +7,7 @@ use masking::Secret; use self::{ active_payments::ActivePaymentsMetrics, api_event::{ApiEventDimensions, ApiEventMetrics}, - auth_events::AuthEventMetrics, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetrics}, disputes::{DisputeDimensions, DisputeMetrics}, frm::{FrmDimensions, FrmMetrics}, payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics}, @@ -226,6 +226,10 @@ pub struct GetAuthEventMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] + pub group_by_names: Vec<AuthEventDimensions>, + #[serde(default)] + pub filters: AuthEventFilters, + #[serde(default)] pub metrics: HashSet<AuthEventMetrics>, #[serde(default)] pub delta: bool, @@ -509,3 +513,36 @@ pub struct SankeyResponse { pub dispute_status: Option<String>, pub first_attempt: i64, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GetAuthEventFilterRequest { + pub time_range: TimeRange, + #[serde(default)] + pub group_by_names: Vec<AuthEventDimensions>, +} + +#[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct AuthEventFiltersResponse { + pub query_data: Vec<AuthEventFilterValue>, +} + +#[derive(Debug, serde::Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct AuthEventFilterValue { + pub dimension: AuthEventDimensions, + pub values: Vec<String>, +} + +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthEventMetricsResponse<T> { + pub query_data: Vec<T>, + pub meta_data: [AuthEventsAnalyticsMetadata; 1], +} + +#[derive(Debug, serde::Serialize)] +pub struct AuthEventsAnalyticsMetadata { + pub total_error_message_count: Option<u64>, +} diff --git a/crates/api_models/src/analytics/auth_events.rs b/crates/api_models/src/analytics/auth_events.rs index 6f527551348..5c2d4ed2064 100644 --- a/crates/api_models/src/analytics/auth_events.rs +++ b/crates/api_models/src/analytics/auth_events.rs @@ -3,7 +3,23 @@ use std::{ hash::{Hash, Hasher}, }; -use super::NameDescription; +use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; + +use super::{NameDescription, TimeRange}; + +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] +pub struct AuthEventFilters { + #[serde(default)] + pub authentication_status: Vec<AuthenticationStatus>, + #[serde(default)] + pub trans_status: Vec<TransactionStatus>, + #[serde(default)] + pub error_message: Vec<String>, + #[serde(default)] + pub authentication_connector: Vec<AuthenticationConnectors>, + #[serde(default)] + pub message_version: Vec<String>, +} #[derive( Debug, @@ -22,10 +38,13 @@ use super::NameDescription; #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthEventDimensions { - #[serde(rename = "authentication_status")] AuthenticationStatus, + #[strum(serialize = "trans_status")] #[serde(rename = "trans_status")] TransactionStatus, + ErrorMessage, + AuthenticationConnector, + MessageVersion, } #[derive( @@ -51,6 +70,8 @@ pub enum AuthEventMetrics { FrictionlessSuccessCount, ChallengeAttemptCount, ChallengeSuccessCount, + AuthenticationErrorMessage, + AuthenticationFunnel, } #[derive( @@ -79,6 +100,7 @@ pub mod metric_behaviour { pub struct FrictionlessSuccessCount; pub struct ChallengeAttemptCount; pub struct ChallengeSuccessCount; + pub struct AuthenticationErrorMessage; } impl From<AuthEventMetrics> for NameDescription { @@ -90,19 +112,58 @@ impl From<AuthEventMetrics> for NameDescription { } } +impl From<AuthEventDimensions> for NameDescription { + fn from(value: AuthEventDimensions) -> Self { + Self { + name: value.to_string(), + desc: String::new(), + } + } +} + #[derive(Debug, serde::Serialize, Eq)] pub struct AuthEventMetricsBucketIdentifier { - pub time_bucket: Option<String>, + pub authentication_status: Option<AuthenticationStatus>, + pub trans_status: Option<TransactionStatus>, + pub error_message: Option<String>, + pub authentication_connector: Option<AuthenticationConnectors>, + pub message_version: 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 AuthEventMetricsBucketIdentifier { - pub fn new(time_bucket: Option<String>) -> Self { - Self { time_bucket } + #[allow(clippy::too_many_arguments)] + pub fn new( + authentication_status: Option<AuthenticationStatus>, + trans_status: Option<TransactionStatus>, + error_message: Option<String>, + authentication_connector: Option<AuthenticationConnectors>, + message_version: Option<String>, + normalized_time_range: TimeRange, + ) -> Self { + Self { + authentication_status, + trans_status, + error_message, + authentication_connector, + message_version, + time_bucket: normalized_time_range, + start_time: normalized_time_range.start_time, + } } } impl Hash for AuthEventMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { + self.authentication_status.hash(state); + self.trans_status.hash(state); + self.authentication_connector.hash(state); + self.message_version.hash(state); + self.error_message.hash(state); self.time_bucket.hash(state); } } @@ -127,6 +188,8 @@ pub struct AuthEventMetricsBucketValue { pub challenge_success_count: Option<u64>, pub frictionless_flow_count: Option<u64>, pub frictionless_success_count: Option<u64>, + pub error_message_count: Option<u64>, + pub authentication_funnel: Option<u64>, } #[derive(Debug, serde::Serialize)] diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index bf7544f7c01..31b0c1d8dce 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -113,10 +113,12 @@ impl_api_event_type!( GetActivePaymentsMetricRequest, GetSdkEventMetricRequest, GetAuthEventMetricRequest, + GetAuthEventFilterRequest, GetPaymentFiltersRequest, PaymentFiltersResponse, GetRefundFilterRequest, RefundFiltersResponse, + AuthEventFiltersResponse, GetSdkEventFiltersRequest, SdkEventFiltersResponse, ApiLogsRequest, @@ -180,6 +182,13 @@ impl<T> ApiEventMetric for DisputesMetricsResponse<T> { Some(ApiEventsType::Miscellaneous) } } + +impl<T> ApiEventMetric for AuthEventMetricsResponse<T> { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Miscellaneous) + } +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl ApiEventMetric for PaymentMethodIntentConfirmInternal { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index c30fe62f829..96afca926c7 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -6685,6 +6685,7 @@ impl From<RoleScope> for EntityType { serde::Serialize, serde::Deserialize, Eq, + Hash, PartialEq, ToSchema, strum::Display, diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index deaf84bb009..858c16d052f 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -19,11 +19,11 @@ pub mod routes { GetGlobalSearchRequest, GetSearchRequest, GetSearchRequestWithIndex, SearchIndex, }, AnalyticsRequest, GenerateReportRequest, GetActivePaymentsMetricRequest, - GetApiEventFiltersRequest, GetApiEventMetricRequest, GetAuthEventMetricRequest, - GetDisputeMetricRequest, GetFrmFilterRequest, GetFrmMetricRequest, - GetPaymentFiltersRequest, GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, - GetPaymentMetricRequest, GetRefundFilterRequest, GetRefundMetricRequest, - GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest, + GetApiEventFiltersRequest, GetApiEventMetricRequest, GetAuthEventFilterRequest, + GetAuthEventMetricRequest, GetDisputeMetricRequest, GetFrmFilterRequest, + GetFrmMetricRequest, GetPaymentFiltersRequest, GetPaymentIntentFiltersRequest, + GetPaymentIntentMetricRequest, GetPaymentMetricRequest, GetRefundFilterRequest, + GetRefundMetricRequest, GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest, }; use common_enums::EntityType; use common_utils::types::TimeRange; @@ -106,6 +106,10 @@ pub mod routes { web::resource("metrics/auth_events") .route(web::post().to(get_auth_event_metrics)), ) + .service( + web::resource("filters/auth_events") + .route(web::post().to(get_merchant_auth_events_filters)), + ) .service( web::resource("metrics/frm").route(web::post().to(get_frm_metrics)), ) @@ -1018,6 +1022,34 @@ pub mod routes { .await } + pub async fn get_merchant_auth_events_filters( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<GetAuthEventFilterRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetAuthEventFilters; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req, _| async move { + analytics::auth_events::get_filters( + &state.pool, + req, + auth.merchant_account.get_id(), + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::MerchantAnalyticsRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + pub async fn get_org_payment_filters( state: web::Data<AppState>, req: actix_web::HttpRequest,
2025-03-06T17:03:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Hotfix PR Original PR: [https://github.com/juspay/hyperswitch/pull/7451](https://github.com/juspay/hyperswitch/pull/7451) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
ec0718f31edf165def85aa71e5d63711d31b4c36
ec0718f31edf165def85aa71e5d63711d31b4c36
juspay/hyperswitch
juspay__hyperswitch-7450
Bug: feat(analytics): add new filters, dimensions and metrics for authentication analytics Add support for filters and dimensions for authentication analytics. Create new metrics: - Authentication Error Message - Authentication Funnel
diff --git a/crates/analytics/src/auth_events.rs b/crates/analytics/src/auth_events.rs index e708c3c8830..3aa23d0793d 100644 --- a/crates/analytics/src/auth_events.rs +++ b/crates/analytics/src/auth_events.rs @@ -1,6 +1,8 @@ pub mod accumulator; mod core; +pub mod filters; pub mod metrics; +pub mod types; pub use accumulator::{AuthEventMetricAccumulator, AuthEventMetricsAccumulator}; -pub use self::core::get_metrics; +pub use self::core::{get_filters, get_metrics}; diff --git a/crates/analytics/src/auth_events/accumulator.rs b/crates/analytics/src/auth_events/accumulator.rs index 446ac6ac8c2..13818d2bd43 100644 --- a/crates/analytics/src/auth_events/accumulator.rs +++ b/crates/analytics/src/auth_events/accumulator.rs @@ -6,12 +6,14 @@ use super::metrics::AuthEventMetricRow; pub struct AuthEventMetricsAccumulator { pub authentication_count: CountAccumulator, pub authentication_attempt_count: CountAccumulator, + pub authentication_error_message: AuthenticationErrorMessageAccumulator, pub authentication_success_count: CountAccumulator, pub challenge_flow_count: CountAccumulator, pub challenge_attempt_count: CountAccumulator, pub challenge_success_count: CountAccumulator, pub frictionless_flow_count: CountAccumulator, pub frictionless_success_count: CountAccumulator, + pub authentication_funnel: CountAccumulator, } #[derive(Debug, Default)] @@ -20,6 +22,11 @@ pub struct CountAccumulator { pub count: Option<i64>, } +#[derive(Debug, Default)] +pub struct AuthenticationErrorMessageAccumulator { + pub count: Option<i64>, +} + pub trait AuthEventMetricAccumulator { type MetricOutput; @@ -44,6 +51,22 @@ impl AuthEventMetricAccumulator for CountAccumulator { } } +impl AuthEventMetricAccumulator for AuthenticationErrorMessageAccumulator { + type MetricOutput = Option<u64>; + #[inline] + fn add_metrics_bucket(&mut self, metrics: &AuthEventMetricRow) { + 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 AuthEventMetricsAccumulator { pub fn collect(self) -> AuthEventMetricsBucketValue { AuthEventMetricsBucketValue { @@ -55,6 +78,8 @@ impl AuthEventMetricsAccumulator { challenge_success_count: self.challenge_success_count.collect(), frictionless_flow_count: self.frictionless_flow_count.collect(), frictionless_success_count: self.frictionless_success_count.collect(), + error_message_count: self.authentication_error_message.collect(), + authentication_funnel: self.authentication_funnel.collect(), } } } diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs index 75bdf4de149..a2640be6ead 100644 --- a/crates/analytics/src/auth_events/core.rs +++ b/crates/analytics/src/auth_events/core.rs @@ -1,13 +1,20 @@ use std::collections::HashMap; use api_models::analytics::{ - auth_events::{AuthEventMetrics, AuthEventMetricsBucketIdentifier, MetricsBucketResponse}, - AnalyticsMetadata, GetAuthEventMetricRequest, MetricsResponse, + auth_events::{ + AuthEventDimensions, AuthEventMetrics, AuthEventMetricsBucketIdentifier, + MetricsBucketResponse, + }, + AuthEventFilterValue, AuthEventFiltersResponse, AuthEventMetricsResponse, + AuthEventsAnalyticsMetadata, GetAuthEventFilterRequest, GetAuthEventMetricRequest, }; -use error_stack::ResultExt; +use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; -use super::AuthEventMetricsAccumulator; +use super::{ + filters::{get_auth_events_filter_for_dimension, AuthEventFilterRow}, + AuthEventMetricsAccumulator, +}; use crate::{ auth_events::AuthEventMetricAccumulator, errors::{AnalyticsError, AnalyticsResult}, @@ -19,7 +26,7 @@ pub async fn get_metrics( pool: &AnalyticsProvider, merchant_id: &common_utils::id_type::MerchantId, req: GetAuthEventMetricRequest, -) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> { +) -> AnalyticsResult<AuthEventMetricsResponse<MetricsBucketResponse>> { let mut metrics_accumulator: HashMap< AuthEventMetricsBucketIdentifier, AuthEventMetricsAccumulator, @@ -34,7 +41,9 @@ pub async fn get_metrics( let data = pool .get_auth_event_metrics( &metric_type, + &req.group_by_names.clone(), &merchant_id_scoped, + &req.filters, req.time_series.map(|t| t.granularity), &req.time_range, ) @@ -77,22 +86,94 @@ pub async fn get_metrics( AuthEventMetrics::FrictionlessSuccessCount => metrics_builder .frictionless_success_count .add_metrics_bucket(&value), + AuthEventMetrics::AuthenticationErrorMessage => metrics_builder + .authentication_error_message + .add_metrics_bucket(&value), + AuthEventMetrics::AuthenticationFunnel => metrics_builder + .authentication_funnel + .add_metrics_bucket(&value), } } } + let mut total_error_message_count = 0; let query_data: Vec<MetricsBucketResponse> = metrics_accumulator .into_iter() - .map(|(id, val)| MetricsBucketResponse { - values: val.collect(), - dimensions: id, + .map(|(id, val)| { + let collected_values = val.collect(); + if let Some(count) = collected_values.error_message_count { + total_error_message_count += count; + } + MetricsBucketResponse { + values: collected_values, + dimensions: id, + } }) .collect(); - - Ok(MetricsResponse { + Ok(AuthEventMetricsResponse { query_data, - meta_data: [AnalyticsMetadata { - current_time_range: req.time_range, + meta_data: [AuthEventsAnalyticsMetadata { + total_error_message_count: Some(total_error_message_count), }], }) } + +pub async fn get_filters( + pool: &AnalyticsProvider, + req: GetAuthEventFilterRequest, + merchant_id: &common_utils::id_type::MerchantId, +) -> AnalyticsResult<AuthEventFiltersResponse> { + let mut res = AuthEventFiltersResponse::default(); + for dim in req.group_by_names { + let values = match pool { + AnalyticsProvider::Sqlx(_pool) => { + Err(report!(AnalyticsError::UnknownError)) + } + AnalyticsProvider::Clickhouse(pool) => { + get_auth_events_filter_for_dimension(dim, merchant_id, &req.time_range, pool) + .await + .map_err(|e| e.change_context(AnalyticsError::UnknownError)) + } + AnalyticsProvider::CombinedCkh(sqlx_pool, ckh_pool) | AnalyticsProvider::CombinedSqlx(sqlx_pool, ckh_pool) => { + let ckh_result = get_auth_events_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + ckh_pool, + ) + .await + .map_err(|e| e.change_context(AnalyticsError::UnknownError)); + let sqlx_result = get_auth_events_filter_for_dimension( + dim, + merchant_id, + &req.time_range, + sqlx_pool, + ) + .await + .map_err(|e| e.change_context(AnalyticsError::UnknownError)); + match (&sqlx_result, &ckh_result) { + (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { + router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres refunds analytics filters") + }, + _ => {} + }; + ckh_result + } + } + .change_context(AnalyticsError::UnknownError)? + .into_iter() + .filter_map(|fil: AuthEventFilterRow| match dim { + AuthEventDimensions::AuthenticationStatus => fil.authentication_status.map(|i| i.as_ref().to_string()), + AuthEventDimensions::TransactionStatus => fil.trans_status.map(|i| i.as_ref().to_string()), + AuthEventDimensions::ErrorMessage => fil.error_message, + AuthEventDimensions::AuthenticationConnector => fil.authentication_connector.map(|i| i.as_ref().to_string()), + AuthEventDimensions::MessageVersion => fil.message_version, + }) + .collect::<Vec<String>>(); + res.query_data.push(AuthEventFilterValue { + dimension: dim, + values, + }) + } + Ok(res) +} diff --git a/crates/analytics/src/auth_events/filters.rs b/crates/analytics/src/auth_events/filters.rs new file mode 100644 index 00000000000..da8e0b7cfa3 --- /dev/null +++ b/crates/analytics/src/auth_events/filters.rs @@ -0,0 +1,60 @@ +use api_models::analytics::{auth_events::AuthEventDimensions, Granularity, TimeRange}; +use common_utils::errors::ReportSwitchExt; +use diesel_models::enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; +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 AuthEventFilterAnalytics: LoadRow<AuthEventFilterRow> {} + +pub async fn get_auth_events_filter_for_dimension<T>( + dimension: AuthEventDimensions, + merchant_id: &common_utils::id_type::MerchantId, + time_range: &TimeRange, + pool: &T, +) -> FiltersResult<Vec<AuthEventFilterRow>> +where + T: AnalyticsDataSource + AuthEventFilterAnalytics, + 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::Authentications); + + 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_id) + .switch()?; + + query_builder.set_distinct(); + + query_builder + .execute_query::<AuthEventFilterRow, _>(pool) + .await + .change_context(FiltersError::QueryBuildingError)? + .change_context(FiltersError::QueryExecutionFailure) +} + +#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] +pub struct AuthEventFilterRow { + pub authentication_status: Option<DBEnumWrapper<AuthenticationStatus>>, + pub trans_status: Option<DBEnumWrapper<TransactionStatus>>, + pub error_message: Option<String>, + pub authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>>, + pub message_version: Option<String>, +} diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index f3f0354818c..fd94aac614c 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -1,18 +1,23 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::{AuthEventMetrics, AuthEventMetricsBucketIdentifier}, + auth_events::{ + AuthEventDimensions, AuthEventFilters, AuthEventMetrics, AuthEventMetricsBucketIdentifier, + }, Granularity, TimeRange, }; +use diesel_models::enums as storage_enums; use time::PrimitiveDateTime; use crate::{ query::{Aggregate, GroupByClause, ToSql, Window}, - types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, MetricsResult}, + types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, }; mod authentication_attempt_count; mod authentication_count; +mod authentication_error_message; +mod authentication_funnel; mod authentication_success_count; mod challenge_attempt_count; mod challenge_flow_count; @@ -22,6 +27,8 @@ mod frictionless_success_count; use authentication_attempt_count::AuthenticationAttemptCount; use authentication_count::AuthenticationCount; +use authentication_error_message::AuthenticationErrorMessage; +use authentication_funnel::AuthenticationFunnel; use authentication_success_count::AuthenticationSuccessCount; use challenge_attempt_count::ChallengeAttemptCount; use challenge_flow_count::ChallengeFlowCount; @@ -32,7 +39,15 @@ use frictionless_success_count::FrictionlessSuccessCount; #[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)] pub struct AuthEventMetricRow { pub count: Option<i64>, - pub time_bucket: Option<String>, + pub authentication_status: Option<DBEnumWrapper<storage_enums::AuthenticationStatus>>, + pub trans_status: Option<DBEnumWrapper<storage_enums::TransactionStatus>>, + pub error_message: Option<String>, + pub authentication_connector: Option<DBEnumWrapper<storage_enums::AuthenticationConnectors>>, + pub message_version: Option<String>, + #[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 AuthEventMetricAnalytics: LoadRow<AuthEventMetricRow> {} @@ -45,6 +60,8 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, @@ -64,6 +81,8 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, @@ -71,42 +90,122 @@ where match self { Self::AuthenticationCount => { AuthenticationCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::AuthenticationAttemptCount => { AuthenticationAttemptCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::AuthenticationSuccessCount => { AuthenticationSuccessCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::ChallengeFlowCount => { ChallengeFlowCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::ChallengeAttemptCount => { ChallengeAttemptCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::ChallengeSuccessCount => { ChallengeSuccessCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::FrictionlessFlowCount => { FrictionlessFlowCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::FrictionlessSuccessCount => { FrictionlessSuccessCount - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::AuthenticationErrorMessage => { + AuthenticationErrorMessage + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::AuthenticationFunnel => { + AuthenticationFunnel + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } } diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index 2d34344905e..32c76385409 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; @@ -10,7 +11,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -30,6 +31,8 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, @@ -37,6 +40,10 @@ where let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + query_builder .add_select_column(Aggregate::Count { field: None, @@ -65,12 +72,19 @@ where query_builder .add_negative_filter_clause("authentication_status", AuthenticationStatus::Pending) .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -86,7 +100,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/metrics/authentication_count.rs b/crates/analytics/src/auth_events/metrics/authentication_count.rs index 9f2311f5638..39df41f53aa 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -9,7 +10,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -29,13 +30,17 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); - + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } query_builder .add_select_column(Aggregate::Count { field: None, @@ -60,12 +65,19 @@ where query_builder .add_filter_clause("merchant_id", merchant_id) .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -81,7 +93,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs new file mode 100644 index 00000000000..cdb89b796dd --- /dev/null +++ b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs @@ -0,0 +1,138 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_enums::AuthenticationStatus; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::AuthEventMetricRow; +use crate::{ + query::{ + Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, + Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct AuthenticationErrorMessage; + +#[async_trait::async_trait] +impl<T> super::AuthEventMetric<T> for AuthenticationErrorMessage +where + T: AnalyticsDataSource + super::AuthEventMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, + granularity: Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::Authentications); + 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()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + + query_builder + .add_filter_clause("authentication_status", AuthenticationStatus::Failed) + .switch()?; + + query_builder + .add_custom_filter_clause( + AuthEventDimensions::ErrorMessage, + "NULL", + FilterTypes::IsNotNull, + ) + .switch()?; + filters.set_filter_clause(&mut query_builder).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 { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<AuthEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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< + HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs new file mode 100644 index 00000000000..37f9dfd1c1f --- /dev/null +++ b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs @@ -0,0 +1,133 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::AuthEventMetricRow; +use crate::{ + query::{ + Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, + Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct AuthenticationFunnel; + +#[async_trait::async_trait] +impl<T> super::AuthEventMetric<T> for AuthenticationFunnel +where + T: AnalyticsDataSource + super::AuthEventMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, + granularity: Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::Authentications); + 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()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + + query_builder + .add_custom_filter_clause( + AuthEventDimensions::TransactionStatus, + "NULL", + FilterTypes::IsNotNull, + ) + .switch()?; + filters.set_filter_clause(&mut query_builder).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 { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<AuthEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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< + HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index e887807f41c..039ef00dd6e 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; @@ -10,7 +11,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -30,13 +31,17 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); - + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } query_builder .add_select_column(Aggregate::Count { field: None, @@ -65,12 +70,19 @@ where query_builder .add_filter_clause("authentication_status", AuthenticationStatus::Success) .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -86,7 +98,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index f1f6a397994..beccc093b19 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -9,7 +10,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -29,13 +30,17 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); - + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } query_builder .add_select_column(Aggregate::Count { field: None, @@ -68,12 +73,19 @@ where query_builder .add_negative_filter_clause("authentication_status", "pending") .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -89,7 +101,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index c08618cc0d0..4d07cffba94 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -9,7 +10,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -29,13 +30,17 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); - + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } query_builder .add_select_column(Aggregate::Count { field: None, @@ -64,12 +69,18 @@ where query_builder .add_filter_clause("trans_status", "C".to_string()) .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -85,7 +96,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index 3fb75efd562..310a45f0530 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; @@ -10,7 +11,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -30,13 +31,17 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); - + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } query_builder .add_select_column(Aggregate::Count { field: None, @@ -69,12 +74,19 @@ where query_builder .add_filter_clause("trans_status", "C".to_string()) .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -90,7 +102,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index 8859c60fc37..24857bfb840 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -9,7 +10,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -29,13 +30,17 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); - + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } query_builder .add_select_column(Aggregate::Count { field: None, @@ -64,12 +69,19 @@ where query_builder .add_filter_clause("trans_status", "Y".to_string()) .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -85,7 +97,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index 3d5d894e7dd..79fef8a16d0 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -1,7 +1,8 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, }; use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; @@ -10,7 +11,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -30,13 +31,17 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Authentications); - + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } query_builder .add_select_column(Aggregate::Count { field: None, @@ -69,12 +74,19 @@ where query_builder .add_filter_clause("authentication_status", AuthenticationStatus::Success) .switch()?; - + filters.set_filter_clause(&mut query_builder).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 { granularity .set_group_by_clause(&mut query_builder) @@ -90,7 +102,23 @@ where .into_iter() .map(|i| { Ok(( - AuthEventMetricsBucketIdentifier::new(i.time_bucket.clone()), + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + 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, )) }) diff --git a/crates/analytics/src/auth_events/types.rs b/crates/analytics/src/auth_events/types.rs new file mode 100644 index 00000000000..ac7ee2462ee --- /dev/null +++ b/crates/analytics/src/auth_events/types.rs @@ -0,0 +1,58 @@ +use api_models::analytics::auth_events::{AuthEventDimensions, AuthEventFilters}; +use error_stack::ResultExt; + +use crate::{ + query::{QueryBuilder, QueryFilter, QueryResult, ToSql}, + types::{AnalyticsCollection, AnalyticsDataSource}, +}; + +impl<T> QueryFilter<T> for AuthEventFilters +where + T: AnalyticsDataSource, + AnalyticsCollection: ToSql<T>, +{ + fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> { + if !self.authentication_status.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::AuthenticationStatus, + &self.authentication_status, + ) + .attach_printable("Error adding authentication status filter")?; + } + + if !self.trans_status.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::TransactionStatus, + &self.trans_status, + ) + .attach_printable("Error adding transaction status filter")?; + } + + if !self.error_message.is_empty() { + builder + .add_filter_in_range_clause(AuthEventDimensions::ErrorMessage, &self.error_message) + .attach_printable("Error adding error message filter")?; + } + + if !self.authentication_connector.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::AuthenticationConnector, + &self.authentication_connector, + ) + .attach_printable("Error adding authentication connector filter")?; + } + + if !self.message_version.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::MessageVersion, + &self.message_version, + ) + .attach_printable("Error adding message version filter")?; + } + Ok(()) + } +} diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index 1c86e7cbcf6..1d52cc9e761 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -28,6 +28,7 @@ use crate::{ filters::ApiEventFilter, metrics::{latency::LatencyAvg, ApiEventMetricRow}, }, + auth_events::filters::AuthEventFilterRow, connector_events::events::ConnectorEventsResult, disputes::{filters::DisputeFilterRow, metrics::DisputeMetricRow}, outgoing_webhook_event::events::OutgoingWebhookLogsResult, @@ -181,6 +182,7 @@ impl super::sdk_events::metrics::SdkEventMetricAnalytics for ClickhouseClient {} impl super::sdk_events::events::SdkEventsFilterAnalytics for ClickhouseClient {} impl super::active_payments::metrics::ActivePaymentsMetricAnalytics for ClickhouseClient {} impl super::auth_events::metrics::AuthEventMetricAnalytics for ClickhouseClient {} +impl super::auth_events::filters::AuthEventFilterAnalytics for ClickhouseClient {} impl super::api_event::events::ApiLogsFilterAnalytics for ClickhouseClient {} impl super::api_event::filters::ApiEventFilterAnalytics for ClickhouseClient {} impl super::api_event::metrics::ApiEventMetricAnalytics for ClickhouseClient {} @@ -403,6 +405,16 @@ impl TryInto<AuthEventMetricRow> for serde_json::Value { } } +impl TryInto<AuthEventFilterRow> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<AuthEventFilterRow, Self::Error> { + serde_json::from_value(self).change_context(ParsingError::StructParseFailure( + "Failed to parse AuthEventFilterRow in clickhouse results", + )) + } +} + impl TryInto<ApiEventFilter> for serde_json::Value { type Error = Report<ParsingError>; diff --git a/crates/analytics/src/core.rs b/crates/analytics/src/core.rs index 0e3ced7993d..980e17bc90a 100644 --- a/crates/analytics/src/core.rs +++ b/crates/analytics/src/core.rs @@ -34,7 +34,7 @@ pub async fn get_domain_info( AnalyticsDomain::AuthEvents => GetInfoResponse { metrics: utils::get_auth_event_metrics_info(), download_dimensions: None, - dimensions: Vec::new(), + dimensions: utils::get_auth_event_dimensions(), }, AnalyticsDomain::ApiEvents => GetInfoResponse { metrics: utils::get_api_event_metrics_info(), diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index ef7108e8ef7..f698b1161a0 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -41,7 +41,9 @@ use api_models::analytics::{ api_event::{ ApiEventDimensions, ApiEventFilters, ApiEventMetrics, ApiEventMetricsBucketIdentifier, }, - auth_events::{AuthEventMetrics, AuthEventMetricsBucketIdentifier}, + auth_events::{ + AuthEventDimensions, AuthEventFilters, AuthEventMetrics, AuthEventMetricsBucketIdentifier, + }, disputes::{DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier}, frm::{FrmDimensions, FrmFilters, FrmMetrics, FrmMetricsBucketIdentifier}, payment_intents::{ @@ -908,7 +910,9 @@ impl AnalyticsProvider { pub async fn get_auth_event_metrics( &self, metric: &AuthEventMetrics, + dimensions: &[AuthEventDimensions], merchant_id: &common_utils::id_type::MerchantId, + filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { @@ -916,13 +920,22 @@ impl AnalyticsProvider { Self::Sqlx(_pool) => Err(report!(MetricsError::NotImplemented)), Self::Clickhouse(pool) => { metric - .load_metrics(merchant_id, granularity, time_range, pool) + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) .await } Self::CombinedCkh(_sqlx_pool, ckh_pool) | Self::CombinedSqlx(_sqlx_pool, ckh_pool) => { metric .load_metrics( merchant_id, + dimensions, + filters, granularity, // Since API events are ckh only use ckh here time_range, @@ -1126,6 +1139,7 @@ pub enum AnalyticsFlow { GetFrmMetrics, GetSdkMetrics, GetAuthMetrics, + GetAuthEventFilters, GetActivePaymentsMetrics, GetPaymentFilters, GetPaymentIntentFilters, diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index 59cb8743448..d483ce43605 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -4,7 +4,7 @@ use api_models::{ analytics::{ self as analytics_api, api_event::ApiEventDimensions, - auth_events::AuthEventFlows, + auth_events::{AuthEventDimensions, AuthEventFlows}, disputes::DisputeDimensions, frm::{FrmDimensions, FrmTransactionType}, payment_intents::PaymentIntentDimensions, @@ -19,7 +19,7 @@ use api_models::{ }, refunds::RefundStatus, }; -use common_enums::{AuthenticationStatus, TransactionStatus}; +use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; use common_utils::{ errors::{CustomResult, ParsingError}, id_type::{MerchantId, OrganizationId, ProfileId}, @@ -505,6 +505,7 @@ impl_to_sql_for_to_string!( FrmTransactionType, TransactionStatus, AuthenticationStatus, + AuthenticationConnectors, Flow, &String, &bool, @@ -522,7 +523,9 @@ impl_to_sql_for_to_string!( ApiEventDimensions, &DisputeDimensions, DisputeDimensions, - DisputeStage + DisputeStage, + AuthEventDimensions, + &AuthEventDimensions ); #[derive(Debug, Clone, Copy)] diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index f3143840f34..a6db92e753f 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -4,6 +4,7 @@ use api_models::{ analytics::{frm::FrmTransactionType, refunds::RefundType}, enums::{DisputeStage, DisputeStatus}, }; +use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; use common_utils::{ errors::{CustomResult, ParsingError}, DbConnectionParams, @@ -96,6 +97,9 @@ db_type!(FraudCheckStatus); db_type!(FrmTransactionType); db_type!(DisputeStage); db_type!(DisputeStatus); +db_type!(AuthenticationStatus); +db_type!(TransactionStatus); +db_type!(AuthenticationConnectors); impl<'q, Type> Encode<'q, Postgres> for DBEnumWrapper<Type> where @@ -159,6 +163,8 @@ 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 {} +impl super::auth_events::metrics::AuthEventMetricAnalytics for SqlxClient {} +impl super::auth_events::filters::AuthEventFilterAnalytics for SqlxClient {} #[async_trait::async_trait] impl AnalyticsDataSource for SqlxClient { @@ -190,6 +196,94 @@ impl HealthCheck for SqlxClient { } } +impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow { + fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { + let authentication_status: Option<DBEnumWrapper<AuthenticationStatus>> = + row.try_get("authentication_status").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let trans_status: Option<DBEnumWrapper<TransactionStatus>> = + row.try_get("trans_status").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>> = row + .try_get("authentication_connector") + .or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let message_version: Option<String> = + row.try_get("message_version").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 { + authentication_status, + trans_status, + error_message, + authentication_connector, + message_version, + count, + start_bucket, + end_bucket, + }) + } +} + +impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow { + fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { + let authentication_status: Option<DBEnumWrapper<AuthenticationStatus>> = + row.try_get("authentication_status").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let trans_status: Option<DBEnumWrapper<TransactionStatus>> = + row.try_get("trans_status").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>> = row + .try_get("authentication_connector") + .or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let message_version: Option<String> = + row.try_get("message_version").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + Ok(Self { + authentication_status, + trans_status, + error_message, + authentication_connector, + message_version, + }) + } +} + impl<'a> FromRow<'a, PgRow> for super::refunds::metrics::RefundMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs index fc21bf09819..a0ddead1363 100644 --- a/crates/analytics/src/utils.rs +++ b/crates/analytics/src/utils.rs @@ -1,6 +1,6 @@ use api_models::analytics::{ api_event::{ApiEventDimensions, ApiEventMetrics}, - auth_events::AuthEventMetrics, + auth_events::{AuthEventDimensions, AuthEventMetrics}, disputes::{DisputeDimensions, DisputeMetrics}, frm::{FrmDimensions, FrmMetrics}, payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics}, @@ -47,6 +47,16 @@ pub fn get_payment_intent_dimensions() -> Vec<NameDescription> { .collect() } +pub fn get_auth_event_dimensions() -> Vec<NameDescription> { + vec![ + AuthEventDimensions::AuthenticationConnector, + AuthEventDimensions::MessageVersion, + ] + .into_iter() + .map(Into::into) + .collect() +} + pub fn get_refund_dimensions() -> Vec<NameDescription> { RefundDimensions::iter().map(Into::into).collect() } diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 132272f0e49..71d7f80eb7c 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -7,7 +7,7 @@ use masking::Secret; use self::{ active_payments::ActivePaymentsMetrics, api_event::{ApiEventDimensions, ApiEventMetrics}, - auth_events::AuthEventMetrics, + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetrics}, disputes::{DisputeDimensions, DisputeMetrics}, frm::{FrmDimensions, FrmMetrics}, payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics}, @@ -226,6 +226,10 @@ pub struct GetAuthEventMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] + pub group_by_names: Vec<AuthEventDimensions>, + #[serde(default)] + pub filters: AuthEventFilters, + #[serde(default)] pub metrics: HashSet<AuthEventMetrics>, #[serde(default)] pub delta: bool, @@ -509,3 +513,36 @@ pub struct SankeyResponse { pub dispute_status: Option<String>, pub first_attempt: i64, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GetAuthEventFilterRequest { + pub time_range: TimeRange, + #[serde(default)] + pub group_by_names: Vec<AuthEventDimensions>, +} + +#[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct AuthEventFiltersResponse { + pub query_data: Vec<AuthEventFilterValue>, +} + +#[derive(Debug, serde::Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct AuthEventFilterValue { + pub dimension: AuthEventDimensions, + pub values: Vec<String>, +} + +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthEventMetricsResponse<T> { + pub query_data: Vec<T>, + pub meta_data: [AuthEventsAnalyticsMetadata; 1], +} + +#[derive(Debug, serde::Serialize)] +pub struct AuthEventsAnalyticsMetadata { + pub total_error_message_count: Option<u64>, +} diff --git a/crates/api_models/src/analytics/auth_events.rs b/crates/api_models/src/analytics/auth_events.rs index 6f527551348..5c2d4ed2064 100644 --- a/crates/api_models/src/analytics/auth_events.rs +++ b/crates/api_models/src/analytics/auth_events.rs @@ -3,7 +3,23 @@ use std::{ hash::{Hash, Hasher}, }; -use super::NameDescription; +use common_enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; + +use super::{NameDescription, TimeRange}; + +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] +pub struct AuthEventFilters { + #[serde(default)] + pub authentication_status: Vec<AuthenticationStatus>, + #[serde(default)] + pub trans_status: Vec<TransactionStatus>, + #[serde(default)] + pub error_message: Vec<String>, + #[serde(default)] + pub authentication_connector: Vec<AuthenticationConnectors>, + #[serde(default)] + pub message_version: Vec<String>, +} #[derive( Debug, @@ -22,10 +38,13 @@ use super::NameDescription; #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthEventDimensions { - #[serde(rename = "authentication_status")] AuthenticationStatus, + #[strum(serialize = "trans_status")] #[serde(rename = "trans_status")] TransactionStatus, + ErrorMessage, + AuthenticationConnector, + MessageVersion, } #[derive( @@ -51,6 +70,8 @@ pub enum AuthEventMetrics { FrictionlessSuccessCount, ChallengeAttemptCount, ChallengeSuccessCount, + AuthenticationErrorMessage, + AuthenticationFunnel, } #[derive( @@ -79,6 +100,7 @@ pub mod metric_behaviour { pub struct FrictionlessSuccessCount; pub struct ChallengeAttemptCount; pub struct ChallengeSuccessCount; + pub struct AuthenticationErrorMessage; } impl From<AuthEventMetrics> for NameDescription { @@ -90,19 +112,58 @@ impl From<AuthEventMetrics> for NameDescription { } } +impl From<AuthEventDimensions> for NameDescription { + fn from(value: AuthEventDimensions) -> Self { + Self { + name: value.to_string(), + desc: String::new(), + } + } +} + #[derive(Debug, serde::Serialize, Eq)] pub struct AuthEventMetricsBucketIdentifier { - pub time_bucket: Option<String>, + pub authentication_status: Option<AuthenticationStatus>, + pub trans_status: Option<TransactionStatus>, + pub error_message: Option<String>, + pub authentication_connector: Option<AuthenticationConnectors>, + pub message_version: 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 AuthEventMetricsBucketIdentifier { - pub fn new(time_bucket: Option<String>) -> Self { - Self { time_bucket } + #[allow(clippy::too_many_arguments)] + pub fn new( + authentication_status: Option<AuthenticationStatus>, + trans_status: Option<TransactionStatus>, + error_message: Option<String>, + authentication_connector: Option<AuthenticationConnectors>, + message_version: Option<String>, + normalized_time_range: TimeRange, + ) -> Self { + Self { + authentication_status, + trans_status, + error_message, + authentication_connector, + message_version, + time_bucket: normalized_time_range, + start_time: normalized_time_range.start_time, + } } } impl Hash for AuthEventMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { + self.authentication_status.hash(state); + self.trans_status.hash(state); + self.authentication_connector.hash(state); + self.message_version.hash(state); + self.error_message.hash(state); self.time_bucket.hash(state); } } @@ -127,6 +188,8 @@ pub struct AuthEventMetricsBucketValue { pub challenge_success_count: Option<u64>, pub frictionless_flow_count: Option<u64>, pub frictionless_success_count: Option<u64>, + pub error_message_count: Option<u64>, + pub authentication_funnel: Option<u64>, } #[derive(Debug, serde::Serialize)] diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index bf7544f7c01..31b0c1d8dce 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -113,10 +113,12 @@ impl_api_event_type!( GetActivePaymentsMetricRequest, GetSdkEventMetricRequest, GetAuthEventMetricRequest, + GetAuthEventFilterRequest, GetPaymentFiltersRequest, PaymentFiltersResponse, GetRefundFilterRequest, RefundFiltersResponse, + AuthEventFiltersResponse, GetSdkEventFiltersRequest, SdkEventFiltersResponse, ApiLogsRequest, @@ -180,6 +182,13 @@ impl<T> ApiEventMetric for DisputesMetricsResponse<T> { Some(ApiEventsType::Miscellaneous) } } + +impl<T> ApiEventMetric for AuthEventMetricsResponse<T> { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Miscellaneous) + } +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl ApiEventMetric for PaymentMethodIntentConfirmInternal { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index dbbee9764f2..296bdbd9ddc 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -6686,6 +6686,7 @@ impl From<RoleScope> for EntityType { serde::Serialize, serde::Deserialize, Eq, + Hash, PartialEq, ToSchema, strum::Display, diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index deaf84bb009..858c16d052f 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -19,11 +19,11 @@ pub mod routes { GetGlobalSearchRequest, GetSearchRequest, GetSearchRequestWithIndex, SearchIndex, }, AnalyticsRequest, GenerateReportRequest, GetActivePaymentsMetricRequest, - GetApiEventFiltersRequest, GetApiEventMetricRequest, GetAuthEventMetricRequest, - GetDisputeMetricRequest, GetFrmFilterRequest, GetFrmMetricRequest, - GetPaymentFiltersRequest, GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, - GetPaymentMetricRequest, GetRefundFilterRequest, GetRefundMetricRequest, - GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest, + GetApiEventFiltersRequest, GetApiEventMetricRequest, GetAuthEventFilterRequest, + GetAuthEventMetricRequest, GetDisputeMetricRequest, GetFrmFilterRequest, + GetFrmMetricRequest, GetPaymentFiltersRequest, GetPaymentIntentFiltersRequest, + GetPaymentIntentMetricRequest, GetPaymentMetricRequest, GetRefundFilterRequest, + GetRefundMetricRequest, GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest, }; use common_enums::EntityType; use common_utils::types::TimeRange; @@ -106,6 +106,10 @@ pub mod routes { web::resource("metrics/auth_events") .route(web::post().to(get_auth_event_metrics)), ) + .service( + web::resource("filters/auth_events") + .route(web::post().to(get_merchant_auth_events_filters)), + ) .service( web::resource("metrics/frm").route(web::post().to(get_frm_metrics)), ) @@ -1018,6 +1022,34 @@ pub mod routes { .await } + pub async fn get_merchant_auth_events_filters( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<GetAuthEventFilterRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetAuthEventFilters; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req, _| async move { + analytics::auth_events::get_filters( + &state.pool, + req, + auth.merchant_account.get_id(), + ) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::MerchantAnalyticsRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + pub async fn get_org_payment_filters( state: web::Data<AppState>, req: actix_web::HttpRequest,
2025-03-06T14:57:01Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Added support for filters and dimensions for authentication analytics. Filters added: - AuthenticationConnector - MessageVersion Dimensions added: - AuthenticationStatus, - TransactionStatus, - ErrorMessage, - AuthenticationConnector, - MessageVersion, New metrics added: - AuthenticationErrorMessage - AuthenticationFunnel ### 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). --> Get better insights into authentication data. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Hit the curls: #### AuthenticationErrorMessage: ```bash curl --location 'http://localhost:8080/analytics/v1/metrics/auth_events' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWFiNWIxNDEtNjQwOC00YTUyLTk2MjMtNTVhNTgxMTU1M2U4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQwNDE0OTA5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTI3NDY4NSwib3JnX2lkIjoib3JnX1QwSEtYNHYyRGFRT2lHUDVwRk52IiwicHJvZmlsZV9pZCI6InByb19xOWc2ZW1xcGM3YjQxTG83VVhweCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.LIExs1jjG6N5AFu5_S3oiuy77fWF0IbJmNGbK8HHLXI' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2025-02-01T18:30:00Z", "endTime": "2025-02-28T09:22:00Z" }, "source": "BATCH", "timeSeries": { "granularity": "G_ONEDAY" }, "groupByNames": [ "error_message" ], "metrics": [ "authentication_error_message" ], "delta": true } ]' ``` Sample Output: ```json { "queryData": [ { "authentication_count": null, "authentication_attempt_count": null, "authentication_success_count": null, "challenge_flow_count": null, "challenge_attempt_count": null, "challenge_success_count": null, "frictionless_flow_count": null, "frictionless_success_count": null, "error_message_count": 1, "authentication_funnel": null, "authentication_status": null, "trans_status": null, "error_message": "Failed to authenticate", "authentication_connector": null, "message_version": null, "time_range": { "start_time": "2025-02-10T00:00:00.000Z", "end_time": "2025-02-10T23:00:00.000Z" }, "time_bucket": "2025-02-10 00:00:00" }, { "authentication_count": null, "authentication_attempt_count": null, "authentication_success_count": null, "challenge_flow_count": null, "challenge_attempt_count": null, "challenge_success_count": null, "frictionless_flow_count": null, "frictionless_success_count": null, "error_message_count": 1, "authentication_funnel": null, "authentication_status": null, "trans_status": null, "error_message": "Something went wrong", "authentication_connector": null, "message_version": null, "time_range": { "start_time": "2025-02-20T00:00:00.000Z", "end_time": "2025-02-20T23:00:00.000Z" }, "time_bucket": "2025-02-20 00:00:00" } ], "metaData": [ { "total_error_message_count": 2 } ] } ``` #### Authentication Funnel: ```bash curl --location 'http://localhost:8080/analytics/v1/metrics/auth_events' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWFiNWIxNDEtNjQwOC00YTUyLTk2MjMtNTVhNTgxMTU1M2U4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQwNDE0OTA5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTI3NDY4NSwib3JnX2lkIjoib3JnX1QwSEtYNHYyRGFRT2lHUDVwRk52IiwicHJvZmlsZV9pZCI6InByb19xOWc2ZW1xcGM3YjQxTG83VVhweCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.LIExs1jjG6N5AFu5_S3oiuy77fWF0IbJmNGbK8HHLXI' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2025-02-01T18:30:00Z", "endTime": "2025-02-28T09:22:00Z" }, "source": "BATCH", "timeSeries": { "granularity": "G_ONEDAY" }, "filters": { "authentication_status": [ "success", "failed" ] }, "metrics": [ "authentication_funnel" ], "delta": true } ]' ``` Sample Output: ```json { "queryData": [ { "authentication_count": null, "authentication_attempt_count": null, "authentication_success_count": null, "challenge_flow_count": null, "challenge_attempt_count": null, "challenge_success_count": null, "frictionless_flow_count": null, "frictionless_success_count": null, "error_message_count": null, "authentication_funnel": 3, "authentication_status": null, "trans_status": null, "error_message": null, "authentication_connector": null, "message_version": null, "time_range": { "start_time": "2025-02-11T00:00:00.000Z", "end_time": "2025-02-11T23:00:00.000Z" }, "time_bucket": "2025-02-11 00:00:00" }, { "authentication_count": null, "authentication_attempt_count": null, "authentication_success_count": null, "challenge_flow_count": null, "challenge_attempt_count": null, "challenge_success_count": null, "frictionless_flow_count": null, "frictionless_success_count": null, "error_message_count": null, "authentication_funnel": 64, "authentication_status": null, "trans_status": null, "error_message": null, "authentication_connector": null, "message_version": null, "time_range": { "start_time": "2025-02-10T00:00:00.000Z", "end_time": "2025-02-10T23:00:00.000Z" }, "time_bucket": "2025-02-10 00:00:00" }, { "authentication_count": null, "authentication_attempt_count": null, "authentication_success_count": null, "challenge_flow_count": null, "challenge_attempt_count": null, "challenge_success_count": null, "frictionless_flow_count": null, "frictionless_success_count": null, "error_message_count": null, "authentication_funnel": 11, "authentication_status": null, "trans_status": null, "error_message": null, "authentication_connector": null, "message_version": null, "time_range": { "start_time": "2025-02-20T00:00:00.000Z", "end_time": "2025-02-20T23:00:00.000Z" }, "time_bucket": "2025-02-20 00:00:00" } ], "metaData": [ { "total_error_message_count": 0 } ] } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
957a22852522a10378fc06dd30521a3a0c530ee5
957a22852522a10378fc06dd30521a3a0c530ee5
juspay/hyperswitch
juspay__hyperswitch-7460
Bug: fix(postman): nmi manual capture state Previously the manually captured payments through `nmi` connector stayed in processing state after confirming the payment. Now, it goes to `requires_capture` state. So, the necessary changes are required.
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/event.test.js index eedc017da1b..df0080dff2f 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/event.test.js +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/event.test.js @@ -63,12 +63,12 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "processing" for "status" +// Response body should have value "requires_capture" for "status" if (jsonData?.status) { pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'processing'", + "[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_capture'", function () { - pm.expect(jsonData.status).to.eql("processing"); + pm.expect(jsonData.status).to.eql("requires_capture"); }, ); } diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/event.test.js index e13c466cc26..2043a80f570 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/event.test.js +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/event.test.js @@ -65,9 +65,9 @@ if (jsonData?.client_secret) { // Response body should have value "requires_capture" for "status" if (jsonData?.status) { pm.test( - "[POST]::/payments - Content check if value for 'status' matches 'processing'", + "[POST]::/payments - Content check if value for 'status' matches 'requires_capture'", function () { - pm.expect(jsonData.status).to.eql("processing"); + pm.expect(jsonData.status).to.eql("requires_capture"); }, ); } diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/event.test.js index cee98b477bd..d683186aa00 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/event.test.js +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/event.test.js @@ -63,9 +63,9 @@ if (jsonData?.client_secret) { // Response body should have value "requires_capture" for "status" if (jsonData?.status) { pm.test( - "[POST]::/payments - Content check if value for 'status' matches 'processing'", + "[POST]::/payments - Content check if value for 'status' matches 'requires_capture'", function () { - pm.expect(jsonData.status).to.eql("processing"); + pm.expect(jsonData.status).to.eql("requires_capture"); }, ); } diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/event.test.js index d03ed16ff56..b7a6220b0f1 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/event.test.js +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/event.test.js @@ -20,10 +20,10 @@ pm.test("[POST]::/payments/:id/confirm - Response has JSON Body", function () { pm.response.to.have.jsonBody(); }); -//// Response body should have value "processing" for "status" +//// Response body should have value "requires_capture" for "status" if (jsonData?.status) { -pm.test("[POST]::/payments - Content check if value for 'status' matches 'processing'", function() { - pm.expect(jsonData.status).to.eql("processing"); +pm.test("[POST]::/payments - Content check if value for 'status' matches 'requires_capture'", function() { + pm.expect(jsonData.status).to.eql("requires_capture"); })}; diff --git a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario3-Capture greater amount/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario3-Capture greater amount/Payments - Create/event.test.js index cee98b477bd..d683186aa00 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario3-Capture greater amount/Payments - Create/event.test.js +++ b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario3-Capture greater amount/Payments - Create/event.test.js @@ -63,9 +63,9 @@ if (jsonData?.client_secret) { // Response body should have value "requires_capture" for "status" if (jsonData?.status) { pm.test( - "[POST]::/payments - Content check if value for 'status' matches 'processing'", + "[POST]::/payments - Content check if value for 'status' matches 'requires_capture'", function () { - pm.expect(jsonData.status).to.eql("processing"); + pm.expect(jsonData.status).to.eql("requires_capture"); }, ); }
2025-03-07T10:12:51Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> ### 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 Postman Testcases for `nmi` connector was failing in case of Manual Capture ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> _**Before**_ <img width="500" alt="image" src="https://github.com/user-attachments/assets/b22d850f-ad64-4fce-a7c2-26a946db3c52" /> <details> <summary>Changes</summary> - Previously the manually captured payments through `nmi` connector stayed in `processing` state after confirming the payment. But now, it goes to `requires_capture` state. So, making the necessary changes. </details> _**After**_ <img width="500" alt="image" src="https://github.com/user-attachments/assets/e31e373a-158c-42e3-a324-e5f55827300a" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
15ad6da0793be4bc149ae2e92f4805735be8712a
15ad6da0793be4bc149ae2e92f4805735be8712a
juspay/hyperswitch
juspay__hyperswitch-7413
Bug: [FEATURE] Add support for Google Pay Mandates in `Authorize.Net` At present, `Authorize.Net` connector only support normal payments via Google Pay. We need to add support for making Mandate payments via Google Pay. Just modify the `transformers.rs` and `authorizedotnet.rs` file to add support to it.
diff --git a/config/config.example.toml b/config/config.example.toml index a52f7486cf5..448d65bb6ee 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -474,9 +474,9 @@ bank_debit.bacs = { connector_list = "adyen" } bank_debit.sepa = { connector_list = "gocardless,adyen" } # 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,globalpay" } -wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon,bankofamerica" } +wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon,bankofamerica,authorizedotnet" } wallet.samsung_pay = { connector_list = "cybersource" } -wallet.google_pay = { connector_list = "bankofamerica" } +wallet.google_pay = { connector_list = "bankofamerica,authorizedotnet" } bank_redirect.giropay = { connector_list = "globalpay" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 1feedf8f1cd..1f4a8dd3b81 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -177,9 +177,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal" card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal" pay_later.klarna.connector_list = "adyen" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet" +wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet" wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 712df253a94..98d3b4d31ec 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -177,9 +177,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal" card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal" pay_later.klarna.connector_list = "adyen" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet" +wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet" wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index a9f20670ca7..d9d98beab75 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -177,9 +177,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal" card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal" pay_later.klarna.connector_list = "adyen" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet" +wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet" wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" diff --git a/config/development.toml b/config/development.toml index 77a38f9d6e8..a21a5f090b9 100644 --- a/config/development.toml +++ b/config/development.toml @@ -739,9 +739,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal" card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal" pay_later.klarna.connector_list = "adyen" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet" +wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet" wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 12242f485b7..4c91078b490 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -588,8 +588,8 @@ adyen = { banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,hal [mandates.supported_payment_methods] pay_later.klarna = { connector_list = "adyen" } -wallet.google_pay = { connector_list = "stripe,adyen,bankofamerica" } -wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon,bankofamerica" } +wallet.google_pay = { connector_list = "stripe,adyen,bankofamerica,authorizedotnet" } +wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon,bankofamerica,authorizedotnet" } wallet.samsung_pay = { connector_list = "cybersource" } wallet.paypal = { connector_list = "adyen" } card.credit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica" } diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs index 29af20a9570..3bd39fd38b5 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs @@ -117,7 +117,11 @@ impl ConnectorValidation for Authorizedotnet { pm_type: Option<enums::PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { - let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]); + let mandate_supported_pmd = std::collections::HashSet::from([ + PaymentMethodDataType::Card, + PaymentMethodDataType::GooglePay, + PaymentMethodDataType::ApplePay, + ]); connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } } diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs index 626d6d76599..d7f50aa7405 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs @@ -31,8 +31,8 @@ use serde_json::Value; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ - self, CardData, ForeignTryFrom, PaymentsSyncRequestData, RefundsRequestData, - RouterData as OtherRouterData, WalletData as OtherWalletData, + self, CardData, ForeignTryFrom, PaymentsAuthorizeRequestData, PaymentsSyncRequestData, + RefundsRequestData, RouterData as OtherRouterData, WalletData as OtherWalletData, }, }; @@ -376,8 +376,92 @@ impl TryFrom<&SetupMandateRouterData> for CreateCustomerProfileRequest { }, }) } + PaymentMethodData::Wallet(wallet_data) => match wallet_data { + WalletData::GooglePay(_) => { + 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 { + // 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::OpaqueData(WalletDetails { + data_descriptor: WalletMethod::Googlepay, + data_value: Secret::new( + wallet_data.get_encoded_wallet_token()?, + ), + }), + }, + }, + validation_mode, + }, + }) + } + WalletData::ApplePay(applepay_token) => { + 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 { + // 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::OpaqueData(WalletDetails { + data_descriptor: WalletMethod::Applepay, + data_value: Secret::new( + applepay_token.payment_data.clone(), + ), + }), + }, + }, + validation_mode, + }, + }) + } + WalletData::AliPayQr(_) + | WalletData::AliPayRedirect(_) + | WalletData::AliPayHkRedirect(_) + | WalletData::AmazonPayRedirect(_) + | WalletData::MomoRedirect(_) + | WalletData::KakaoPayRedirect(_) + | WalletData::GoPayRedirect(_) + | WalletData::GcashRedirect(_) + | WalletData::ApplePayRedirect(_) + | WalletData::ApplePayThirdPartySdk(_) + | WalletData::DanaRedirect {} + | WalletData::GooglePayRedirect(_) + | WalletData::GooglePayThirdPartySdk(_) + | WalletData::MbWayRedirect(_) + | WalletData::MobilePayRedirect(_) + | WalletData::PaypalRedirect(_) + | WalletData::PaypalSdk(_) + | WalletData::Paze(_) + | WalletData::SamsungPay(_) + | WalletData::TwintRedirect {} + | WalletData::VippsRedirect {} + | WalletData::TouchNGoRedirect(_) + | WalletData::WeChatPayRedirect(_) + | WalletData::WeChatPayQr(_) + | WalletData::CashappQr(_) + | WalletData::SwishQr(_) + | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("authorizedotnet"), + ))?, + }, PaymentMethodData::CardRedirect(_) - | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) @@ -748,41 +832,24 @@ impl &Card, ), ) -> Result<Self, Self::Error> { - let (profile, customer) = - if item - .router_data - .request - .setup_future_usage - .is_some_and(|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() - .is_some_and(|mandate_details| { - mandate_details.customer_acceptance.is_some() - })) - { - ( - Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails { - create_profile: true, - })), - Some(CustomerDetails { - //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 { - (None, None) - }; + let (profile, customer) = if item.router_data.request.is_mandate_payment() { + ( + Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails { + create_profile: true, + })), + Some(CustomerDetails { + //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 { + (None, None) + }; Ok(Self { transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, amount: item.amount, @@ -841,6 +908,23 @@ impl &WalletData, ), ) -> Result<Self, Self::Error> { + let (profile, customer) = if item.router_data.request.is_mandate_payment() { + ( + Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails { + create_profile: true, + })), + Some(CustomerDetails { + 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 { + (None, None) + }; + Ok(Self { transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, amount: item.amount, @@ -849,11 +933,11 @@ impl wallet_data, &item.router_data.request.complete_authorize_url, )?), - profile: None, + profile, order: Order { description: item.router_data.connector_request_reference_id.clone(), }, - customer: None, + customer, bill_to: item .router_data .get_optional_billing() diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index a85ca141281..f575a22f2e0 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -279,8 +279,8 @@ cards = [ ] [pm_filters.dlocal] -credit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"} -debit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"} +credit = { country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW" } +debit = { country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW" } [pm_filters.mollie] credit = { not_available_flows = { capture_method = "manual" } } @@ -386,9 +386,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal" card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal" pay_later.klarna.connector_list = "adyen" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet" +wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet" wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen"
2025-03-03T17:54:29Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds mandates support for Google Pay and Apple Pay Payment Method via `Authorize.Net` connector. It also supports Zero Auth Mandates. ### 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). --> First of all, it is a merchant requirement and also, `Authorize.Net` previously did not have mandates support. So we were throwing `501` every time some one tried to create a mandate payment via Google Pay or Apple Pay. Also closes https://github.com/juspay/hyperswitch/issues/7413 ## 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)? --> **Google Pay (confirm: `true`)** <details> <summary>0. Generate Token</summary> Generated with jsfiddle. A snippet from it has been attached below: ```js paymentToken = paymentData.paymentMethodData.tokenizationData.token; // Stringified payment token is passed in the request console.log("STRINGIFIED_TOKEN: ", JSON.stringify(paymentToken)); ``` </details> **Normal Payment** <details> <summary>1. Google Pay Payment Create</summary> ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data-raw '{ "amount": 7000, "currency": "USD", "confirm": true, "business_country":"US", "business_label":"default", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_data": { "wallet": { "google_pay": { "description": "Visa •••• 1111", "tokenization_data": { "type": "PAYMENT_GATEWAY", "token": "{\"signature\":\"MEYCIQD4IOPmA38TEwyc2MydkgUkk/qVM2sMCS7EmUPNP2NpIAIhAJKXI2JdZSjQRBEAZ6LNmXVPv7j80i9iuTeAWM4+f/2Y\",\"protocolVersion\":\"ECv1\",\"signedMessage\":\"{\\\"encryptedMessage\\\":\\\"HUriM67+LViEdMAtrwfcyxiOuQIEAI9WKzJYZ6AqAh8Zx4c673vNN7ni/tddZLoID1Jv1ly1a3brPvWtvGLaoshh0BKqKRX/talksIBBQceTUbnPYVwC4vUK+PakLCGK1gOAmfaMnoHVmiKDZQs5Lnu1zJ1xww2Wm0M/YzGTx12njDmLuVsA2qU8fgkQiW6aJnPePiA+4Rx6ykDI1mDcALoU+gmSftSBkibAY9igkpmJkS6SCxTZ/5ihwXayBZTaGWBGKVIU2CrwwbECIWvaldvlWaHC0T/Iual1o4zAIsmbeqIejYa2TZtCMhiLI3kX+3FaS4LrcTn5/RyjD9ZurVXfdXJ/2XPhSMzHj14RE0Axf+ZabZsf9UxZzGVtsBw2kfCnSNZ9v2BEjPNxwGy4w3giumUHlqaQWv5RGg\\\\u003d\\\\u003d\\\",\\\"ephemeralPublicKey\\\":\\\"BJOyfPwG44zKn/eIEAO9On1Huuo+5aiwAolhqoDObl3yX8tQrjwtMk3eTUJOfuKG+fkGs5IIgYPARlpt/SEwOos\\\\u003d\\\",\\\"tag\\\":\\\"nKgFcEDO0LGzngqIsx/myAI8+TshLBvKkNxn8HdoBCw\\\\u003d\\\"}\"}" }, "type": "CARD", "info": { "card_network": "VISA", "card_details": "1111" } } } } }' ``` ```json { "payment_id": "pay_Ycjdrhh70tgbCzFUovom", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "succeeded", "amount": 7000, "net_amount": 7000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 7000, "connector": "authorizedotnet", "client_secret": "pay_Ycjdrhh70tgbCzFUovom_secret_pGJFgpSIthkYEqIryDYm", "created": "2025-03-04T10:28:48.398Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "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": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "google_pay": { "last4": "1111", "card_network": "VISA", "type": "CARD" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "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": null, "email": null }, "order_details": null, "email": "[email protected]", "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": "google_pay", "connector_label": "authorizedotnet_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1741084128, "expires": 1741087728, "secret": "epk_cbc6c778677e4a1988dea5ff96be7a49" }, "manual_retry_allowed": false, "connector_transaction_id": "0", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "0", "payment_link": null, "profile_id": "pro_oHA88TJXvZtdcosjZFkq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_C6aMBB2E0kNICU09mSCP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-04T10:43:48.398Z", "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": "2025-03-04T10:28:50.381Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null } ``` </details> **Mandate Payment** Prior to make 0 Auth mandate, make sure that the Test Mode is turned off on connector dashboard and Live mode is turned on: ![image](https://github.com/user-attachments/assets/c9867570-f9eb-4b7f-bd40-560e25be0d50) If not, you'll be greeted with below mentioned error: ```log 2025-03-04T11:47:15.392668Z ERROR router::services::api: error: {"error":{"type":"invalid_request","message":"Payment failed during authorization with connector. Retry payment","code":"CE_01"}} ├╴at crates/router/src/services/api.rs:790:14 │ ├─▶ {"error":{"type":"processing_error","code":"CE_01","message":"Payment failed during authorization with connector. Retry payment","data":null}} │ ╰╴at crates/router/src/core/errors/utils.rs:418:17 │ ├─▶ Failed to deserialize connector response │ ╰╴at crates/router/src/connector/authorizedotnet.rs:199:14 │ ├─▶ Failed to parse struct: AuthorizedotnetPaymentsResponse │ ├╴at /orca/crates/common_utils/src/ext_traits.rs:175:14 │ ╰╴Unable to parse router::connector::authorizedotnet::transformers::AuthorizedotnetSetupMandateResponse from bytes b"{\"messages\":{\"resultCode\":\"Error\",\"message\":[{\"code\":\"E00009\",\"text\":\"The payment gateway account is in Test Mode. The request cannot be processed.\"}]}}" │ ╰─▶ missing field `customerPaymentProfileIdList` at line 1 column 152 ╰╴at /orca/crates/common_utils/src/ext_traits.rs:175:14 ``` <details> <summary>2. 0 Auth mandate Google Pay Payment Create (CIT)</summary> ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": true, "business_country":"US", "business_label":"default", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "off_session", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 8000, "currency": "USD" } } }, "payment_type": "setup_mandate", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_data": { "wallet": { "google_pay": { "description": "Visa •••• 1111", "tokenization_data": { "type": "PAYMENT_GATEWAY", "token": "{\"signature\":\"MEYCIQDXSxykX6QsEf6OfbBt6JeZRV0fKMfdGqLMWW09SVTIiQIhAL1AQ4oCeX09uK//SZotBysxb1VJocA9UFjRj3E2f90+\",\"protocolVersion\":\"ECv1\",\"signedMessage\":\"{\\\"encryptedMessage\\\":\\\"j/yT6NHHmADowqcEBoC58j99OyIEqOIJc6uWFwXAV2duIjI838Rl7U+4XYjpKfSViaNhPoW9KJ8rAKy04XAVxx9iEM4sgIeP3cgZXq5T28ivWLbGiKI+iVBvgkd6TFq9OCWvo2WD+xhg0gZshkKmuq50QzELQuoNeIbmgehXQgD2QizIcxfr/1bKLWYU46DsR+nbN/I8L8of6TbbHsTlyN3A36+uq24uQGMoWloWj9A6ZEGbiPox9ljdZiYTfqXEkBd/LoRCYp8yuDPrGFOYBCCWq7tZ8TR8EBWOvAzfWpwQLMBpuFR+P22S2fM3lvbcJoHgMimsAlCRmcdS9G/knoV32KhkVLsMz3zMvqXPMRxGa9yxbHbopYSPpu8HoXZMgv867GtMHguzqNkSas0r+WFg3GAR/ZxKnwK7sQ\\\\u003d\\\\u003d\\\",\\\"ephemeralPublicKey\\\":\\\"BAkY6NwItLszcKq2mX4tgTwqYpP1bJkSQ5nJhWPEaPE7OhlSMMNjikCwRFQqq1qEyvDJjiNopuHmEwUTMDY5GRE\\\\u003d\\\",\\\"tag\\\":\\\"yRNDiUqscYJDSzhe3NozPDftfR6MTy83iui6Hru/F3g\\\\u003d\\\"}\"}" }, "type": "CARD", "info": { "card_network": "VISA", "card_details": "1111" } } } } }' ``` ```json { "payment_id": "pay_mIpw378Mk8zHlAjiMMMP", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "succeeded", "amount": 0, "net_amount": 0, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_mIpw378Mk8zHlAjiMMMP_secret_ifCWgJ3idLvIOSNl3diR", "created": "2025-03-04T11:51:57.766Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": "man_P4lMkUEfHZL1so7BT7vL", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 8000, "currency": "USD", "start_date": null, "end_date": null, "metadata": null } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "google_pay": { "last4": "1111", "card_network": "VISA", "type": "CARD" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "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": null, "email": null }, "order_details": null, "email": "[email protected]", "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": "google_pay", "connector_label": "authorizedotnet_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1741089117, "expires": 1741092717, "secret": "epk_14f46a89c0324250855f4ffdb66b6393" }, "manual_retry_allowed": false, "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_oHA88TJXvZtdcosjZFkq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_C6aMBB2E0kNICU09mSCP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-04T12:06:57.766Z", "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": "pm_uiXIl346CEL1MNsb1Itz", "payment_method_status": "active", "updated": "2025-03-04T11:51:59.981Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "929556579-928947232", "card_discovery": null } ``` </details> <details> <summary>3. 0 Auth mandate Google Pay Payment Create (MIT)</summary> ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data '{ "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "StripeCustomer", "client_secret": "pay_Yjz0to0D2SWrvMnu9YYJ_secret_dww4J2IkgUS375Qp14DD", "recurring_details": { "type": "payment_method_id", "data": "pm_uiXIl346CEL1MNsb1Itz" }, "off_session": true, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "payment_method": "wallet", "payment_method_type": "google_pay", "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" } } }' ``` ```json { "payment_id": "pay_Yjz0to0D2SWrvMnu9YYJ", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "authorizedotnet", "client_secret": "pay_Yjz0to0D2SWrvMnu9YYJ_secret_dww4J2IkgUS375Qp14DD", "created": "2025-03-04T12:41:24.421Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "google_pay": { "last4": "1111", "card_network": "VISA", "type": "CARD" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "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": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "google_pay", "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": 1741092084, "expires": 1741095684, "secret": "epk_33afe25ebfdb438099126de2170ac062" }, "manual_retry_allowed": false, "connector_transaction_id": "120058112387", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "120058112387", "payment_link": null, "profile_id": "pro_oHA88TJXvZtdcosjZFkq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_C6aMBB2E0kNICU09mSCP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-04T12:56:24.421Z", "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": "pm_uiXIl346CEL1MNsb1Itz", "payment_method_status": "active", "updated": "2025-03-04T12:41:26.065Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "929556579-928947232", "card_discovery": null } ``` </details> ____ **Google Pay (confirm: `false`)** <details> <summary>0. Generate Token</summary> Generated with jsfiddle. A snippet from it has been attached below: ```js paymentToken = paymentData.paymentMethodData.tokenizationData.token; // Stringified payment token is passed in the request console.log("STRINGIFIED_TOKEN: ", JSON.stringify(paymentToken)); ``` </details> **Normal Payment** <details> <summary>1. Google Pay Payment Create</summary> Create a payment with Google Pay as payment method: ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data-raw '{ "amount": 1000, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "[email protected]", "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", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "payment_id": "pay_bfeoigMGZuwS8e93al9S", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "requires_payment_method", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_bfeoigMGZuwS8e93al9S_secret_YSFWpewZeiZM981x31QF", "created": "2025-03-04T16:17:55.833Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "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": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "[email protected]", "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": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1741105075, "expires": 1741108675, "secret": "epk_19957b6804bd446fa6fd0e64e110bb38" }, "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_oHA88TJXvZtdcosjZFkq", "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": "2025-03-04T16:32:55.833Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-04T16:17:55.849Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null } ``` Confirm the payment with the payment tokenizated data in the previous step: ```curl curl --location 'http://Localhost:8080/payments/pay_i0kBWoWf2WhaxDmCb0Kr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data '{ "confirm": true, "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_data": { "wallet": { "google_pay": { "description": "Visa •••• 1111", "tokenization_data": { "type": "PAYMENT_GATEWAY", "token": "{\"signature\":\"MEUCIQCwtiXZxhnLtPm8HSpM4nes1xsgMGUXj/mejNJdHdYSwAIgWS/Rpx42PBTsmFB0Ypw3WFiSkHhJIKfhDCZ4D1EJe2g\\u003d\",\"protocolVersion\":\"ECv1\",\"signedMessage\":\"{\\\"encryptedMessage\\\":\\\"HqOYpkcOVnkNMjHAAGQnNU82ZNzREewVB6cJNusCjSK8q5C/wumXuatl+8Hs78m/GD1km10onXLCiCkLs429taWyCpMKPMdeZH2aGU5S347RCRzn+hTCxHn0Erh2RQeyUBQ4/hdekdLhg53fLZOm0ORXqc/2cz9m98c0Gdjqjc/Ladhm2+r5WL1AEIbHwGZVVnBB1bzgbL8El5aF6FhdG3iAltVDIzjCUvsX2WXP+vxCXRtwE+xtyN3iUcCxLSshoPDkWEFcmT3aTTlfk6ss9iU6b0KDo2fWDk3PAQKqbQeog0QiWNSZgACqhtTKfV21JxfozlMZ5J6Z/7hROkENHLLNstQa+NeOls0Q7g9f0AvbwkpvF401CXa+jvKgUWnwJ4QTmIt5ogfOUDihK/A54U20LLNxzHZ9Ts5kdw\\\\u003d\\\\u003d\\\",\\\"ephemeralPublicKey\\\":\\\"BLg8yDGYj+1Iu6bNXK+gcvGdDpfha252FT/yzqrTA37WMuXgoEHoq6dOzDmbwORV5x25Z+TiwourpASRgMEDqw4\\\\u003d\\\",\\\"tag\\\":\\\"lshmH3K28uQMBSsvRlYHEeH77WZWV6cplNfdNegWEZY\\\\u003d\\\"}\"}" }, "type": "CARD", "info": { "card_network": "VISA", "card_details": "1111" } } } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "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" } } }' ``` ```json { "payment_id": "pay_bfeoigMGZuwS8e93al9S", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "authorizedotnet", "client_secret": "pay_bfeoigMGZuwS8e93al9S_secret_YSFWpewZeiZM981x31QF", "created": "2025-03-04T16:17:55.833Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "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": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "google_pay": { "last4": "1111", "card_network": "VISA", "type": "CARD" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "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": null, "email": null }, "order_details": null, "email": "[email protected]", "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": "google_pay", "connector_label": "authorizedotnet_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "120058141907", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "120058141907", "payment_link": null, "profile_id": "pro_oHA88TJXvZtdcosjZFkq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_C6aMBB2E0kNICU09mSCP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-04T16:32:55.833Z", "fingerprint": null, "browser_info": { "os_type": null, "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "os_version": null, "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, "device_model": null, "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, "accept_language": "en", "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-04T16:17:59.047Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null } ``` </details> **Mandate Payment** <details> <summary>2. 0 Auth mandate Google Pay Payment Create (CIT)</summary> Create a payment with Google Pay as payment method: ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "payment_id": "pay_i0kBWoWf2WhaxDmCb0Kr", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "requires_payment_method", "amount": 0, "net_amount": 0, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_i0kBWoWf2WhaxDmCb0Kr_secret_X9DDaLKrgZ3EnuGBeGVq", "created": "2025-03-04T17:07:43.928Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": "John Doe", "email": "[email protected]", "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": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "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": null, "connector_label": null, "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": 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_oHA88TJXvZtdcosjZFkq", "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": "2025-03-04T17:22:43.928Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-04T17:07:43.934Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null } ``` Confirm the payment with the payment tokenizated data in the previous step: ```curl curl --location 'http://Localhost:8080/payments/pay_i0kBWoWf2WhaxDmCb0Kr/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data '{ "confirm": true, "payment_type": "setup_mandate", "setup_future_usage": "off_session", "customer_id": "userId", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 8000, "currency": "USD" } } }, "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_data": { "wallet": { "google_pay": { "description": "Visa •••• 1111", "tokenization_data": { "type": "PAYMENT_GATEWAY", "token": "{\"signature\":\"MEYCIQDiQ33RYZBOIPG/gJccPcESROy/aiC1WvtTcIDd53EXeAIhAJS6t5bnsO36+RAR1vEIFAgofOjftLDdvIlRNiQILbYO\",\"protocolVersion\":\"ECv1\",\"signedMessage\":\"{\\\"encryptedMessage\\\":\\\"H9KoqlToBs0ulMI0MA4yTjYW+ha9iuwkSBnG/nvoYSJtDsAs+LiESg9gd9ucGvVYm2YO3ZBTFFIFjF+1+jeITmVGZ8H8n/zoBxHQtzAUuvxSLdPIE1hGgLYDApvX9iZBXQ/BDFbnPCWc5vza/OMHzeSbXAv3xa/5AOEFIQqcsSXymfvNGSkObHAOOl8EYbWV3+trYhs7jqUU92SMYTytqepubq6fRGH3ShaCC1wh2GiAs3wyldbVLCzAXQWwpg0D+YtUUCWIrb6/le09FTyIvZILdZZYCV8en5AzLPaeV24g8JzSq9n4iVlEIMk2Z5XOn2iQbh+czSjEaayyasBs1iwcSvmlsqwA5MjOZOeL6NLEltqX+UylpZfzozwjn6oYfJsOuRwFkW2Bu13jXIo02DS24GVuh17FErvIeQ\\\\u003d\\\\u003d\\\",\\\"ephemeralPublicKey\\\":\\\"BJuTS/Sz6nreFjQE6KCvF8LtbKc2+jUrZZdvd1euYamxps5s+cvCdosar/uHPWRKgUFuNGrwj262aFw85gOFxNQ\\\\u003d\\\",\\\"tag\\\":\\\"vXk0kI20KevUYBEjuXFN6k1U91NEeGx/trlcXG2r3B0\\\\u003d\\\"}\"}" }, "type": "CARD", "info": { "card_network": "VISA", "card_details": "1111" } } } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "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" } } }' ``` ```json { "payment_id": "pay_8lXtsxjVVnXyW3qYwwGL", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "succeeded", "amount": 0, "net_amount": 0, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_8lXtsxjVVnXyW3qYwwGL_secret_vV4VAArRJGYOeB1b76nx", "created": "2025-03-04T17:04:40.633Z", "currency": "USD", "customer_id": "userId", "customer": { "id": "userId", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": "man_7Kl62g9g2ddIAmINxRdB", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 8000, "currency": "USD", "start_date": null, "end_date": null, "metadata": null } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "google_pay": { "last4": "1111", "card_network": "VISA", "type": "CARD" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "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": null, "email": null }, "order_details": null, "email": "[email protected]", "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": "google_pay", "connector_label": "authorizedotnet_US_default", "business_country": "US", "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": { "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_oHA88TJXvZtdcosjZFkq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_C6aMBB2E0kNICU09mSCP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-04T17:19:40.633Z", "fingerprint": null, "browser_info": { "os_type": null, "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "os_version": null, "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, "device_model": null, "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, "accept_language": "en", "java_script_enabled": true }, "payment_method_id": "pm_Y5eD5ietWpQzEP4acuJp", "payment_method_status": "active", "updated": "2025-03-04T17:04:45.377Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "929566202-928957413", "card_discovery": null } ``` </details> <details> <summary>3. 0 Auth mandate Google Pay Payment Create (MIT)</summary> Create + Confirm: ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data '{ "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "userId", "client_secret": "pay_Gfr2ciHSGx2abiThwEeb_secret_RCNmYv7Vm6YA915Kj2fR", "recurring_details": { "type": "payment_method_id", "data": "pm_Y5eD5ietWpQzEP4acuJp" }, "off_session": true, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "payment_method": "wallet", "payment_method_type": "google_pay", "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" } } }' ``` ```json { "payment_id": "pay_Gfr2ciHSGx2abiThwEeb", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "authorizedotnet", "client_secret": "pay_Gfr2ciHSGx2abiThwEeb_secret_RCNmYv7Vm6YA915Kj2fR", "created": "2025-03-04T17:12:50.614Z", "currency": "USD", "customer_id": "userId", "customer": { "id": "userId", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "google_pay": { "last4": "1111", "card_network": "VISA", "type": "CARD" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "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": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "google_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "userId", "created_at": 1741108370, "expires": 1741111970, "secret": "epk_9d2e899d1aae4a1eb19730fadd7cd51a" }, "manual_retry_allowed": false, "connector_transaction_id": "120058147194", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "120058147194", "payment_link": null, "profile_id": "pro_oHA88TJXvZtdcosjZFkq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_C6aMBB2E0kNICU09mSCP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-04T17:27:50.614Z", "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": "pm_Y5eD5ietWpQzEP4acuJp", "payment_method_status": "active", "updated": "2025-03-04T17:12:52.243Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "929566110-928957293", "card_discovery": null } ``` </details> ____ **Apple Pay (confirm: `true`)** **Normal Payment** <details> <summary>0. Apple Pay Payment Create</summary> ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data '{ "amount": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "StripeCustomer", "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "eyJkYXRhIjoiRWQ0UjZYYzVuTk85ZjVZZHc2Z0RVTzlZRE9qSlpxdFg4ME9acEtVNWxNMFNVSU9xbEEvdDU3TDNyV09mNHNTZjZqaGIvKzhiZXFvNFlCM21wU0U5emUrZzAyY0w2S1hOaWlGN2pqbE81eC9FOFFYWW0vRjNNK2lJdmtrcVlzYzBmZWlLandzSkI3SGFoOWJpUW5oOFhJQ2dpREhUSXpZcFIwaUlyVi9rdjFSbGxGT21NNlZDQkM3QVhhenhqUTJ4NEtOVzVIZUw1c2lkdHhia3ZsS2xpa1ZDeloxK2kzYjcwaEw2ZUFlamVsUno3UlEyLzNDbTVScVVqTWZnaHMvd25PVUNZb280UGVwN1BUdHdXdXdid3VMV3lkM0ZRYzdMMjlIcE5STVhCckFFd1RLN2RMTjdTc1VGSGczaTF6N0kxeVM1N1FjQ0d1aGo2dGR6clNOWW1PRmk2Nm03NzZ4M3VVc2kwM3hwdlU2bGdjMVlneUFnT2VSelBlcTRNL0Z4dzU4SlZXVGxYdnY4M09ibXJPbzZrVk0vbDJLRlRZSEszK0hjL2Y1SEZhST0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK1F3Z2dPTG9BTUNBUUlDQ0ZuWW9ieXE5T1BOTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlNVEEwTWpBeE9UTTNNREJhRncweU5qQTBNVGt4T1RNMk5UbGFNR0l4S0RBbUJnTlZCQU1NSDJWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVk5CVGtSQ1QxZ3hGREFTQmdOVkJBc01DMmxQVXlCVGVYTjBaVzF6TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekJaTUJNR0J5cUdTTTQ5QWdFR0NDcUdTTTQ5QXdFSEEwSUFCSUl3L2F2RG5QZGVJQ3hRMlp0RkV1WTM0cWtCM1d5ejRMSE5TMUpubVBqUFRyM29HaVdvd2g1TU05M09qaXFXd3Zhdm9aTURSY1RvZWtRbXpwVWJFcFdqZ2dJUk1JSUNEVEFNQmdOVkhSTUJBZjhFQWpBQU1COEdBMVVkSXdRWU1CYUFGQ1B5U2NSUGsrVHZKK2JFOWloc1A2SzcvUzVMTUVVR0NDc0dBUVVGQndFQkJEa3dOekExQmdnckJnRUZCUWN3QVlZcGFIUjBjRG92TDI5amMzQXVZWEJ3YkdVdVkyOXRMMjlqYzNBd05DMWhjSEJzWldGcFkyRXpNREl3Z2dFZEJnTlZIU0FFZ2dFVU1JSUJFRENDQVF3R0NTcUdTSWIzWTJRRkFUQ0IvakNCd3dZSUt3WUJCUVVIQWdJd2diWU1nYk5TWld4cFlXNWpaU0J2YmlCMGFHbHpJR05sY25ScFptbGpZWFJsSUdKNUlHRnVlU0J3WVhKMGVTQmhjM04xYldWeklHRmpZMlZ3ZEdGdVkyVWdiMllnZEdobElIUm9aVzRnWVhCd2JHbGpZV0pzWlNCemRHRnVaR0Z5WkNCMFpYSnRjeUJoYm1RZ1kyOXVaR2wwYVc5dWN5QnZaaUIxYzJVc0lHTmxjblJwWm1sallYUmxJSEJ2YkdsamVTQmhibVFnWTJWeWRHbG1hV05oZEdsdmJpQndjbUZqZEdsalpTQnpkR0YwWlcxbGJuUnpMakEyQmdnckJnRUZCUWNDQVJZcWFIUjBjRG92TDNkM2R5NWhjSEJzWlM1amIyMHZZMlZ5ZEdsbWFXTmhkR1ZoZFhSb2IzSnBkSGt2TURRR0ExVWRId1F0TUNzd0thQW5vQ1dHSTJoMGRIQTZMeTlqY213dVlYQndiR1V1WTI5dEwyRndjR3hsWVdsallUTXVZM0pzTUIwR0ExVWREZ1FXQkJRQ0pEQUxtdTd0UmpHWHBLWmFLWjVDY1lJY1JUQU9CZ05WSFE4QkFmOEVCQU1DQjRBd0R3WUpLb1pJaHZkalpBWWRCQUlGQURBS0JnZ3Foa2pPUFFRREFnTkhBREJFQWlCMG9iTWsyMEpKUXczVEoweFFkTVNBalpvZlNBNDZoY1hCTmlWbU1sKzhvd0lnYVRhUVU2djFDMXBTK2ZZQVRjV0tyV3hRcDlZSWFEZVE0S2M2MEI1SzJZRXdnZ0x1TUlJQ2RhQURBZ0VDQWdoSmJTKy9PcGphbHpBS0JnZ3Foa2pPUFFRREFqQm5NUnN3R1FZRFZRUUREQkpCY0hCc1pTQlNiMjkwSUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHhOREExTURZeU16UTJNekJhRncweU9UQTFNRFl5TXpRMk16QmFNSG94TGpBc0JnTlZCQU1NSlVGd2NHeGxJRUZ3Y0d4cFkyRjBhVzl1SUVsdWRHVm5jbUYwYVc5dUlFTkJJQzBnUnpNeEpqQWtCZ05WQkFzTUhVRndjR3hsSUVObGNuUnBabWxqWVhScGIyNGdRWFYwYUc5eWFYUjVNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJQQVhFWVFaMTJTRjFScGVKWUVIZHVpQW91L2VlNjVONEkzOFM1UGhNMWJWWmxzMXJpTFFsM1lOSWs1N3VnajlkaGZPaU10MnUyWnd2c2pvS1lUL1ZFV2pnZmN3Z2ZRd1JnWUlLd1lCQlFVSEFRRUVPakE0TURZR0NDc0dBUVVGQnpBQmhpcG9kSFJ3T2k4dmIyTnpjQzVoY0hCc1pTNWpiMjB2YjJOemNEQTBMV0Z3Y0d4bGNtOXZkR05oWnpNd0hRWURWUjBPQkJZRUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNQThHQTFVZEV3RUIvd1FGTUFNQkFmOHdId1lEVlIwakJCZ3dGb0FVdTdEZW9WZ3ppSnFraXBuZXZyM3JyOXJMSktzd053WURWUjBmQkRBd0xqQXNvQ3FnS0lZbWFIUjBjRG92TDJOeWJDNWhjSEJzWlM1amIyMHZZWEJ3YkdWeWIyOTBZMkZuTXk1amNtd3dEZ1lEVlIwUEFRSC9CQVFEQWdFR01CQUdDaXFHU0liM1kyUUdBZzRFQWdVQU1Bb0dDQ3FHU000OUJBTUNBMmNBTUdRQ01EclBjb05SRnBteGh2czF3MWJLWXIvMEYrM1pEM1ZOb282KzhaeUJYa0szaWZpWTk1dFpuNWpWUVEyUG5lbkMvZ0l3TWkzVlJDR3dvd1YzYkYzek9EdVFaLzBYZkN3aGJaWlB4bkpwZ2hKdlZQaDZmUnVaeTVzSmlTRmhCcGtQQ1pJZEFBQXhnZ0dJTUlJQmhBSUJBVENCaGpCNk1TNHdMQVlEVlFRRERDVkJjSEJzWlNCQmNIQnNhV05oZEdsdmJpQkpiblJsWjNKaGRHbHZiaUJEUVNBdElFY3pNU1l3SkFZRFZRUUxEQjFCY0hCc1pTQkRaWEowYVdacFkyRjBhVzl1SUVGMWRHaHZjbWwwZVRFVE1CRUdBMVVFQ2d3S1FYQndiR1VnU1c1akxqRUxNQWtHQTFVRUJoTUNWVk1DQ0ZuWW9ieXE5T1BOTUFzR0NXQ0dTQUZsQXdRQ0FhQ0JrekFZQmdrcWhraUc5dzBCQ1FNeEN3WUpLb1pJaHZjTkFRY0JNQndHQ1NxR1NJYjNEUUVKQlRFUEZ3MHlOVEF6TURZeE1URXlOVFZhTUNnR0NTcUdTSWIzRFFFSk5ERWJNQmt3Q3dZSllJWklBV1VEQkFJQm9Rb0dDQ3FHU000OUJBTUNNQzhHQ1NxR1NJYjNEUUVKQkRFaUJDQS9FemxmRUhtbk5uSW9uS2FwOUpBVkNEdld3dmlMRkhuY0IwdmpaY21WN3pBS0JnZ3Foa2pPUFFRREFnUkhNRVVDSVFEeWV0MUdwSU9QcXkyRjFzYkY3M1hOSDRJTEp6WWozSDdXR1Zzd0huRzFBQUlnQVJYZG5HY0hERkI1LzNhc1I5bm9PNVdkMy95NlZKRFpmZXQ3WWV6RjFEMEFBQUFBQUFBPSIsImhlYWRlciI6eyJwdWJsaWNLZXlIYXNoIjoiVzFOT3JTbWhwTVdDQlg0cWE3NEZBeTNEMnNWZDZ3YWFzOEdHMWdYQ21Pdz0iLCJlcGhlbWVyYWxQdWJsaWNLZXkiOiJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUVaUmdaNGkveUhwK3d3ckxtRGpDanJyTkJkQnB5b0tEU1VvamV0enBuVk4wdDNXajZiNjhnUWkvempTS3hsOUZ0eXdkb0lJSUFvWm9Sa0ZuMFpseTBMZz09IiwidHJhbnNhY3Rpb25JZCI6ImE3OWVjMjYyMThiZmZjNDNmYzlkZDZlMTg0ZDI4NDNmNzQ2MjNhNWE5ODJhZTY5YWM2NmU3ZjQ1ZDNiNzhiZDUifSwidmVyc2lvbiI6IkVDX3YxIn0=", "payment_method": { "display_name": "Visa 4228", "network": "Visa", "type": "debit" }, "transaction_identifier": "a79ec26218bffc43fc9dd6e184d2843f74623a5a982ae69ac66e7f45d3b78bd5" } }, "billing": null }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "Harrison Street", "city": "San Francisco", "state": "California", "zip": "94016", "country": "US" } } }' ``` ```json { "payment_id": "pay_pQplkw03E65IspKj5Pgl", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "authorizedotnet", "client_secret": "pay_pQplkw03E65IspKj5Pgl_secret_HIQ1AUupmzls5u5dlpV7", "created": "2025-03-06T16:51:49.667Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "apple_pay": { "last4": "4228", "card_network": "Visa", "type": "debit" } }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Francisco", "country": "US", "line1": "Harrison Street", "line2": null, "line3": null, "zip": "94016", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "apple_pay", "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": 1741279909, "expires": 1741283509, "secret": "epk_8d33224b35174c7696b267531b5f1b10" }, "manual_retry_allowed": false, "connector_transaction_id": "120058500499", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "120058500499", "payment_link": null, "profile_id": "pro_oHA88TJXvZtdcosjZFkq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_C6aMBB2E0kNICU09mSCP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-06T17:06:49.667Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-06T16:51:50.402Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null } ``` </details> **Mandate Payment** <details> <summary>1. 0 Auth mandate Apple Pay Payment Create (CIT)</summary> ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cus_1741281436", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "setup_future_usage": "off_session", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 8000, "currency": "USD" } } }, "payment_type": "setup_mandate", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "eyJkYXRhIjoiRWQ0UjZYYzVuTk85ZjVZZHc2Z0RVTzlZRE9qSlpxdFg4ME9acEtVNWxNMFNVSU9xbEEvdDU3TDNyV09mNHNTZjZqaGIvKzhiZXFvNFlCM21wU0U5emUrZzAyY0w2S1hOaWlGN2pqbE81eC9FOFFYWW0vRjNNK2lJdmtrcVlzYzBmZWlLandzSkI3SGFoOWJpUW5oOFhJQ2dpREhUSXpZcFIwaUlyVi9rdjFSbGxGT21NNlZDQkM3QVhhenhqUTJ4NEtOVzVIZUw1c2lkdHhia3ZsS2xpa1ZDeloxK2kzYjcwaEw2ZUFlamVsUno3UlEyLzNDbTVScVVqTWZnaHMvd25PVUNZb280UGVwN1BUdHdXdXdid3VMV3lkM0ZRYzdMMjlIcE5STVhCckFFd1RLN2RMTjdTc1VGSGczaTF6N0kxeVM1N1FjQ0d1aGo2dGR6clNOWW1PRmk2Nm03NzZ4M3VVc2kwM3hwdlU2bGdjMVlneUFnT2VSelBlcTRNL0Z4dzU4SlZXVGxYdnY4M09ibXJPbzZrVk0vbDJLRlRZSEszK0hjL2Y1SEZhST0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK1F3Z2dPTG9BTUNBUUlDQ0ZuWW9ieXE5T1BOTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlNVEEwTWpBeE9UTTNNREJhRncweU5qQTBNVGt4T1RNMk5UbGFNR0l4S0RBbUJnTlZCQU1NSDJWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVk5CVGtSQ1QxZ3hGREFTQmdOVkJBc01DMmxQVXlCVGVYTjBaVzF6TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekJaTUJNR0J5cUdTTTQ5QWdFR0NDcUdTTTQ5QXdFSEEwSUFCSUl3L2F2RG5QZGVJQ3hRMlp0RkV1WTM0cWtCM1d5ejRMSE5TMUpubVBqUFRyM29HaVdvd2g1TU05M09qaXFXd3Zhdm9aTURSY1RvZWtRbXpwVWJFcFdqZ2dJUk1JSUNEVEFNQmdOVkhSTUJBZjhFQWpBQU1COEdBMVVkSXdRWU1CYUFGQ1B5U2NSUGsrVHZKK2JFOWloc1A2SzcvUzVMTUVVR0NDc0dBUVVGQndFQkJEa3dOekExQmdnckJnRUZCUWN3QVlZcGFIUjBjRG92TDI5amMzQXVZWEJ3YkdVdVkyOXRMMjlqYzNBd05DMWhjSEJzWldGcFkyRXpNREl3Z2dFZEJnTlZIU0FFZ2dFVU1JSUJFRENDQVF3R0NTcUdTSWIzWTJRRkFUQ0IvakNCd3dZSUt3WUJCUVVIQWdJd2diWU1nYk5TWld4cFlXNWpaU0J2YmlCMGFHbHpJR05sY25ScFptbGpZWFJsSUdKNUlHRnVlU0J3WVhKMGVTQmhjM04xYldWeklHRmpZMlZ3ZEdGdVkyVWdiMllnZEdobElIUm9aVzRnWVhCd2JHbGpZV0pzWlNCemRHRnVaR0Z5WkNCMFpYSnRjeUJoYm1RZ1kyOXVaR2wwYVc5dWN5QnZaaUIxYzJVc0lHTmxjblJwWm1sallYUmxJSEJ2YkdsamVTQmhibVFnWTJWeWRHbG1hV05oZEdsdmJpQndjbUZqZEdsalpTQnpkR0YwWlcxbGJuUnpMakEyQmdnckJnRUZCUWNDQVJZcWFIUjBjRG92TDNkM2R5NWhjSEJzWlM1amIyMHZZMlZ5ZEdsbWFXTmhkR1ZoZFhSb2IzSnBkSGt2TURRR0ExVWRId1F0TUNzd0thQW5vQ1dHSTJoMGRIQTZMeTlqY213dVlYQndiR1V1WTI5dEwyRndjR3hsWVdsallUTXVZM0pzTUIwR0ExVWREZ1FXQkJRQ0pEQUxtdTd0UmpHWHBLWmFLWjVDY1lJY1JUQU9CZ05WSFE4QkFmOEVCQU1DQjRBd0R3WUpLb1pJaHZkalpBWWRCQUlGQURBS0JnZ3Foa2pPUFFRREFnTkhBREJFQWlCMG9iTWsyMEpKUXczVEoweFFkTVNBalpvZlNBNDZoY1hCTmlWbU1sKzhvd0lnYVRhUVU2djFDMXBTK2ZZQVRjV0tyV3hRcDlZSWFEZVE0S2M2MEI1SzJZRXdnZ0x1TUlJQ2RhQURBZ0VDQWdoSmJTKy9PcGphbHpBS0JnZ3Foa2pPUFFRREFqQm5NUnN3R1FZRFZRUUREQkpCY0hCc1pTQlNiMjkwSUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHhOREExTURZeU16UTJNekJhRncweU9UQTFNRFl5TXpRMk16QmFNSG94TGpBc0JnTlZCQU1NSlVGd2NHeGxJRUZ3Y0d4cFkyRjBhVzl1SUVsdWRHVm5jbUYwYVc5dUlFTkJJQzBnUnpNeEpqQWtCZ05WQkFzTUhVRndjR3hsSUVObGNuUnBabWxqWVhScGIyNGdRWFYwYUc5eWFYUjVNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJQQVhFWVFaMTJTRjFScGVKWUVIZHVpQW91L2VlNjVONEkzOFM1UGhNMWJWWmxzMXJpTFFsM1lOSWs1N3VnajlkaGZPaU10MnUyWnd2c2pvS1lUL1ZFV2pnZmN3Z2ZRd1JnWUlLd1lCQlFVSEFRRUVPakE0TURZR0NDc0dBUVVGQnpBQmhpcG9kSFJ3T2k4dmIyTnpjQzVoY0hCc1pTNWpiMjB2YjJOemNEQTBMV0Z3Y0d4bGNtOXZkR05oWnpNd0hRWURWUjBPQkJZRUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNQThHQTFVZEV3RUIvd1FGTUFNQkFmOHdId1lEVlIwakJCZ3dGb0FVdTdEZW9WZ3ppSnFraXBuZXZyM3JyOXJMSktzd053WURWUjBmQkRBd0xqQXNvQ3FnS0lZbWFIUjBjRG92TDJOeWJDNWhjSEJzWlM1amIyMHZZWEJ3YkdWeWIyOTBZMkZuTXk1amNtd3dEZ1lEVlIwUEFRSC9CQVFEQWdFR01CQUdDaXFHU0liM1kyUUdBZzRFQWdVQU1Bb0dDQ3FHU000OUJBTUNBMmNBTUdRQ01EclBjb05SRnBteGh2czF3MWJLWXIvMEYrM1pEM1ZOb282KzhaeUJYa0szaWZpWTk1dFpuNWpWUVEyUG5lbkMvZ0l3TWkzVlJDR3dvd1YzYkYzek9EdVFaLzBYZkN3aGJaWlB4bkpwZ2hKdlZQaDZmUnVaeTVzSmlTRmhCcGtQQ1pJZEFBQXhnZ0dJTUlJQmhBSUJBVENCaGpCNk1TNHdMQVlEVlFRRERDVkJjSEJzWlNCQmNIQnNhV05oZEdsdmJpQkpiblJsWjNKaGRHbHZiaUJEUVNBdElFY3pNU1l3SkFZRFZRUUxEQjFCY0hCc1pTQkRaWEowYVdacFkyRjBhVzl1SUVGMWRHaHZjbWwwZVRFVE1CRUdBMVVFQ2d3S1FYQndiR1VnU1c1akxqRUxNQWtHQTFVRUJoTUNWVk1DQ0ZuWW9ieXE5T1BOTUFzR0NXQ0dTQUZsQXdRQ0FhQ0JrekFZQmdrcWhraUc5dzBCQ1FNeEN3WUpLb1pJaHZjTkFRY0JNQndHQ1NxR1NJYjNEUUVKQlRFUEZ3MHlOVEF6TURZeE1URXlOVFZhTUNnR0NTcUdTSWIzRFFFSk5ERWJNQmt3Q3dZSllJWklBV1VEQkFJQm9Rb0dDQ3FHU000OUJBTUNNQzhHQ1NxR1NJYjNEUUVKQkRFaUJDQS9FemxmRUhtbk5uSW9uS2FwOUpBVkNEdld3dmlMRkhuY0IwdmpaY21WN3pBS0JnZ3Foa2pPUFFRREFnUkhNRVVDSVFEeWV0MUdwSU9QcXkyRjFzYkY3M1hOSDRJTEp6WWozSDdXR1Zzd0huRzFBQUlnQVJYZG5HY0hERkI1LzNhc1I5bm9PNVdkMy95NlZKRFpmZXQ3WWV6RjFEMEFBQUFBQUFBPSIsImhlYWRlciI6eyJwdWJsaWNLZXlIYXNoIjoiVzFOT3JTbWhwTVdDQlg0cWE3NEZBeTNEMnNWZDZ3YWFzOEdHMWdYQ21Pdz0iLCJlcGhlbWVyYWxQdWJsaWNLZXkiOiJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUVaUmdaNGkveUhwK3d3ckxtRGpDanJyTkJkQnB5b0tEU1VvamV0enBuVk4wdDNXajZiNjhnUWkvempTS3hsOUZ0eXdkb0lJSUFvWm9Sa0ZuMFpseTBMZz09IiwidHJhbnNhY3Rpb25JZCI6ImE3OWVjMjYyMThiZmZjNDNmYzlkZDZlMTg0ZDI4NDNmNzQ2MjNhNWE5ODJhZTY5YWM2NmU3ZjQ1ZDNiNzhiZDUifSwidmVyc2lvbiI6IkVDX3YxIn0=", "payment_method": { "display_name": "Visa 4228", "network": "Visa", "type": "debit" }, "transaction_identifier": "a79ec26218bffc43fc9dd6e184d2843f74623a5a982ae69ac66e7f45d3b78bd5" } }, "billing": null } }' ``` ```json { "payment_id": "pay_q6QI3s5EftuPHiXweHO8", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "succeeded", "amount": 0, "net_amount": 0, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_q6QI3s5EftuPHiXweHO8_secret_iaQ0TCvv3cJEPx6C2H4T", "created": "2025-03-06T17:17:11.969Z", "currency": "USD", "customer_id": "cus_1741281432", "customer": { "id": "cus_1741281432", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": "man_aSSagnsnEwx26GJmmv4D", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 8000, "currency": "USD", "start_date": null, "end_date": null, "metadata": null } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "apple_pay": { "last4": "4228", "card_network": "Visa", "type": "debit" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "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": null, "email": null }, "order_details": null, "email": "[email protected]", "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": "apple_pay", "connector_label": "authorizedotnet_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cus_1741281432", "created_at": 1741281431, "expires": 1741285031, "secret": "epk_652599a411dc4037b07fdb5ff70c05cd" }, "manual_retry_allowed": false, "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_oHA88TJXvZtdcosjZFkq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_C6aMBB2E0kNICU09mSCP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-06T17:32:11.969Z", "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": "pm_PvC6MYhxwlUucL32HX4C", "payment_method_status": "active", "updated": "2025-03-06T17:17:13.973Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "929610853-929002308", "card_discovery": null } ``` </details> <details> <summary>2. 0 Auth mandate Apple Pay Payment Create (MIT)</summary> ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data '{ "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "cus_1741281432", "client_secret": "pay_ldeENuwjOHvyLJ0xq5RS_secret_C5IomwEVgCsWGrQ8QOqV", "recurring_details": { "type": "payment_method_id", "data": "pm_PvC6MYhxwlUucL32HX4C" }, "off_session": true, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "payment_method": "wallet", "payment_method_type": "apple_pay", "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" } } }' ``` ```json { "payment_id": "pay_ldeENuwjOHvyLJ0xq5RS", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "authorizedotnet", "client_secret": "pay_ldeENuwjOHvyLJ0xq5RS_secret_C5IomwEVgCsWGrQ8QOqV", "created": "2025-03-06T17:17:40.740Z", "currency": "USD", "customer_id": "cus_1741281432", "customer": { "id": "cus_1741281432", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "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": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "apple_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cus_1741281432", "created_at": 1741281460, "expires": 1741285060, "secret": "epk_22f2d7c3c4b44c36aa837b5286c3bac4" }, "manual_retry_allowed": false, "connector_transaction_id": "120058501970", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "120058501970", "payment_link": null, "profile_id": "pro_oHA88TJXvZtdcosjZFkq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_C6aMBB2E0kNICU09mSCP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-06T17:32:40.740Z", "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": "pm_PvC6MYhxwlUucL32HX4C", "payment_method_status": "active", "updated": "2025-03-06T17:17:41.481Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "929610853-929002308", "card_discovery": null } ``` </details> ____ **Apple Pay (confirm: `false`)** **Normal Payment** <details> <summary>0. Apple Pay Payment Create</summary> Create a payment with Apple Pay as payment method: ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data-raw '{ "amount": 1000, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "payment_id": "pay_I1yph8Vzm5LYUKWYLeGE", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "requires_payment_method", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_I1yph8Vzm5LYUKWYLeGE_secret_HYK6Yj7wDW5bSe2HUMAS", "created": "2025-03-06T17:27:47.474Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "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": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "[email protected]", "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": null, "connector_label": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1741282067, "expires": 1741285667, "secret": "epk_188e2a750ea84059913ebd8490860258" }, "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_oHA88TJXvZtdcosjZFkq", "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": "2025-03-06T17:42:47.474Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-06T17:27:47.483Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null } ``` Confirm the payment with the payment tokenizated data in the previous step: ```curl curl --location 'http://Localhost:8080/payments/pay_I1yph8Vzm5LYUKWYLeGE/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data '{ "confirm": true, "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "eyJkYXRhIjoiRWQ0UjZYYzVuTk85ZjVZZHc2Z0RVTzlZRE9qSlpxdFg4ME9acEtVNWxNMFNVSU9xbEEvdDU3TDNyV09mNHNTZjZqaGIvKzhiZXFvNFlCM21wU0U5emUrZzAyY0w2S1hOaWlGN2pqbE81eC9FOFFYWW0vRjNNK2lJdmtrcVlzYzBmZWlLandzSkI3SGFoOWJpUW5oOFhJQ2dpREhUSXpZcFIwaUlyVi9rdjFSbGxGT21NNlZDQkM3QVhhenhqUTJ4NEtOVzVIZUw1c2lkdHhia3ZsS2xpa1ZDeloxK2kzYjcwaEw2ZUFlamVsUno3UlEyLzNDbTVScVVqTWZnaHMvd25PVUNZb280UGVwN1BUdHdXdXdid3VMV3lkM0ZRYzdMMjlIcE5STVhCckFFd1RLN2RMTjdTc1VGSGczaTF6N0kxeVM1N1FjQ0d1aGo2dGR6clNOWW1PRmk2Nm03NzZ4M3VVc2kwM3hwdlU2bGdjMVlneUFnT2VSelBlcTRNL0Z4dzU4SlZXVGxYdnY4M09ibXJPbzZrVk0vbDJLRlRZSEszK0hjL2Y1SEZhST0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK1F3Z2dPTG9BTUNBUUlDQ0ZuWW9ieXE5T1BOTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlNVEEwTWpBeE9UTTNNREJhRncweU5qQTBNVGt4T1RNMk5UbGFNR0l4S0RBbUJnTlZCQU1NSDJWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVk5CVGtSQ1QxZ3hGREFTQmdOVkJBc01DMmxQVXlCVGVYTjBaVzF6TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekJaTUJNR0J5cUdTTTQ5QWdFR0NDcUdTTTQ5QXdFSEEwSUFCSUl3L2F2RG5QZGVJQ3hRMlp0RkV1WTM0cWtCM1d5ejRMSE5TMUpubVBqUFRyM29HaVdvd2g1TU05M09qaXFXd3Zhdm9aTURSY1RvZWtRbXpwVWJFcFdqZ2dJUk1JSUNEVEFNQmdOVkhSTUJBZjhFQWpBQU1COEdBMVVkSXdRWU1CYUFGQ1B5U2NSUGsrVHZKK2JFOWloc1A2SzcvUzVMTUVVR0NDc0dBUVVGQndFQkJEa3dOekExQmdnckJnRUZCUWN3QVlZcGFIUjBjRG92TDI5amMzQXVZWEJ3YkdVdVkyOXRMMjlqYzNBd05DMWhjSEJzWldGcFkyRXpNREl3Z2dFZEJnTlZIU0FFZ2dFVU1JSUJFRENDQVF3R0NTcUdTSWIzWTJRRkFUQ0IvakNCd3dZSUt3WUJCUVVIQWdJd2diWU1nYk5TWld4cFlXNWpaU0J2YmlCMGFHbHpJR05sY25ScFptbGpZWFJsSUdKNUlHRnVlU0J3WVhKMGVTQmhjM04xYldWeklHRmpZMlZ3ZEdGdVkyVWdiMllnZEdobElIUm9aVzRnWVhCd2JHbGpZV0pzWlNCemRHRnVaR0Z5WkNCMFpYSnRjeUJoYm1RZ1kyOXVaR2wwYVc5dWN5QnZaaUIxYzJVc0lHTmxjblJwWm1sallYUmxJSEJ2YkdsamVTQmhibVFnWTJWeWRHbG1hV05oZEdsdmJpQndjbUZqZEdsalpTQnpkR0YwWlcxbGJuUnpMakEyQmdnckJnRUZCUWNDQVJZcWFIUjBjRG92TDNkM2R5NWhjSEJzWlM1amIyMHZZMlZ5ZEdsbWFXTmhkR1ZoZFhSb2IzSnBkSGt2TURRR0ExVWRId1F0TUNzd0thQW5vQ1dHSTJoMGRIQTZMeTlqY213dVlYQndiR1V1WTI5dEwyRndjR3hsWVdsallUTXVZM0pzTUIwR0ExVWREZ1FXQkJRQ0pEQUxtdTd0UmpHWHBLWmFLWjVDY1lJY1JUQU9CZ05WSFE4QkFmOEVCQU1DQjRBd0R3WUpLb1pJaHZkalpBWWRCQUlGQURBS0JnZ3Foa2pPUFFRREFnTkhBREJFQWlCMG9iTWsyMEpKUXczVEoweFFkTVNBalpvZlNBNDZoY1hCTmlWbU1sKzhvd0lnYVRhUVU2djFDMXBTK2ZZQVRjV0tyV3hRcDlZSWFEZVE0S2M2MEI1SzJZRXdnZ0x1TUlJQ2RhQURBZ0VDQWdoSmJTKy9PcGphbHpBS0JnZ3Foa2pPUFFRREFqQm5NUnN3R1FZRFZRUUREQkpCY0hCc1pTQlNiMjkwSUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHhOREExTURZeU16UTJNekJhRncweU9UQTFNRFl5TXpRMk16QmFNSG94TGpBc0JnTlZCQU1NSlVGd2NHeGxJRUZ3Y0d4cFkyRjBhVzl1SUVsdWRHVm5jbUYwYVc5dUlFTkJJQzBnUnpNeEpqQWtCZ05WQkFzTUhVRndjR3hsSUVObGNuUnBabWxqWVhScGIyNGdRWFYwYUc5eWFYUjVNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJQQVhFWVFaMTJTRjFScGVKWUVIZHVpQW91L2VlNjVONEkzOFM1UGhNMWJWWmxzMXJpTFFsM1lOSWs1N3VnajlkaGZPaU10MnUyWnd2c2pvS1lUL1ZFV2pnZmN3Z2ZRd1JnWUlLd1lCQlFVSEFRRUVPakE0TURZR0NDc0dBUVVGQnpBQmhpcG9kSFJ3T2k4dmIyTnpjQzVoY0hCc1pTNWpiMjB2YjJOemNEQTBMV0Z3Y0d4bGNtOXZkR05oWnpNd0hRWURWUjBPQkJZRUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNQThHQTFVZEV3RUIvd1FGTUFNQkFmOHdId1lEVlIwakJCZ3dGb0FVdTdEZW9WZ3ppSnFraXBuZXZyM3JyOXJMSktzd053WURWUjBmQkRBd0xqQXNvQ3FnS0lZbWFIUjBjRG92TDJOeWJDNWhjSEJzWlM1amIyMHZZWEJ3YkdWeWIyOTBZMkZuTXk1amNtd3dEZ1lEVlIwUEFRSC9CQVFEQWdFR01CQUdDaXFHU0liM1kyUUdBZzRFQWdVQU1Bb0dDQ3FHU000OUJBTUNBMmNBTUdRQ01EclBjb05SRnBteGh2czF3MWJLWXIvMEYrM1pEM1ZOb282KzhaeUJYa0szaWZpWTk1dFpuNWpWUVEyUG5lbkMvZ0l3TWkzVlJDR3dvd1YzYkYzek9EdVFaLzBYZkN3aGJaWlB4bkpwZ2hKdlZQaDZmUnVaeTVzSmlTRmhCcGtQQ1pJZEFBQXhnZ0dJTUlJQmhBSUJBVENCaGpCNk1TNHdMQVlEVlFRRERDVkJjSEJzWlNCQmNIQnNhV05oZEdsdmJpQkpiblJsWjNKaGRHbHZiaUJEUVNBdElFY3pNU1l3SkFZRFZRUUxEQjFCY0hCc1pTQkRaWEowYVdacFkyRjBhVzl1SUVGMWRHaHZjbWwwZVRFVE1CRUdBMVVFQ2d3S1FYQndiR1VnU1c1akxqRUxNQWtHQTFVRUJoTUNWVk1DQ0ZuWW9ieXE5T1BOTUFzR0NXQ0dTQUZsQXdRQ0FhQ0JrekFZQmdrcWhraUc5dzBCQ1FNeEN3WUpLb1pJaHZjTkFRY0JNQndHQ1NxR1NJYjNEUUVKQlRFUEZ3MHlOVEF6TURZeE1URXlOVFZhTUNnR0NTcUdTSWIzRFFFSk5ERWJNQmt3Q3dZSllJWklBV1VEQkFJQm9Rb0dDQ3FHU000OUJBTUNNQzhHQ1NxR1NJYjNEUUVKQkRFaUJDQS9FemxmRUhtbk5uSW9uS2FwOUpBVkNEdld3dmlMRkhuY0IwdmpaY21WN3pBS0JnZ3Foa2pPUFFRREFnUkhNRVVDSVFEeWV0MUdwSU9QcXkyRjFzYkY3M1hOSDRJTEp6WWozSDdXR1Zzd0huRzFBQUlnQVJYZG5HY0hERkI1LzNhc1I5bm9PNVdkMy95NlZKRFpmZXQ3WWV6RjFEMEFBQUFBQUFBPSIsImhlYWRlciI6eyJwdWJsaWNLZXlIYXNoIjoiVzFOT3JTbWhwTVdDQlg0cWE3NEZBeTNEMnNWZDZ3YWFzOEdHMWdYQ21Pdz0iLCJlcGhlbWVyYWxQdWJsaWNLZXkiOiJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUVaUmdaNGkveUhwK3d3ckxtRGpDanJyTkJkQnB5b0tEU1VvamV0enBuVk4wdDNXajZiNjhnUWkvempTS3hsOUZ0eXdkb0lJSUFvWm9Sa0ZuMFpseTBMZz09IiwidHJhbnNhY3Rpb25JZCI6ImE3OWVjMjYyMThiZmZjNDNmYzlkZDZlMTg0ZDI4NDNmNzQ2MjNhNWE5ODJhZTY5YWM2NmU3ZjQ1ZDNiNzhiZDUifSwidmVyc2lvbiI6IkVDX3YxIn0=", "payment_method": { "display_name": "Visa 4228", "network": "Visa", "type": "debit" }, "transaction_identifier": "a79ec26218bffc43fc9dd6e184d2843f74623a5a982ae69ac66e7f45d3b78bd5" } }, "billing": null }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "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" } } }' ``` ```json { "payment_id": "pay_I1yph8Vzm5LYUKWYLeGE", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "authorizedotnet", "client_secret": "pay_I1yph8Vzm5LYUKWYLeGE_secret_HYK6Yj7wDW5bSe2HUMAS", "created": "2025-03-06T17:27:47.474Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "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": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "apple_pay": { "last4": "4228", "card_network": "Visa", "type": "debit" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "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": null, "email": null }, "order_details": null, "email": "[email protected]", "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": "apple_pay", "connector_label": "authorizedotnet_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "120058504003", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "120058504003", "payment_link": null, "profile_id": "pro_oHA88TJXvZtdcosjZFkq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_C6aMBB2E0kNICU09mSCP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-06T17:42:47.474Z", "fingerprint": null, "browser_info": { "os_type": null, "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "os_version": null, "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, "device_model": null, "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, "accept_language": "en", "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-06T17:28:06.643Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null } ``` </details> **Mandate Payment** <details> <summary>1. 0 Auth mandate Apple Pay Payment Create (CIT)</summary> Create a payment with Apple Pay as payment method: ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "setup_future_usage": "off_session" }' ``` ```json { "payment_id": "pay_2tnZM8hO4nIxl6gox8rI", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "requires_payment_method", "amount": 0, "net_amount": 0, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_2tnZM8hO4nIxl6gox8rI_secret_wEWXQgZ7k7Rod2MdN7Kf", "created": "2025-03-06T17:28:21.551Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": "John Doe", "email": "[email protected]", "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": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "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": null, "connector_label": null, "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": 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_oHA88TJXvZtdcosjZFkq", "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": "2025-03-06T17:43:21.551Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-06T17:28:21.561Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null } ``` Confirm the payment with the payment tokenizated data in the previous step: ```curl curl --location 'http://Localhost:8080/payments/pay_2tnZM8hO4nIxl6gox8rI/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data '{ "confirm": true, "payment_type": "setup_mandate", "customer_id": "cus_1741282119", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 8000, "currency": "USD" } } }, "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "eyJkYXRhIjoiRWQ0UjZYYzVuTk85ZjVZZHc2Z0RVTzlZRE9qSlpxdFg4ME9acEtVNWxNMFNVSU9xbEEvdDU3TDNyV09mNHNTZjZqaGIvKzhiZXFvNFlCM21wU0U5emUrZzAyY0w2S1hOaWlGN2pqbE81eC9FOFFYWW0vRjNNK2lJdmtrcVlzYzBmZWlLandzSkI3SGFoOWJpUW5oOFhJQ2dpREhUSXpZcFIwaUlyVi9rdjFSbGxGT21NNlZDQkM3QVhhenhqUTJ4NEtOVzVIZUw1c2lkdHhia3ZsS2xpa1ZDeloxK2kzYjcwaEw2ZUFlamVsUno3UlEyLzNDbTVScVVqTWZnaHMvd25PVUNZb280UGVwN1BUdHdXdXdid3VMV3lkM0ZRYzdMMjlIcE5STVhCckFFd1RLN2RMTjdTc1VGSGczaTF6N0kxeVM1N1FjQ0d1aGo2dGR6clNOWW1PRmk2Nm03NzZ4M3VVc2kwM3hwdlU2bGdjMVlneUFnT2VSelBlcTRNL0Z4dzU4SlZXVGxYdnY4M09ibXJPbzZrVk0vbDJLRlRZSEszK0hjL2Y1SEZhST0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK1F3Z2dPTG9BTUNBUUlDQ0ZuWW9ieXE5T1BOTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlNVEEwTWpBeE9UTTNNREJhRncweU5qQTBNVGt4T1RNMk5UbGFNR0l4S0RBbUJnTlZCQU1NSDJWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVk5CVGtSQ1QxZ3hGREFTQmdOVkJBc01DMmxQVXlCVGVYTjBaVzF6TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekJaTUJNR0J5cUdTTTQ5QWdFR0NDcUdTTTQ5QXdFSEEwSUFCSUl3L2F2RG5QZGVJQ3hRMlp0RkV1WTM0cWtCM1d5ejRMSE5TMUpubVBqUFRyM29HaVdvd2g1TU05M09qaXFXd3Zhdm9aTURSY1RvZWtRbXpwVWJFcFdqZ2dJUk1JSUNEVEFNQmdOVkhSTUJBZjhFQWpBQU1COEdBMVVkSXdRWU1CYUFGQ1B5U2NSUGsrVHZKK2JFOWloc1A2SzcvUzVMTUVVR0NDc0dBUVVGQndFQkJEa3dOekExQmdnckJnRUZCUWN3QVlZcGFIUjBjRG92TDI5amMzQXVZWEJ3YkdVdVkyOXRMMjlqYzNBd05DMWhjSEJzWldGcFkyRXpNREl3Z2dFZEJnTlZIU0FFZ2dFVU1JSUJFRENDQVF3R0NTcUdTSWIzWTJRRkFUQ0IvakNCd3dZSUt3WUJCUVVIQWdJd2diWU1nYk5TWld4cFlXNWpaU0J2YmlCMGFHbHpJR05sY25ScFptbGpZWFJsSUdKNUlHRnVlU0J3WVhKMGVTQmhjM04xYldWeklHRmpZMlZ3ZEdGdVkyVWdiMllnZEdobElIUm9aVzRnWVhCd2JHbGpZV0pzWlNCemRHRnVaR0Z5WkNCMFpYSnRjeUJoYm1RZ1kyOXVaR2wwYVc5dWN5QnZaaUIxYzJVc0lHTmxjblJwWm1sallYUmxJSEJ2YkdsamVTQmhibVFnWTJWeWRHbG1hV05oZEdsdmJpQndjbUZqZEdsalpTQnpkR0YwWlcxbGJuUnpMakEyQmdnckJnRUZCUWNDQVJZcWFIUjBjRG92TDNkM2R5NWhjSEJzWlM1amIyMHZZMlZ5ZEdsbWFXTmhkR1ZoZFhSb2IzSnBkSGt2TURRR0ExVWRId1F0TUNzd0thQW5vQ1dHSTJoMGRIQTZMeTlqY213dVlYQndiR1V1WTI5dEwyRndjR3hsWVdsallUTXVZM0pzTUIwR0ExVWREZ1FXQkJRQ0pEQUxtdTd0UmpHWHBLWmFLWjVDY1lJY1JUQU9CZ05WSFE4QkFmOEVCQU1DQjRBd0R3WUpLb1pJaHZkalpBWWRCQUlGQURBS0JnZ3Foa2pPUFFRREFnTkhBREJFQWlCMG9iTWsyMEpKUXczVEoweFFkTVNBalpvZlNBNDZoY1hCTmlWbU1sKzhvd0lnYVRhUVU2djFDMXBTK2ZZQVRjV0tyV3hRcDlZSWFEZVE0S2M2MEI1SzJZRXdnZ0x1TUlJQ2RhQURBZ0VDQWdoSmJTKy9PcGphbHpBS0JnZ3Foa2pPUFFRREFqQm5NUnN3R1FZRFZRUUREQkpCY0hCc1pTQlNiMjkwSUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHhOREExTURZeU16UTJNekJhRncweU9UQTFNRFl5TXpRMk16QmFNSG94TGpBc0JnTlZCQU1NSlVGd2NHeGxJRUZ3Y0d4cFkyRjBhVzl1SUVsdWRHVm5jbUYwYVc5dUlFTkJJQzBnUnpNeEpqQWtCZ05WQkFzTUhVRndjR3hsSUVObGNuUnBabWxqWVhScGIyNGdRWFYwYUc5eWFYUjVNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJQQVhFWVFaMTJTRjFScGVKWUVIZHVpQW91L2VlNjVONEkzOFM1UGhNMWJWWmxzMXJpTFFsM1lOSWs1N3VnajlkaGZPaU10MnUyWnd2c2pvS1lUL1ZFV2pnZmN3Z2ZRd1JnWUlLd1lCQlFVSEFRRUVPakE0TURZR0NDc0dBUVVGQnpBQmhpcG9kSFJ3T2k4dmIyTnpjQzVoY0hCc1pTNWpiMjB2YjJOemNEQTBMV0Z3Y0d4bGNtOXZkR05oWnpNd0hRWURWUjBPQkJZRUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNQThHQTFVZEV3RUIvd1FGTUFNQkFmOHdId1lEVlIwakJCZ3dGb0FVdTdEZW9WZ3ppSnFraXBuZXZyM3JyOXJMSktzd053WURWUjBmQkRBd0xqQXNvQ3FnS0lZbWFIUjBjRG92TDJOeWJDNWhjSEJzWlM1amIyMHZZWEJ3YkdWeWIyOTBZMkZuTXk1amNtd3dEZ1lEVlIwUEFRSC9CQVFEQWdFR01CQUdDaXFHU0liM1kyUUdBZzRFQWdVQU1Bb0dDQ3FHU000OUJBTUNBMmNBTUdRQ01EclBjb05SRnBteGh2czF3MWJLWXIvMEYrM1pEM1ZOb282KzhaeUJYa0szaWZpWTk1dFpuNWpWUVEyUG5lbkMvZ0l3TWkzVlJDR3dvd1YzYkYzek9EdVFaLzBYZkN3aGJaWlB4bkpwZ2hKdlZQaDZmUnVaeTVzSmlTRmhCcGtQQ1pJZEFBQXhnZ0dJTUlJQmhBSUJBVENCaGpCNk1TNHdMQVlEVlFRRERDVkJjSEJzWlNCQmNIQnNhV05oZEdsdmJpQkpiblJsWjNKaGRHbHZiaUJEUVNBdElFY3pNU1l3SkFZRFZRUUxEQjFCY0hCc1pTQkRaWEowYVdacFkyRjBhVzl1SUVGMWRHaHZjbWwwZVRFVE1CRUdBMVVFQ2d3S1FYQndiR1VnU1c1akxqRUxNQWtHQTFVRUJoTUNWVk1DQ0ZuWW9ieXE5T1BOTUFzR0NXQ0dTQUZsQXdRQ0FhQ0JrekFZQmdrcWhraUc5dzBCQ1FNeEN3WUpLb1pJaHZjTkFRY0JNQndHQ1NxR1NJYjNEUUVKQlRFUEZ3MHlOVEF6TURZeE1URXlOVFZhTUNnR0NTcUdTSWIzRFFFSk5ERWJNQmt3Q3dZSllJWklBV1VEQkFJQm9Rb0dDQ3FHU000OUJBTUNNQzhHQ1NxR1NJYjNEUUVKQkRFaUJDQS9FemxmRUhtbk5uSW9uS2FwOUpBVkNEdld3dmlMRkhuY0IwdmpaY21WN3pBS0JnZ3Foa2pPUFFRREFnUkhNRVVDSVFEeWV0MUdwSU9QcXkyRjFzYkY3M1hOSDRJTEp6WWozSDdXR1Zzd0huRzFBQUlnQVJYZG5HY0hERkI1LzNhc1I5bm9PNVdkMy95NlZKRFpmZXQ3WWV6RjFEMEFBQUFBQUFBPSIsImhlYWRlciI6eyJwdWJsaWNLZXlIYXNoIjoiVzFOT3JTbWhwTVdDQlg0cWE3NEZBeTNEMnNWZDZ3YWFzOEdHMWdYQ21Pdz0iLCJlcGhlbWVyYWxQdWJsaWNLZXkiOiJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUVaUmdaNGkveUhwK3d3ckxtRGpDanJyTkJkQnB5b0tEU1VvamV0enBuVk4wdDNXajZiNjhnUWkvempTS3hsOUZ0eXdkb0lJSUFvWm9Sa0ZuMFpseTBMZz09IiwidHJhbnNhY3Rpb25JZCI6ImE3OWVjMjYyMThiZmZjNDNmYzlkZDZlMTg0ZDI4NDNmNzQ2MjNhNWE5ODJhZTY5YWM2NmU3ZjQ1ZDNiNzhiZDUifSwidmVyc2lvbiI6IkVDX3YxIn0=", "payment_method": { "display_name": "Visa 4228", "network": "Visa", "type": "debit" }, "transaction_identifier": "a79ec26218bffc43fc9dd6e184d2843f74623a5a982ae69ac66e7f45d3b78bd5" } }, "billing": null }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "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" } } }' ``` ```json { "payment_id": "pay_2tnZM8hO4nIxl6gox8rI", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "succeeded", "amount": 0, "net_amount": 0, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_2tnZM8hO4nIxl6gox8rI_secret_wEWXQgZ7k7Rod2MdN7Kf", "created": "2025-03-06T17:28:21.551Z", "currency": "USD", "customer_id": "cus_1741282115", "customer": { "id": "cus_1741282115", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": "man_f3nDuo2P2PnTlqkUuMQs", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 8000, "currency": "USD", "start_date": null, "end_date": null, "metadata": null } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "apple_pay": { "last4": "4228", "card_network": "Visa", "type": "debit" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "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": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "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": "apple_pay", "connector_label": "authorizedotnet_US_default", "business_country": "US", "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": { "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_oHA88TJXvZtdcosjZFkq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_C6aMBB2E0kNICU09mSCP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-06T17:43:21.551Z", "fingerprint": null, "browser_info": { "os_type": null, "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "os_version": null, "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, "device_model": null, "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, "accept_language": "en", "java_script_enabled": true }, "payment_method_id": "pm_EpXi7jTd8DzFIG5Vj2y7", "payment_method_status": "active", "updated": "2025-03-06T17:28:36.364Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "929611432-929002945", "card_discovery": null } ``` </details> <details> <summary>2. 0 Auth mandate Apple Pay Payment Create (MIT)</summary> Create + Confirm: ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_a0e1Cq93U9sDLfUgilzlEJqg4eBRZI4Y021Hqj6bTXhAZTC7gjLij6aqolpvM9Gn' \ --data '{ "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "cus_1741282115", "client_secret": "pay_Jc0FhbExingoDJPnrOAQ_secret_eBhCpq9mBPOSajNH3Kpl", "recurring_details": { "type": "payment_method_id", "data": "pm_EpXi7jTd8DzFIG5Vj2y7" }, "off_session": true, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "payment_method": "wallet", "payment_method_type": "apple_pay", "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" } } }' ``` ```json { "payment_id": "pay_Jc0FhbExingoDJPnrOAQ", "merchant_id": "postman_merchant_GHAction_1741082806", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "authorizedotnet", "client_secret": "pay_Jc0FhbExingoDJPnrOAQ_secret_eBhCpq9mBPOSajNH3Kpl", "created": "2025-03-06T17:28:53.109Z", "currency": "USD", "customer_id": "cus_1741282115", "customer": { "id": "cus_1741282115", "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": true, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "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": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": 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": "apple_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cus_1741282115", "created_at": 1741282133, "expires": 1741285733, "secret": "epk_7b3fdc77c6c8443cb2d6ce57a1d7c4c1" }, "manual_retry_allowed": false, "connector_transaction_id": "120058504115", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "120058504115", "payment_link": null, "profile_id": "pro_oHA88TJXvZtdcosjZFkq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_C6aMBB2E0kNICU09mSCP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-06T17:43:53.109Z", "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": "pm_EpXi7jTd8DzFIG5Vj2y7", "payment_method_status": "active", "updated": "2025-03-06T17:28:53.762Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "929611432-929002945", "card_discovery": null } ``` </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
586adea99275df7032d276552688da6012728f3c
586adea99275df7032d276552688da6012728f3c
juspay/hyperswitch
juspay__hyperswitch-7436
Bug: [CYPRESS] Fix lints and address code duplication - [ ] Fix lints that is resulting in checks to fail on every PRs - [ ] Reduce duplicate code in connector configs
2025-03-05T16:07:30Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR is just a minor refactor of removing duplicate / redundant `customer_acceptance` object by re-using it. Moved the object to `Commons` and imported the object where ever the duplicate code exist. ### 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). --> Reduce code duplication closes https://github.com/juspay/hyperswitch/issues/7436 ## 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)? --> CI should pass ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `npm run format` - [x] I addressed lints thrown by `npm run lint` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
6df1578922b7bdc3d0b20ef1bc0b8714f43cc4bf
6df1578922b7bdc3d0b20ef1bc0b8714f43cc4bf
juspay/hyperswitch
juspay__hyperswitch-7432
Bug: feat(analytics): refactor and rewrite authentication related analytics Need to refactor and re-write the authentication related analytics. The table which should be queried is `authentications`. The existing metrics need to be modified and a few new metrics should be created to provide enhanced insights into authentication related data.
diff --git a/crates/analytics/src/auth_events/accumulator.rs b/crates/analytics/src/auth_events/accumulator.rs index 2958030c8da..446ac6ac8c2 100644 --- a/crates/analytics/src/auth_events/accumulator.rs +++ b/crates/analytics/src/auth_events/accumulator.rs @@ -4,7 +4,7 @@ use super::metrics::AuthEventMetricRow; #[derive(Debug, Default)] pub struct AuthEventMetricsAccumulator { - pub three_ds_sdk_count: CountAccumulator, + pub authentication_count: CountAccumulator, pub authentication_attempt_count: CountAccumulator, pub authentication_success_count: CountAccumulator, pub challenge_flow_count: CountAccumulator, @@ -47,7 +47,7 @@ impl AuthEventMetricAccumulator for CountAccumulator { impl AuthEventMetricsAccumulator { pub fn collect(self) -> AuthEventMetricsBucketValue { AuthEventMetricsBucketValue { - three_ds_sdk_count: self.three_ds_sdk_count.collect(), + authentication_count: self.authentication_count.collect(), authentication_attempt_count: self.authentication_attempt_count.collect(), authentication_success_count: self.authentication_success_count.collect(), challenge_flow_count: self.challenge_flow_count.collect(), diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs index 3fd134bc498..75bdf4de149 100644 --- a/crates/analytics/src/auth_events/core.rs +++ b/crates/analytics/src/auth_events/core.rs @@ -18,7 +18,6 @@ use crate::{ pub async fn get_metrics( pool: &AnalyticsProvider, merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &String, req: GetAuthEventMetricRequest, ) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> { let mut metrics_accumulator: HashMap< @@ -30,14 +29,12 @@ pub async fn get_metrics( for metric_type in req.metrics.iter().cloned() { let req = req.clone(); let merchant_id_scoped = merchant_id.to_owned(); - let publishable_key_scoped = publishable_key.to_owned(); let pool = pool.clone(); set.spawn(async move { let data = pool .get_auth_event_metrics( &metric_type, &merchant_id_scoped, - &publishable_key_scoped, req.time_series.map(|t| t.granularity), &req.time_range, ) @@ -56,8 +53,8 @@ pub async fn get_metrics( for (id, value) in data? { let metrics_builder = metrics_accumulator.entry(id).or_default(); match metric { - AuthEventMetrics::ThreeDsSdkCount => metrics_builder - .three_ds_sdk_count + AuthEventMetrics::AuthenticationCount => metrics_builder + .authentication_count .add_metrics_bucket(&value), AuthEventMetrics::AuthenticationAttemptCount => metrics_builder .authentication_attempt_count diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index 4a1fbd0e147..f3f0354818c 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -12,22 +12,22 @@ use crate::{ }; mod authentication_attempt_count; +mod authentication_count; mod authentication_success_count; mod challenge_attempt_count; mod challenge_flow_count; mod challenge_success_count; mod frictionless_flow_count; mod frictionless_success_count; -mod three_ds_sdk_count; use authentication_attempt_count::AuthenticationAttemptCount; +use authentication_count::AuthenticationCount; use authentication_success_count::AuthenticationSuccessCount; use challenge_attempt_count::ChallengeAttemptCount; use challenge_flow_count::ChallengeFlowCount; use challenge_success_count::ChallengeSuccessCount; use frictionless_flow_count::FrictionlessFlowCount; use frictionless_success_count::FrictionlessSuccessCount; -use three_ds_sdk_count::ThreeDsSdkCount; #[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)] pub struct AuthEventMetricRow { @@ -45,7 +45,6 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, @@ -65,50 +64,49 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { match self { - Self::ThreeDsSdkCount => { - ThreeDsSdkCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + Self::AuthenticationCount => { + AuthenticationCount + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::AuthenticationAttemptCount => { AuthenticationAttemptCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::AuthenticationSuccessCount => { AuthenticationSuccessCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::ChallengeFlowCount => { ChallengeFlowCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::ChallengeAttemptCount => { ChallengeAttemptCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::ChallengeSuccessCount => { ChallengeSuccessCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::FrictionlessFlowCount => { FrictionlessFlowCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::FrictionlessSuccessCount => { FrictionlessSuccessCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } } diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index 5faeefec686..2d34344905e 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -1,9 +1,9 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, sdk_events::SdkEventNames, Granularity, - TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; +use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -29,14 +29,13 @@ where { async fn load_metrics( &self, - _merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, + merchant_id: &common_utils::id_type::MerchantId, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,30 +44,26 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .switch()?; - } - - query_builder - .add_filter_clause("merchant_id", publishable_key) - .switch()?; - query_builder - .add_bool_filter_clause("first_event", 1) + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) .switch()?; query_builder - .add_filter_clause("event_name", SdkEventNames::AuthenticationCallInit) + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) .switch()?; query_builder - .add_filter_clause("log_type", "INFO") + .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder - .add_filter_clause("category", "API") + .add_negative_filter_clause("authentication_status", AuthenticationStatus::Pending) .switch()?; time_range @@ -76,9 +71,9 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs b/crates/analytics/src/auth_events/metrics/authentication_count.rs similarity index 69% rename from crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs rename to crates/analytics/src/auth_events/metrics/authentication_count.rs index 4ce10c9aad3..9f2311f5638 100644 --- a/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_count.rs @@ -1,8 +1,7 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, sdk_events::SdkEventNames, Granularity, - TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -15,10 +14,10 @@ use crate::{ }; #[derive(Default)] -pub(super) struct ThreeDsSdkCount; +pub(super) struct AuthenticationCount; #[async_trait::async_trait] -impl<T> super::AuthEventMetric<T> for ThreeDsSdkCount +impl<T> super::AuthEventMetric<T> for AuthenticationCount where T: AnalyticsDataSource + super::AuthEventMetricAnalytics, PrimitiveDateTime: ToSql<T>, @@ -29,14 +28,13 @@ where { async fn load_metrics( &self, - _merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, + merchant_id: &common_utils::id_type::MerchantId, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,30 +43,22 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .switch()?; - } - - query_builder - .add_filter_clause("merchant_id", publishable_key) - .switch()?; - query_builder - .add_bool_filter_clause("first_event", 1) - .switch()?; - - query_builder - .add_filter_clause("category", "USER_EVENT") + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) .switch()?; query_builder - .add_filter_clause("log_type", "INFO") + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) .switch()?; query_builder - .add_filter_clause("event_name", SdkEventNames::ThreeDsMethod) + .add_filter_clause("merchant_id", merchant_id) .switch()?; time_range @@ -76,9 +66,9 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index 663473c2d89..e887807f41c 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -1,9 +1,9 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, sdk_events::SdkEventNames, Granularity, - TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; +use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -29,14 +29,13 @@ where { async fn load_metrics( &self, - _merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, + merchant_id: &common_utils::id_type::MerchantId, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,30 +44,26 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .switch()?; - } - - query_builder - .add_filter_clause("merchant_id", publishable_key) - .switch()?; - query_builder - .add_bool_filter_clause("first_event", 1) + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) .switch()?; query_builder - .add_filter_clause("event_name", SdkEventNames::AuthenticationCall) + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) .switch()?; query_builder - .add_filter_clause("log_type", "INFO") + .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder - .add_filter_clause("category", "API") + .add_filter_clause("authentication_status", AuthenticationStatus::Success) .switch()?; time_range @@ -76,9 +71,9 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index 15cd86e5cc8..f1f6a397994 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -1,8 +1,7 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::{AuthEventFlows, AuthEventMetricsBucketIdentifier}, - Granularity, TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -10,7 +9,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -30,13 +29,12 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, - _publishable_key: &str, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::ApiEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,22 +43,30 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .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()?; query_builder .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder - .add_filter_clause("api_flow", AuthEventFlows::IncomingWebhookReceive) + .add_filter_clause("trans_status", "C".to_string()) .switch()?; query_builder - .add_custom_filter_clause("request", "threeDSServerTransID", FilterTypes::Like) + .add_negative_filter_clause("authentication_status", "pending") .switch()?; time_range @@ -68,9 +74,9 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index 61b10e6fb9e..c08618cc0d0 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -1,8 +1,7 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, sdk_events::SdkEventNames, Granularity, - TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -29,14 +28,13 @@ where { async fn load_metrics( &self, - _merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, + merchant_id: &common_utils::id_type::MerchantId, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,42 +43,36 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .switch()?; - } - query_builder - .add_filter_clause("merchant_id", publishable_key) - .switch()?; - - query_builder - .add_bool_filter_clause("first_event", 1) + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) .switch()?; query_builder - .add_filter_clause("category", "USER_EVENT") + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) .switch()?; query_builder - .add_filter_clause("log_type", "INFO") + .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder - .add_filter_clause("event_name", SdkEventNames::DisplayThreeDsSdk) + .add_filter_clause("trans_status", "C".to_string()) .switch()?; - query_builder.add_filter_clause("value", "C").switch()?; - time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index c5bf7bf81ce..3fb75efd562 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -1,9 +1,9 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::{AuthEventFlows, AuthEventMetricsBucketIdentifier}, - Granularity, TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; +use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -30,13 +30,12 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, - _publishable_key: &str, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::ApiEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,22 +44,30 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .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()?; query_builder .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder - .add_filter_clause("api_flow", AuthEventFlows::IncomingWebhookReceive) + .add_filter_clause("authentication_status", AuthenticationStatus::Success) .switch()?; query_builder - .add_filter_clause("visitParamExtractRaw(request, 'transStatus')", "\"Y\"") + .add_filter_clause("trans_status", "C".to_string()) .switch()?; time_range @@ -68,9 +75,9 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index c08cc511e16..8859c60fc37 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -1,8 +1,7 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, sdk_events::SdkEventNames, Granularity, - TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -29,14 +28,13 @@ where { async fn load_metrics( &self, - _merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, + merchant_id: &common_utils::id_type::MerchantId, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,34 +43,26 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .switch()?; - } - - query_builder - .add_filter_clause("merchant_id", publishable_key) - .switch()?; - query_builder - .add_bool_filter_clause("first_event", 1) - .switch()?; - - query_builder - .add_filter_clause("category", "USER_EVENT") + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) .switch()?; query_builder - .add_filter_clause("log_type", "INFO") + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) .switch()?; query_builder - .add_filter_clause("event_name", SdkEventNames::DisplayThreeDsSdk) + .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder - .add_negative_filter_clause("value", "C") + .add_filter_clause("trans_status", "Y".to_string()) .switch()?; time_range @@ -80,9 +70,9 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index b310567c9db..3d5d894e7dd 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -1,9 +1,9 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::{AuthEventFlows, AuthEventMetricsBucketIdentifier}, - Granularity, TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; +use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -30,13 +30,12 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, - _publishable_key: &str, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::ApiEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,22 +44,30 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .switch()?; - } + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; query_builder - .add_filter_clause("merchant_id", merchant_id.get_string_repr()) + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) .switch()?; query_builder - .add_filter_clause("api_flow", AuthEventFlows::PaymentsExternalAuthentication) + .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder - .add_filter_clause("visitParamExtractRaw(response, 'transStatus')", "\"Y\"") + .add_filter_clause("trans_status", "Y".to_string()) + .switch()?; + + query_builder + .add_filter_clause("authentication_status", AuthenticationStatus::Success) .switch()?; time_range @@ -68,9 +75,9 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index cd870c12b23..1c86e7cbcf6 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -138,6 +138,7 @@ impl AnalyticsDataSource for ClickhouseClient { | AnalyticsCollection::FraudCheck | AnalyticsCollection::PaymentIntent | AnalyticsCollection::PaymentIntentSessionized + | AnalyticsCollection::Authentications | AnalyticsCollection::Dispute => { TableEngine::CollapsingMergeTree { sign: "sign_flag" } } @@ -457,6 +458,7 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection { Self::Dispute => Ok("dispute".to_string()), Self::DisputeSessionized => Ok("sessionizer_dispute".to_string()), Self::ActivePaymentsAnalytics => Ok("active_payments".to_string()), + Self::Authentications => Ok("authentications".to_string()), } } } diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 0ad8886b820..ef7108e8ef7 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -909,7 +909,6 @@ impl AnalyticsProvider { &self, metric: &AuthEventMetrics, merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { @@ -917,14 +916,13 @@ impl AnalyticsProvider { Self::Sqlx(_pool) => Err(report!(MetricsError::NotImplemented)), Self::Clickhouse(pool) => { metric - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::CombinedCkh(_sqlx_pool, ckh_pool) | Self::CombinedSqlx(_sqlx_pool, ckh_pool) => { metric .load_metrics( merchant_id, - publishable_key, granularity, // Since API events are ckh only use ckh here time_range, diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index f449ba2f9b5..59cb8743448 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -19,6 +19,7 @@ use api_models::{ }, refunds::RefundStatus, }; +use common_enums::{AuthenticationStatus, TransactionStatus}; use common_utils::{ errors::{CustomResult, ParsingError}, id_type::{MerchantId, OrganizationId, ProfileId}, @@ -502,6 +503,8 @@ impl_to_sql_for_to_string!( Currency, RefundType, FrmTransactionType, + TransactionStatus, + AuthenticationStatus, Flow, &String, &bool, diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 653d019adeb..f3143840f34 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -1034,6 +1034,8 @@ impl ToSql<SqlxClient> for AnalyticsCollection { Self::Dispute => Ok("dispute".to_string()), Self::DisputeSessionized => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("DisputeSessionized table is not implemented for Sqlx"))?, + Self::Authentications => Err(error_stack::report!(ParsingError::UnknownError) + .attach_printable("Authentications table is not implemented for Sqlx"))?, } } } diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs index 86056338106..7bf8fc7d3c3 100644 --- a/crates/analytics/src/types.rs +++ b/crates/analytics/src/types.rs @@ -37,6 +37,7 @@ pub enum AnalyticsCollection { PaymentIntentSessionized, ConnectorEvents, OutgoingWebhookEvent, + Authentications, Dispute, DisputeSessionized, ApiEventsAnalytics, diff --git a/crates/api_models/src/analytics/auth_events.rs b/crates/api_models/src/analytics/auth_events.rs index 7791a2f3cd5..6f527551348 100644 --- a/crates/api_models/src/analytics/auth_events.rs +++ b/crates/api_models/src/analytics/auth_events.rs @@ -5,6 +5,29 @@ use std::{ use super::NameDescription; +#[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 AuthEventDimensions { + #[serde(rename = "authentication_status")] + AuthenticationStatus, + #[serde(rename = "trans_status")] + TransactionStatus, +} + #[derive( Clone, Debug, @@ -20,7 +43,7 @@ use super::NameDescription; #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum AuthEventMetrics { - ThreeDsSdkCount, + AuthenticationCount, AuthenticationAttemptCount, AuthenticationSuccessCount, ChallengeFlowCount, @@ -48,7 +71,7 @@ pub enum AuthEventFlows { } pub mod metric_behaviour { - pub struct ThreeDsSdkCount; + pub struct AuthenticationCount; pub struct AuthenticationAttemptCount; pub struct AuthenticationSuccessCount; pub struct ChallengeFlowCount; @@ -96,7 +119,7 @@ impl PartialEq for AuthEventMetricsBucketIdentifier { #[derive(Debug, serde::Serialize)] pub struct AuthEventMetricsBucketValue { - pub three_ds_sdk_count: Option<u64>, + pub authentication_count: Option<u64>, pub authentication_attempt_count: Option<u64>, pub authentication_success_count: Option<u64>, pub challenge_flow_count: Option<u64>, diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 8fb4f2ac2c1..deaf84bb009 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -975,7 +975,6 @@ pub mod routes { analytics::auth_events::get_metrics( &state.pool, auth.merchant_account.get_id(), - &auth.merchant_account.publishable_key, req, ) .await
2025-03-05T09:12:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Refactored and re-wrote the authentication related analytics. The table being queried is now `authentications`. The following metrics were modified: - Authentication Attempt Count - Authentication Count - Authentication Success Count - Challenge Attempt Count - Challenge Flow Count - Challenge Success Count - Frictionless Flow Count - Frictionless Success Count ### 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). --> Get better insights into authentications related data through analytics ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Hit the following curls: #### Authentication Attempt Count: ```bash curl --location 'http://localhost:8080/analytics/v1/metrics/auth_events' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWFiNWIxNDEtNjQwOC00YTUyLTk2MjMtNTVhNTgxMTU1M2U4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQwNDE0OTA5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTI3NDY4NSwib3JnX2lkIjoib3JnX1QwSEtYNHYyRGFRT2lHUDVwRk52IiwicHJvZmlsZV9pZCI6InByb19xOWc2ZW1xcGM3YjQxTG83VVhweCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.LIExs1jjG6N5AFu5_S3oiuy77fWF0IbJmNGbK8HHLXI' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2025-02-01T18:30:00Z", "endTime": "2025-02-28T09:22:00Z" }, "source": "BATCH", "timeSeries": { "granularity": "G_ONEDAY" }, "metrics": [ "authentication_attempt_count" ], "delta": true } ]' ``` Sample Output: ```json { "queryData": [ { "authentication_count": null, "authentication_attempt_count": 80, "authentication_success_count": null, "challenge_flow_count": null, "challenge_attempt_count": null, "challenge_success_count": null, "frictionless_flow_count": null, "frictionless_success_count": null, "time_bucket": null } ], "metaData": [ { "current_time_range": { "start_time": "2025-02-01T18:30:00.000Z", "end_time": "2025-02-28T09:22:00.000Z" } } ] } ``` #### Authentication Count: ```bash curl --location 'http://localhost:8080/analytics/v1/metrics/auth_events' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWFiNWIxNDEtNjQwOC00YTUyLTk2MjMtNTVhNTgxMTU1M2U4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQwNDE0OTA5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTI3NDY4NSwib3JnX2lkIjoib3JnX1QwSEtYNHYyRGFRT2lHUDVwRk52IiwicHJvZmlsZV9pZCI6InByb19xOWc2ZW1xcGM3YjQxTG83VVhweCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.LIExs1jjG6N5AFu5_S3oiuy77fWF0IbJmNGbK8HHLXI' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2025-02-01T18:30:00Z", "endTime": "2025-02-28T09:22:00Z" }, "source": "BATCH", "timeSeries": { "granularity": "G_ONEDAY" }, "metrics": [ "authentication_count" ], "delta": true } ]' ``` Sample Output: ```json { "queryData": [ { "authentication_count": 95, "authentication_attempt_count": null, "authentication_success_count": null, "challenge_flow_count": null, "challenge_attempt_count": null, "challenge_success_count": null, "frictionless_flow_count": null, "frictionless_success_count": null, "time_bucket": null } ], "metaData": [ { "current_time_range": { "start_time": "2025-02-01T18:30:00.000Z", "end_time": "2025-02-28T09:22:00.000Z" } } ] } ``` #### Authentication Success Count: ```bash curl --location 'http://localhost:8080/analytics/v1/metrics/auth_events' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWFiNWIxNDEtNjQwOC00YTUyLTk2MjMtNTVhNTgxMTU1M2U4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQwNDE0OTA5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTI3NDY4NSwib3JnX2lkIjoib3JnX1QwSEtYNHYyRGFRT2lHUDVwRk52IiwicHJvZmlsZV9pZCI6InByb19xOWc2ZW1xcGM3YjQxTG83VVhweCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.LIExs1jjG6N5AFu5_S3oiuy77fWF0IbJmNGbK8HHLXI' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2025-02-01T18:30:00Z", "endTime": "2025-02-28T09:22:00Z" }, "source": "BATCH", "timeSeries": { "granularity": "G_ONEDAY" }, "metrics": [ "authentication_success_count" ], "delta": true } ]' ``` Sample Output: ```json { "queryData": [ { "authentication_count": null, "authentication_attempt_count": null, "authentication_success_count": 75, "challenge_flow_count": null, "challenge_attempt_count": null, "challenge_success_count": null, "frictionless_flow_count": null, "frictionless_success_count": null, "time_bucket": null } ], "metaData": [ { "current_time_range": { "start_time": "2025-02-01T18:30:00.000Z", "end_time": "2025-02-28T09:22:00.000Z" } } ] } ``` #### Challenge Flow Count: ```bash curl --location 'http://localhost:8080/analytics/v1/metrics/auth_events' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWFiNWIxNDEtNjQwOC00YTUyLTk2MjMtNTVhNTgxMTU1M2U4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQwNDE0OTA5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTI3NDY4NSwib3JnX2lkIjoib3JnX1QwSEtYNHYyRGFRT2lHUDVwRk52IiwicHJvZmlsZV9pZCI6InByb19xOWc2ZW1xcGM3YjQxTG83VVhweCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.LIExs1jjG6N5AFu5_S3oiuy77fWF0IbJmNGbK8HHLXI' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2025-02-01T18:30:00Z", "endTime": "2025-02-28T09:22:00Z" }, "source": "BATCH", "timeSeries": { "granularity": "G_ONEDAY" }, "metrics": [ "challenge_flow_count" ], "delta": true } ]' ``` Sample Output: ```json { "queryData": [ { "authentication_count": null, "authentication_attempt_count": null, "authentication_success_count": null, "challenge_flow_count": 1, "challenge_attempt_count": null, "challenge_success_count": null, "frictionless_flow_count": null, "frictionless_success_count": null, "time_bucket": null } ], "metaData": [ { "current_time_range": { "start_time": "2025-02-01T18:30:00.000Z", "end_time": "2025-02-28T09:22:00.000Z" } } ] } ``` #### Challenge Attempt Count: ```bash curl --location 'http://localhost:8080/analytics/v1/metrics/auth_events' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWFiNWIxNDEtNjQwOC00YTUyLTk2MjMtNTVhNTgxMTU1M2U4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQwNDE0OTA5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTI3NDY4NSwib3JnX2lkIjoib3JnX1QwSEtYNHYyRGFRT2lHUDVwRk52IiwicHJvZmlsZV9pZCI6InByb19xOWc2ZW1xcGM3YjQxTG83VVhweCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.LIExs1jjG6N5AFu5_S3oiuy77fWF0IbJmNGbK8HHLXI' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2025-02-01T18:30:00Z", "endTime": "2025-02-28T09:22:00Z" }, "source": "BATCH", "timeSeries": { "granularity": "G_ONEDAY" }, "metrics": [ "challenge_attempt_count" ], "delta": true } ]' ``` Sample Output: ```json { "queryData": [ { "authentication_count": null, "authentication_attempt_count": null, "authentication_success_count": null, "challenge_flow_count": null, "challenge_attempt_count": 1, "challenge_success_count": null, "frictionless_flow_count": null, "frictionless_success_count": null, "time_bucket": null } ], "metaData": [ { "current_time_range": { "start_time": "2025-02-01T18:30:00.000Z", "end_time": "2025-02-28T09:22:00.000Z" } } ] } ``` #### Challenge Sccess Count: ```bash curl --location 'http://localhost:8080/analytics/v1/metrics/auth_events' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWFiNWIxNDEtNjQwOC00YTUyLTk2MjMtNTVhNTgxMTU1M2U4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQwNDE0OTA5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTI3NDY4NSwib3JnX2lkIjoib3JnX1QwSEtYNHYyRGFRT2lHUDVwRk52IiwicHJvZmlsZV9pZCI6InByb19xOWc2ZW1xcGM3YjQxTG83VVhweCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.LIExs1jjG6N5AFu5_S3oiuy77fWF0IbJmNGbK8HHLXI' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2025-02-01T18:30:00Z", "endTime": "2025-02-28T09:22:00Z" }, "source": "BATCH", "timeSeries": { "granularity": "G_ONEDAY" }, "metrics": [ "challenge_success_count" ], "delta": true } ]' ``` Sample Output: ```json { "queryData": [ { "authentication_count": null, "authentication_attempt_count": null, "authentication_success_count": null, "challenge_flow_count": null, "challenge_attempt_count": null, "challenge_success_count": 1, "frictionless_flow_count": null, "frictionless_success_count": null, "time_bucket": null } ], "metaData": [ { "current_time_range": { "start_time": "2025-02-01T18:30:00.000Z", "end_time": "2025-02-28T09:22:00.000Z" } } ] } ``` #### Frictionless Flow Count: ```bash curl --location 'http://localhost:8080/analytics/v1/metrics/auth_events' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWFiNWIxNDEtNjQwOC00YTUyLTk2MjMtNTVhNTgxMTU1M2U4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQwNDE0OTA5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTI3NDY4NSwib3JnX2lkIjoib3JnX1QwSEtYNHYyRGFRT2lHUDVwRk52IiwicHJvZmlsZV9pZCI6InByb19xOWc2ZW1xcGM3YjQxTG83VVhweCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.LIExs1jjG6N5AFu5_S3oiuy77fWF0IbJmNGbK8HHLXI' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2025-02-01T18:30:00Z", "endTime": "2025-02-28T09:22:00Z" }, "source": "BATCH", "timeSeries": { "granularity": "G_ONEDAY" }, "metrics": [ "frictionless_flow_count" ], "delta": true } ]' ``` Sample Output: ```json { "queryData": [ { "authentication_count": null, "authentication_attempt_count": null, "authentication_success_count": null, "challenge_flow_count": null, "challenge_attempt_count": null, "challenge_success_count": null, "frictionless_flow_count": 74, "frictionless_success_count": null, "time_bucket": null } ], "metaData": [ { "current_time_range": { "start_time": "2025-02-01T18:30:00.000Z", "end_time": "2025-02-28T09:22:00.000Z" } } ] } ``` #### Frictionless Success Count: ```bash curl --location 'http://localhost:8080/analytics/v1/metrics/auth_events' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWFiNWIxNDEtNjQwOC00YTUyLTk2MjMtNTVhNTgxMTU1M2U4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQwNDE0OTA5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTI3NDY4NSwib3JnX2lkIjoib3JnX1QwSEtYNHYyRGFRT2lHUDVwRk52IiwicHJvZmlsZV9pZCI6InByb19xOWc2ZW1xcGM3YjQxTG83VVhweCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.LIExs1jjG6N5AFu5_S3oiuy77fWF0IbJmNGbK8HHLXI' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2025-02-01T18:30:00Z", "endTime": "2025-02-28T09:22:00Z" }, "source": "BATCH", "timeSeries": { "granularity": "G_ONEDAY" }, "metrics": [ "frictionless_success_count" ], "delta": true } ]' ``` Sample Output: ```json { "queryData": [ { "authentication_count": null, "authentication_attempt_count": null, "authentication_success_count": null, "challenge_flow_count": null, "challenge_attempt_count": null, "challenge_success_count": null, "frictionless_flow_count": null, "frictionless_success_count": 74, "time_bucket": null } ], "metaData": [ { "current_time_range": { "start_time": "2025-02-01T18:30:00.000Z", "end_time": "2025-02-28T09:22:00.000Z" } } ] } ``` Queries: #### Authentication Attempt Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_status != 'pending' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Authentication Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Authentication Success Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_status = 'success' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Challenge Attempt Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND trans_status = 'C' AND authentication_status != 'pending' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Challenge Flow Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND trans_status = 'C' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Challenge Success Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND authentication_status = 'success' AND trans_status = 'C' AND created_at >= '1726079400' AND created_at <= '1727256120' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Frictionless Flow Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND trans_status = 'Y' AND created_at >= '1738402351' AND created_at <= '1740216751' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` #### Frictionless Success Count: ```bash SELECT sum(sign_flag) as count, min(created_at) as start_bucket, max(created_at) as end_bucket FROM authentications WHERE ( merchant_id = 'merchant_1740414909' AND trans_status = 'Y' AND authentication_status = 'success' AND created_at >= '1738402351' AND created_at <= '1740216751' ) GROUP BY toStartOfDay(created_at) HAVING sum(sign_flag) >= '1' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
30f321bc2001264f5197172428ecae79896ad2f5
30f321bc2001264f5197172428ecae79896ad2f5
juspay/hyperswitch
juspay__hyperswitch-7407
Bug: [FEATURE]: Add `Payment Method - Delete` endpoint to payment methods session for V2 Required for Payment Methods Service
diff --git a/api-reference-v2/api-reference/payment-method-session/payment-method-session--delete-a-saved-payment-method.mdx b/api-reference-v2/api-reference/payment-method-session/payment-method-session--delete-a-saved-payment-method.mdx new file mode 100644 index 00000000000..2f9e800ebe8 --- /dev/null +++ b/api-reference-v2/api-reference/payment-method-session/payment-method-session--delete-a-saved-payment-method.mdx @@ -0,0 +1,3 @@ +--- +openapi: delete /v2/payment-method-session/:id +--- diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json index 2b0997326d8..d0ad2e87996 100644 --- a/api-reference-v2/mint.json +++ b/api-reference-v2/mint.json @@ -67,7 +67,8 @@ "api-reference/payment-method-session/payment-method-session--retrieve", "api-reference/payment-method-session/payment-method-session--list-payment-methods", "api-reference/payment-method-session/payment-method-session--update-a-saved-payment-method", - "api-reference/payment-method-session/payment-method-session--confirm-a-payment-method-session" + "api-reference/payment-method-session/payment-method-session--confirm-a-payment-method-session", + "api-reference/payment-method-session/payment-method-session--delete-a-saved-payment-method" ] }, { diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 9467ac0820b..e2cfb06b6e4 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -2960,6 +2960,62 @@ "ephemeral_key": [] } ] + }, + "delete": { + "tags": [ + "Payment Method Session" + ], + "summary": "Payment Method Session - Delete a saved payment method", + "description": "Delete a saved payment method from the given payment method session.", + "operationId": "Delete a saved payment method", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "The unique identifier for the Payment Method Session", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodSessionDeleteSavedPaymentMethod" + }, + "examples": { + "Update the card holder name": { + "value": { + "payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The payment method has been updated successfully", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentMethodDeleteResponse" + } + } + } + }, + "404": { + "description": "The request is invalid" + } + }, + "security": [ + { + "ephemeral_key": [] + } + ] } }, "/v2/payment-method-session/:id/list-payment-methods": { @@ -4457,15 +4513,19 @@ "AuthenticationDetails": { "type": "object", "required": [ - "status", - "error" + "status" ], "properties": { "status": { "$ref": "#/components/schemas/IntentStatus" }, "error": { - "$ref": "#/components/schemas/ErrorDetails" + "allOf": [ + { + "$ref": "#/components/schemas/ErrorDetails" + } + ], + "nullable": true } } }, @@ -15602,6 +15662,19 @@ } } }, + "PaymentMethodSessionDeleteSavedPaymentMethod": { + "type": "object", + "required": [ + "payment_method_id" + ], + "properties": { + "payment_method_id": { + "type": "string", + "description": "The payment method id of the payment method to be updated", + "example": "12345_pm_01926c58bc6e77c09e809964e72af8c8" + } + } + }, "PaymentMethodSessionRequest": { "type": "object", "required": [ diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index d665337fda0..2dbe16bfaa6 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -2781,6 +2781,14 @@ pub struct PaymentMethodSessionUpdateSavedPaymentMethod { pub payment_method_update_request: PaymentMethodUpdate, } +#[cfg(feature = "v2")] +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct PaymentMethodSessionDeleteSavedPaymentMethod { + /// The payment method id of the payment method to be updated + #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] + pub payment_method_id: id_type::GlobalPaymentMethodId, +} + #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionConfirmRequest { @@ -2858,6 +2866,6 @@ pub struct AuthenticationDetails { pub status: common_enums::IntentStatus, /// Error details of the authentication - #[schema(value_type = ErrorDetails)] + #[schema(value_type = Option<ErrorDetails>)] pub error: Option<payments::ErrorDetails>, } diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index ff4459ac56f..a84f04dc6c5 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -143,6 +143,7 @@ Never share your secret api keys. Keep them guarded and secure. routes::payment_method::payment_method_session_retrieve, routes::payment_method::payment_method_session_list_payment_methods, routes::payment_method::payment_method_session_update_saved_payment_method, + routes::payment_method::payment_method_session_delete_saved_payment_method, routes::payment_method::payment_method_session_confirm, //Routes for refunds @@ -212,6 +213,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::PaymentMethodCreate, api_models::payment_methods::PaymentMethodIntentCreate, api_models::payment_methods::PaymentMethodIntentConfirm, + api_models::payment_methods::AuthenticationDetails, api_models::payment_methods::PaymentMethodResponse, api_models::payment_methods::PaymentMethodResponseData, api_models::payment_methods::CustomerPaymentMethod, @@ -697,6 +699,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::feature_matrix::CardSpecificFeatures, api_models::feature_matrix::SupportedPaymentMethod, api_models::payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod, + api_models::payment_methods::PaymentMethodSessionDeleteSavedPaymentMethod, common_utils::types::BrowserInformation, api_models::enums::TokenizationType, api_models::enums::NetworkTokenizationToggle, diff --git a/crates/openapi/src/routes/payment_method.rs b/crates/openapi/src/routes/payment_method.rs index cf1cd15346f..6dcf3b67753 100644 --- a/crates/openapi/src/routes/payment_method.rs +++ b/crates/openapi/src/routes/payment_method.rs @@ -444,6 +444,35 @@ pub fn payment_method_session_list_payment_methods() {} )] pub fn payment_method_session_update_saved_payment_method() {} +/// Payment Method Session - Delete a saved payment method +/// +/// Delete a saved payment method from the given payment method session. +#[cfg(feature = "v2")] +#[utoipa::path( + delete, + path = "/v2/payment-method-session/:id", + params ( + ("id" = String, Path, description = "The unique identifier for the Payment Method Session"), + ), + request_body( + content = PaymentMethodSessionDeleteSavedPaymentMethod, + examples(( "Update the card holder name" = ( + value =json!( { + "payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3", + } + ) + ))) + ), + responses( + (status = 200, description = "The payment method has been updated successfully", body = PaymentMethodDeleteResponse), + (status = 404, description = "The request is invalid") + ), + tag = "Payment Method Session", + operation_id = "Delete a saved payment method", + security(("ephemeral_key" = [])) +)] +pub fn payment_method_session_delete_saved_payment_method() {} + /// Card network tokenization - Create using raw card data /// /// Create a card network token for a customer and store it as a payment method. diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index eec47ca6255..86e4d8e1646 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -2021,12 +2021,24 @@ pub async fn delete_payment_method( key_store: domain::MerchantKeyStore, merchant_account: domain::MerchantAccount, ) -> RouterResponse<api::PaymentMethodDeleteResponse> { - let db = state.store.as_ref(); - let key_manager_state = &(&state).into(); - let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm_id.payment_method_id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodId")?; + let response = delete_payment_method_core(state, pm_id, key_store, merchant_account).await?; + + Ok(services::ApplicationResponse::Json(response)) +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all)] +pub async fn delete_payment_method_core( + state: SessionState, + pm_id: id_type::GlobalPaymentMethodId, + key_store: domain::MerchantKeyStore, + merchant_account: domain::MerchantAccount, +) -> RouterResult<api::PaymentMethodDeleteResponse> { + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); let payment_method = db .find_payment_method( @@ -2084,7 +2096,7 @@ pub async fn delete_payment_method( let response = api::PaymentMethodDeleteResponse { id: pm_id }; - Ok(services::ApplicationResponse::Json(response)) + Ok(response) } #[cfg(feature = "v2")] @@ -2415,6 +2427,32 @@ pub async fn payment_methods_session_update_payment_method( Ok(services::ApplicationResponse::Json(updated_payment_method)) } +#[cfg(feature = "v2")] +pub async fn payment_methods_session_delete_payment_method( + state: SessionState, + key_store: domain::MerchantKeyStore, + merchant_account: domain::MerchantAccount, + pm_id: id_type::GlobalPaymentMethodId, + payment_method_session_id: id_type::GlobalPaymentMethodSessionId, +) -> RouterResponse<api::PaymentMethodDeleteResponse> { + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + + // Validate if the session still exists + db.get_payment_methods_session(key_manager_state, &key_store, &payment_method_session_id) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "payment methods session does not exist or has expired".to_string(), + }) + .attach_printable("Failed to retrieve payment methods session from db")?; + + let response = delete_payment_method_core(state, pm_id, key_store, merchant_account) + .await + .attach_printable("Failed to delete saved payment method")?; + + Ok(services::ApplicationResponse::Json(response)) +} + #[cfg(feature = "v2")] fn construct_zero_auth_payments_request( confirm_request: &payment_methods::PaymentMethodSessionConfirmRequest, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index c4896bed498..c6ba89dd8de 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1332,7 +1332,10 @@ impl PaymentMethodSession { .service( web::resource("") .route(web::get().to(payment_methods::payment_methods_session_retrieve)) - .route(web::put().to(payment_methods::payment_methods_session_update)), + .route(web::put().to(payment_methods::payment_methods_session_update)) + .route(web::delete().to( + payment_methods::payment_method_session_delete_saved_payment_method, + )), ) .service(web::resource("/list-payment-methods").route( web::get().to(payment_methods::payment_method_session_list_payment_methods), diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 1cc3442b74b..1c3e23c2b03 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -331,6 +331,7 @@ impl From<Flow> for ApiIdentifier { | Flow::PaymentMethodSessionRetrieve | Flow::PaymentMethodSessionConfirm | Flow::PaymentMethodSessionUpdateSavedPaymentMethod + | Flow::PaymentMethodSessionDeleteSavedPaymentMethod | Flow::PaymentMethodSessionUpdate => Self::PaymentMethodSession, } } diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index ec5e1dacf0a..6b60a05c6c1 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -1327,3 +1327,46 @@ pub async fn payment_method_session_update_saved_payment_method( )) .await } + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionUpdateSavedPaymentMethod))] +pub async fn payment_method_session_delete_saved_payment_method( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<id_type::GlobalPaymentMethodSessionId>, + json_payload: web::Json< + api_models::payment_methods::PaymentMethodSessionDeleteSavedPaymentMethod, + >, +) -> HttpResponse { + let flow = Flow::PaymentMethodSessionDeleteSavedPaymentMethod; + let payload = json_payload.into_inner(); + let payment_method_session_id = path.into_inner(); + + let request = PaymentMethodsSessionGenericRequest { + payment_method_session_id: payment_method_session_id.clone(), + request: payload, + }; + + Box::pin(api::server_wrap( + flow, + state, + &req, + request, + |state, auth: auth::AuthenticationData, request, _| { + payment_methods_routes::payment_methods_session_delete_payment_method( + state, + auth.key_store, + auth.merchant_account, + request.request.payment_method_id, + request.payment_method_session_id, + ) + }, + &auth::V2ClientAuth( + common_utils::types::authentication::ResourceId::PaymentMethodSession( + payment_method_session_id, + ), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 26f88217e4a..890dcae12c6 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -566,6 +566,8 @@ pub enum Flow { PaymentMethodSessionUpdate, /// Update a saved payment method using the payment methods session PaymentMethodSessionUpdateSavedPaymentMethod, + /// Delete a saved payment method using the payment methods session + PaymentMethodSessionDeleteSavedPaymentMethod, /// Confirm a payment method session with payment method data PaymentMethodSessionConfirm, /// Create Cards Info flow
2025-03-03T12:56:33Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This endpoint allows deleting saved payment methods for a customer ### 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 #7407 ## 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. Request: ``` curl --location --request DELETE 'http://localhost:8080/v2/payment-methods-session/12345_pms_01955b8bed367ee09f81e053cde47593' \ --header 'Authorization: publishable-key=pk_dev_16fea0a9bf5447ed9f25aa835565f285,client-secret=cs_01955b8bed37771282694611c1db81e5' \ --header 'X-Profile-Id: pro_0xaQT1sPjecc284Qtf5N' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_DfzEs7oHcqmWiWeKTPZ8RqHnWyuuPkEheYExXkY1AO1H5EMdkgNcfTFe3JU4vFLt' \ --data '{ "payment_method_id": "12345_pm_01955b8c21d37b53b999e934b53fffae" }' ``` 2. Response: ```json {"id":"12345_pm_01955b8c21d37b53b999e934b53fffae"} ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
8bf0f8df35dccc07749df380d183ed21b0bc6c8e
8bf0f8df35dccc07749df380d183ed21b0bc6c8e
juspay/hyperswitch
juspay__hyperswitch-7447
Bug: feat(analytics): refactor and rewrite authentication related analytics hotfix Need to refactor and re-write the authentication related analytics. The table which should be queried is authentications. The existing metrics need to be modified and a few new metrics should be created to provide enhanced insights into authentication related data.
diff --git a/crates/analytics/src/auth_events/accumulator.rs b/crates/analytics/src/auth_events/accumulator.rs index 2958030c8da..446ac6ac8c2 100644 --- a/crates/analytics/src/auth_events/accumulator.rs +++ b/crates/analytics/src/auth_events/accumulator.rs @@ -4,7 +4,7 @@ use super::metrics::AuthEventMetricRow; #[derive(Debug, Default)] pub struct AuthEventMetricsAccumulator { - pub three_ds_sdk_count: CountAccumulator, + pub authentication_count: CountAccumulator, pub authentication_attempt_count: CountAccumulator, pub authentication_success_count: CountAccumulator, pub challenge_flow_count: CountAccumulator, @@ -47,7 +47,7 @@ impl AuthEventMetricAccumulator for CountAccumulator { impl AuthEventMetricsAccumulator { pub fn collect(self) -> AuthEventMetricsBucketValue { AuthEventMetricsBucketValue { - three_ds_sdk_count: self.three_ds_sdk_count.collect(), + authentication_count: self.authentication_count.collect(), authentication_attempt_count: self.authentication_attempt_count.collect(), authentication_success_count: self.authentication_success_count.collect(), challenge_flow_count: self.challenge_flow_count.collect(), diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs index 3fd134bc498..75bdf4de149 100644 --- a/crates/analytics/src/auth_events/core.rs +++ b/crates/analytics/src/auth_events/core.rs @@ -18,7 +18,6 @@ use crate::{ pub async fn get_metrics( pool: &AnalyticsProvider, merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &String, req: GetAuthEventMetricRequest, ) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> { let mut metrics_accumulator: HashMap< @@ -30,14 +29,12 @@ pub async fn get_metrics( for metric_type in req.metrics.iter().cloned() { let req = req.clone(); let merchant_id_scoped = merchant_id.to_owned(); - let publishable_key_scoped = publishable_key.to_owned(); let pool = pool.clone(); set.spawn(async move { let data = pool .get_auth_event_metrics( &metric_type, &merchant_id_scoped, - &publishable_key_scoped, req.time_series.map(|t| t.granularity), &req.time_range, ) @@ -56,8 +53,8 @@ pub async fn get_metrics( for (id, value) in data? { let metrics_builder = metrics_accumulator.entry(id).or_default(); match metric { - AuthEventMetrics::ThreeDsSdkCount => metrics_builder - .three_ds_sdk_count + AuthEventMetrics::AuthenticationCount => metrics_builder + .authentication_count .add_metrics_bucket(&value), AuthEventMetrics::AuthenticationAttemptCount => metrics_builder .authentication_attempt_count diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index 4a1fbd0e147..f3f0354818c 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -12,22 +12,22 @@ use crate::{ }; mod authentication_attempt_count; +mod authentication_count; mod authentication_success_count; mod challenge_attempt_count; mod challenge_flow_count; mod challenge_success_count; mod frictionless_flow_count; mod frictionless_success_count; -mod three_ds_sdk_count; use authentication_attempt_count::AuthenticationAttemptCount; +use authentication_count::AuthenticationCount; use authentication_success_count::AuthenticationSuccessCount; use challenge_attempt_count::ChallengeAttemptCount; use challenge_flow_count::ChallengeFlowCount; use challenge_success_count::ChallengeSuccessCount; use frictionless_flow_count::FrictionlessFlowCount; use frictionless_success_count::FrictionlessSuccessCount; -use three_ds_sdk_count::ThreeDsSdkCount; #[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)] pub struct AuthEventMetricRow { @@ -45,7 +45,6 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, @@ -65,50 +64,49 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { match self { - Self::ThreeDsSdkCount => { - ThreeDsSdkCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + Self::AuthenticationCount => { + AuthenticationCount + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::AuthenticationAttemptCount => { AuthenticationAttemptCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::AuthenticationSuccessCount => { AuthenticationSuccessCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::ChallengeFlowCount => { ChallengeFlowCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::ChallengeAttemptCount => { ChallengeAttemptCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::ChallengeSuccessCount => { ChallengeSuccessCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::FrictionlessFlowCount => { FrictionlessFlowCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::FrictionlessSuccessCount => { FrictionlessSuccessCount - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } } diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index 5faeefec686..2d34344905e 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -1,9 +1,9 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, sdk_events::SdkEventNames, Granularity, - TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; +use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -29,14 +29,13 @@ where { async fn load_metrics( &self, - _merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, + merchant_id: &common_utils::id_type::MerchantId, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,30 +44,26 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .switch()?; - } - - query_builder - .add_filter_clause("merchant_id", publishable_key) - .switch()?; - query_builder - .add_bool_filter_clause("first_event", 1) + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) .switch()?; query_builder - .add_filter_clause("event_name", SdkEventNames::AuthenticationCallInit) + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) .switch()?; query_builder - .add_filter_clause("log_type", "INFO") + .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder - .add_filter_clause("category", "API") + .add_negative_filter_clause("authentication_status", AuthenticationStatus::Pending) .switch()?; time_range @@ -76,9 +71,9 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs b/crates/analytics/src/auth_events/metrics/authentication_count.rs similarity index 69% rename from crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs rename to crates/analytics/src/auth_events/metrics/authentication_count.rs index 4ce10c9aad3..9f2311f5638 100644 --- a/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_count.rs @@ -1,8 +1,7 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, sdk_events::SdkEventNames, Granularity, - TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -15,10 +14,10 @@ use crate::{ }; #[derive(Default)] -pub(super) struct ThreeDsSdkCount; +pub(super) struct AuthenticationCount; #[async_trait::async_trait] -impl<T> super::AuthEventMetric<T> for ThreeDsSdkCount +impl<T> super::AuthEventMetric<T> for AuthenticationCount where T: AnalyticsDataSource + super::AuthEventMetricAnalytics, PrimitiveDateTime: ToSql<T>, @@ -29,14 +28,13 @@ where { async fn load_metrics( &self, - _merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, + merchant_id: &common_utils::id_type::MerchantId, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,30 +43,22 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .switch()?; - } - - query_builder - .add_filter_clause("merchant_id", publishable_key) - .switch()?; - query_builder - .add_bool_filter_clause("first_event", 1) - .switch()?; - - query_builder - .add_filter_clause("category", "USER_EVENT") + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) .switch()?; query_builder - .add_filter_clause("log_type", "INFO") + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) .switch()?; query_builder - .add_filter_clause("event_name", SdkEventNames::ThreeDsMethod) + .add_filter_clause("merchant_id", merchant_id) .switch()?; time_range @@ -76,9 +66,9 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index 663473c2d89..e887807f41c 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -1,9 +1,9 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, sdk_events::SdkEventNames, Granularity, - TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; +use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -29,14 +29,13 @@ where { async fn load_metrics( &self, - _merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, + merchant_id: &common_utils::id_type::MerchantId, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,30 +44,26 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .switch()?; - } - - query_builder - .add_filter_clause("merchant_id", publishable_key) - .switch()?; - query_builder - .add_bool_filter_clause("first_event", 1) + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) .switch()?; query_builder - .add_filter_clause("event_name", SdkEventNames::AuthenticationCall) + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) .switch()?; query_builder - .add_filter_clause("log_type", "INFO") + .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder - .add_filter_clause("category", "API") + .add_filter_clause("authentication_status", AuthenticationStatus::Success) .switch()?; time_range @@ -76,9 +71,9 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index 15cd86e5cc8..f1f6a397994 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -1,8 +1,7 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::{AuthEventFlows, AuthEventMetricsBucketIdentifier}, - Granularity, TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -10,7 +9,7 @@ use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ - query::{Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -30,13 +29,12 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, - _publishable_key: &str, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::ApiEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,22 +43,30 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .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()?; query_builder .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder - .add_filter_clause("api_flow", AuthEventFlows::IncomingWebhookReceive) + .add_filter_clause("trans_status", "C".to_string()) .switch()?; query_builder - .add_custom_filter_clause("request", "threeDSServerTransID", FilterTypes::Like) + .add_negative_filter_clause("authentication_status", "pending") .switch()?; time_range @@ -68,9 +74,9 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index 61b10e6fb9e..c08618cc0d0 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -1,8 +1,7 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, sdk_events::SdkEventNames, Granularity, - TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -29,14 +28,13 @@ where { async fn load_metrics( &self, - _merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, + merchant_id: &common_utils::id_type::MerchantId, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,42 +43,36 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .switch()?; - } - query_builder - .add_filter_clause("merchant_id", publishable_key) - .switch()?; - - query_builder - .add_bool_filter_clause("first_event", 1) + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) .switch()?; query_builder - .add_filter_clause("category", "USER_EVENT") + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) .switch()?; query_builder - .add_filter_clause("log_type", "INFO") + .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder - .add_filter_clause("event_name", SdkEventNames::DisplayThreeDsSdk) + .add_filter_clause("trans_status", "C".to_string()) .switch()?; - query_builder.add_filter_clause("value", "C").switch()?; - time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index c5bf7bf81ce..3fb75efd562 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -1,9 +1,9 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::{AuthEventFlows, AuthEventMetricsBucketIdentifier}, - Granularity, TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; +use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -30,13 +30,12 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, - _publishable_key: &str, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::ApiEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,22 +44,30 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .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()?; query_builder .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder - .add_filter_clause("api_flow", AuthEventFlows::IncomingWebhookReceive) + .add_filter_clause("authentication_status", AuthenticationStatus::Success) .switch()?; query_builder - .add_filter_clause("visitParamExtractRaw(request, 'transStatus')", "\"Y\"") + .add_filter_clause("trans_status", "C".to_string()) .switch()?; time_range @@ -68,9 +75,9 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index c08cc511e16..8859c60fc37 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -1,8 +1,7 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::AuthEventMetricsBucketIdentifier, sdk_events::SdkEventNames, Granularity, - TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; @@ -29,14 +28,13 @@ where { async fn load_metrics( &self, - _merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, + merchant_id: &common_utils::id_type::MerchantId, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,34 +43,26 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .switch()?; - } - - query_builder - .add_filter_clause("merchant_id", publishable_key) - .switch()?; - query_builder - .add_bool_filter_clause("first_event", 1) - .switch()?; - - query_builder - .add_filter_clause("category", "USER_EVENT") + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) .switch()?; query_builder - .add_filter_clause("log_type", "INFO") + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) .switch()?; query_builder - .add_filter_clause("event_name", SdkEventNames::DisplayThreeDsSdk) + .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder - .add_negative_filter_clause("value", "C") + .add_filter_clause("trans_status", "Y".to_string()) .switch()?; time_range @@ -80,9 +70,9 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index b310567c9db..3d5d894e7dd 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -1,9 +1,9 @@ use std::collections::HashSet; use api_models::analytics::{ - auth_events::{AuthEventFlows, AuthEventMetricsBucketIdentifier}, - Granularity, TimeRange, + auth_events::AuthEventMetricsBucketIdentifier, Granularity, TimeRange, }; +use common_enums::AuthenticationStatus; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -30,13 +30,12 @@ where async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, - _publishable_key: &str, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = - QueryBuilder::new(AnalyticsCollection::ApiEventsAnalytics); + QueryBuilder::new(AnalyticsCollection::Authentications); query_builder .add_select_column(Aggregate::Count { @@ -45,22 +44,30 @@ where }) .switch()?; - if let Some(granularity) = granularity { - query_builder - .add_granularity_in_mins(granularity) - .switch()?; - } + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; query_builder - .add_filter_clause("merchant_id", merchant_id.get_string_repr()) + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) .switch()?; query_builder - .add_filter_clause("api_flow", AuthEventFlows::PaymentsExternalAuthentication) + .add_filter_clause("merchant_id", merchant_id) .switch()?; query_builder - .add_filter_clause("visitParamExtractRaw(response, 'transStatus')", "\"Y\"") + .add_filter_clause("trans_status", "Y".to_string()) + .switch()?; + + query_builder + .add_filter_clause("authentication_status", AuthenticationStatus::Success) .switch()?; time_range @@ -68,9 +75,9 @@ where .attach_printable("Error filtering time range") .switch()?; - if let Some(_granularity) = granularity.as_ref() { - query_builder - .add_group_by_clause("time_bucket") + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) .attach_printable("Error adding granularity") .switch()?; } diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index cd870c12b23..1c86e7cbcf6 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -138,6 +138,7 @@ impl AnalyticsDataSource for ClickhouseClient { | AnalyticsCollection::FraudCheck | AnalyticsCollection::PaymentIntent | AnalyticsCollection::PaymentIntentSessionized + | AnalyticsCollection::Authentications | AnalyticsCollection::Dispute => { TableEngine::CollapsingMergeTree { sign: "sign_flag" } } @@ -457,6 +458,7 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection { Self::Dispute => Ok("dispute".to_string()), Self::DisputeSessionized => Ok("sessionizer_dispute".to_string()), Self::ActivePaymentsAnalytics => Ok("active_payments".to_string()), + Self::Authentications => Ok("authentications".to_string()), } } } diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 0ad8886b820..ef7108e8ef7 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -909,7 +909,6 @@ impl AnalyticsProvider { &self, metric: &AuthEventMetrics, merchant_id: &common_utils::id_type::MerchantId, - publishable_key: &str, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { @@ -917,14 +916,13 @@ impl AnalyticsProvider { Self::Sqlx(_pool) => Err(report!(MetricsError::NotImplemented)), Self::Clickhouse(pool) => { metric - .load_metrics(merchant_id, publishable_key, granularity, time_range, pool) + .load_metrics(merchant_id, granularity, time_range, pool) .await } Self::CombinedCkh(_sqlx_pool, ckh_pool) | Self::CombinedSqlx(_sqlx_pool, ckh_pool) => { metric .load_metrics( merchant_id, - publishable_key, granularity, // Since API events are ckh only use ckh here time_range, diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index f449ba2f9b5..59cb8743448 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -19,6 +19,7 @@ use api_models::{ }, refunds::RefundStatus, }; +use common_enums::{AuthenticationStatus, TransactionStatus}; use common_utils::{ errors::{CustomResult, ParsingError}, id_type::{MerchantId, OrganizationId, ProfileId}, @@ -502,6 +503,8 @@ impl_to_sql_for_to_string!( Currency, RefundType, FrmTransactionType, + TransactionStatus, + AuthenticationStatus, Flow, &String, &bool, diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 653d019adeb..f3143840f34 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -1034,6 +1034,8 @@ impl ToSql<SqlxClient> for AnalyticsCollection { Self::Dispute => Ok("dispute".to_string()), Self::DisputeSessionized => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("DisputeSessionized table is not implemented for Sqlx"))?, + Self::Authentications => Err(error_stack::report!(ParsingError::UnknownError) + .attach_printable("Authentications table is not implemented for Sqlx"))?, } } } diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs index 86056338106..7bf8fc7d3c3 100644 --- a/crates/analytics/src/types.rs +++ b/crates/analytics/src/types.rs @@ -37,6 +37,7 @@ pub enum AnalyticsCollection { PaymentIntentSessionized, ConnectorEvents, OutgoingWebhookEvent, + Authentications, Dispute, DisputeSessionized, ApiEventsAnalytics, diff --git a/crates/api_models/src/analytics/auth_events.rs b/crates/api_models/src/analytics/auth_events.rs index 7791a2f3cd5..6f527551348 100644 --- a/crates/api_models/src/analytics/auth_events.rs +++ b/crates/api_models/src/analytics/auth_events.rs @@ -5,6 +5,29 @@ use std::{ use super::NameDescription; +#[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 AuthEventDimensions { + #[serde(rename = "authentication_status")] + AuthenticationStatus, + #[serde(rename = "trans_status")] + TransactionStatus, +} + #[derive( Clone, Debug, @@ -20,7 +43,7 @@ use super::NameDescription; #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum AuthEventMetrics { - ThreeDsSdkCount, + AuthenticationCount, AuthenticationAttemptCount, AuthenticationSuccessCount, ChallengeFlowCount, @@ -48,7 +71,7 @@ pub enum AuthEventFlows { } pub mod metric_behaviour { - pub struct ThreeDsSdkCount; + pub struct AuthenticationCount; pub struct AuthenticationAttemptCount; pub struct AuthenticationSuccessCount; pub struct ChallengeFlowCount; @@ -96,7 +119,7 @@ impl PartialEq for AuthEventMetricsBucketIdentifier { #[derive(Debug, serde::Serialize)] pub struct AuthEventMetricsBucketValue { - pub three_ds_sdk_count: Option<u64>, + pub authentication_count: Option<u64>, pub authentication_attempt_count: Option<u64>, pub authentication_success_count: Option<u64>, pub challenge_flow_count: Option<u64>, diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 8fb4f2ac2c1..deaf84bb009 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -975,7 +975,6 @@ pub mod routes { analytics::auth_events::get_metrics( &state.pool, auth.merchant_account.get_id(), - &auth.merchant_account.publishable_key, req, ) .await
2025-03-06T12:31:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Hotfix PR Original PR: [https://github.com/juspay/hyperswitch/pull/7433](https://github.com/juspay/hyperswitch/pull/7433) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
bf0b9bb9ebd58b85f1f92bd9cb00d8f29cec5d57
bf0b9bb9ebd58b85f1f92bd9cb00d8f29cec5d57
juspay/hyperswitch
juspay__hyperswitch-7405
Bug: [FEATURE] display DuitNow QR code in expected color ### Feature Description DuitNow is a realtime payment method offered in Malaysia. This works using a QR code which is scanned for completing the payment transactions. Displaying the QR code has guidelines mentioned in - https://docs.developer.paynet.my/branding/duitnow/DuitNow%20Brand.pdf Currently, HyperSwitch displays a basic QR code (in black), without following any guidelines. This needs to be rendered correctly on the payment links. - Rendering the QR code in required color (#ED2E67) requires modifying the QR code's image data sent by the connector - Other UI refactors will be made in SDK ### Possible Implementation Confirm API response sends back `qr_code_information` as next_action. This field to contain below items - Modified QR data in specified color - QR image border color - QR image display text ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 97352ead781..59791cc7504 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -15306,6 +15306,14 @@ "type": "string", "description": "The url for Qr code given by the connector" }, + "display_text": { + "type": "string", + "nullable": true + }, + "border_color": { + "type": "string", + "nullable": true + }, "type": { "type": "string", "enum": [ diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 59ea6e97fbb..12da310ac61 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4406,6 +4406,8 @@ pub enum NextActionData { #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, + display_text: Option<String>, + border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { @@ -4493,6 +4495,12 @@ pub enum QrCodeInformation { qr_code_url: Url, display_to_timestamp: Option<i64>, }, + QrColorDataUrl { + color_image_data_url: Url, + display_to_timestamp: Option<i64>, + display_text: Option<String>, + border_color: Option<String>, + }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] diff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rs index e62606b4585..9f653616738 100644 --- a/crates/common_utils/src/errors.rs +++ b/crates/common_utils/src/errors.rs @@ -103,6 +103,9 @@ pub enum QrCodeError { /// Failed to encode data into Qr code #[error("Failed to create Qr code")] FailedToCreateQrCode, + /// Failed to parse hex color + #[error("Invalid hex color code supplied")] + InvalidHexColor, } /// Api Models construction error diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index 2f8a979ba99..5c38a55dc0f 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -41,6 +41,7 @@ const GOOGLEPAY_API_VERSION_MINOR: u8 = 0; const GOOGLEPAY_API_VERSION: u8 = 2; use crate::{ + constants, types::{ PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData, @@ -1725,16 +1726,21 @@ impl From<RefundStatus> for enums::RefundStatus { pub fn get_qr_metadata( response: &DuitNowQrCodeResponse, ) -> CustomResult<Option<serde_json::Value>, errors::ConnectorError> { - let image_data = QrImage::new_from_data(response.txn_data.request_data.qr_data.peek().clone()) - .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + let image_data = QrImage::new_colored_from_data( + response.txn_data.request_data.qr_data.peek().clone(), + constants::DUIT_NOW_BRAND_COLOR, + ) + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let image_data_url = Url::parse(image_data.data.clone().as_str()).ok(); let display_to_timestamp = None; - if let Some(image_data_url) = image_data_url { - let qr_code_info = payments::QrCodeInformation::QrDataUrl { - image_data_url, + if let Some(color_image_data_url) = image_data_url { + let qr_code_info = payments::QrCodeInformation::QrColorDataUrl { + color_image_data_url, display_to_timestamp, + display_text: Some(constants::DUIT_NOW_BRAND_TEXT.to_string()), + border_color: Some(constants::DUIT_NOW_BRAND_COLOR.to_string()), }; Some(qr_code_info.encode_to_value()) diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs index bf2f4c25843..51767bf327c 100644 --- a/crates/hyperswitch_connectors/src/constants.rs +++ b/crates/hyperswitch_connectors/src/constants.rs @@ -43,3 +43,7 @@ pub const CONNECTOR_UNAUTHORIZED_ERROR: &str = "Authentication Error from the co pub const REFUND_VOIDED: &str = "Refund request has been voided."; pub const LOW_BALANCE_ERROR_MESSAGE: &str = "Insufficient balance in the payment method"; + +pub const DUIT_NOW_BRAND_COLOR: &str = "#ED2E67"; + +pub const DUIT_NOW_BRAND_TEXT: &str = "MALAYSIA NATIONAL QR"; diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 05657216d9d..e2b7c688aa5 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -51,7 +51,7 @@ use hyperswitch_domain_models::{ types::OrderDetailsWithAmount, }; use hyperswitch_interfaces::{api, consts, errors, types::Response}; -use image::Luma; +use image::{DynamicImage, ImageBuffer, ImageFormat, Luma, Rgba}; use masking::{ExposeInterface, PeekInterface, Secret}; use once_cell::sync::Lazy; use regex::Regex; @@ -4991,12 +4991,12 @@ impl QrImage { .change_context(common_utils::errors::QrCodeError::FailedToCreateQrCode)?; let qrcode_image_buffer = qr_code.render::<Luma<u8>>().build(); - let qrcode_dynamic_image = image::DynamicImage::ImageLuma8(qrcode_image_buffer); + let qrcode_dynamic_image = DynamicImage::ImageLuma8(qrcode_image_buffer); let mut image_bytes = std::io::BufWriter::new(std::io::Cursor::new(Vec::new())); // Encodes qrcode_dynamic_image and write it to image_bytes - let _ = qrcode_dynamic_image.write_to(&mut image_bytes, image::ImageFormat::Png); + let _ = qrcode_dynamic_image.write_to(&mut image_bytes, ImageFormat::Png); let image_data_source = format!( "{},{}", @@ -5007,6 +5007,58 @@ impl QrImage { data: image_data_source, }) } + + pub fn new_colored_from_data( + data: String, + hex_color: &str, + ) -> Result<Self, error_stack::Report<common_utils::errors::QrCodeError>> { + let qr_code = qrcode::QrCode::new(data.as_bytes()) + .change_context(common_utils::errors::QrCodeError::FailedToCreateQrCode)?; + + let qrcode_image_buffer = qr_code.render::<Luma<u8>>().build(); + let (width, height) = qrcode_image_buffer.dimensions(); + let mut colored_image = ImageBuffer::new(width, height); + let rgb = Self::parse_hex_color(hex_color)?; + + for (x, y, pixel) in qrcode_image_buffer.enumerate_pixels() { + let luminance = pixel.0[0]; + let color = if luminance == 0 { + Rgba([rgb.0, rgb.1, rgb.2, 255]) + } else { + Rgba([255, 255, 255, 255]) + }; + colored_image.put_pixel(x, y, color); + } + + let qrcode_dynamic_image = DynamicImage::ImageRgba8(colored_image); + let mut image_bytes = std::io::Cursor::new(Vec::new()); + qrcode_dynamic_image + .write_to(&mut image_bytes, ImageFormat::Png) + .change_context(common_utils::errors::QrCodeError::FailedToCreateQrCode)?; + + let image_data_source = format!( + "{},{}", + QR_IMAGE_DATA_SOURCE_STRING, + BASE64_ENGINE.encode(image_bytes.get_ref()) + ); + + Ok(Self { + data: image_data_source, + }) + } + + pub fn parse_hex_color(hex: &str) -> Result<(u8, u8, u8), common_utils::errors::QrCodeError> { + let hex = hex.trim_start_matches('#'); + if hex.len() == 6 { + let r = u8::from_str_radix(&hex[0..2], 16).ok(); + let g = u8::from_str_radix(&hex[2..4], 16).ok(); + let b = u8::from_str_radix(&hex[4..6], 16).ok(); + if let (Some(r), Some(g), Some(b)) = (r, g, b) { + return Ok((r, g, b)); + } + } + Err(common_utils::errors::QrCodeError::InvalidHexColor) + } } #[cfg(test)] diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 545c058ce1c..70051bdd504 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -824,6 +824,8 @@ pub enum StripeNextAction { image_data_url: Option<url::Url>, display_to_timestamp: Option<i64>, qr_code_url: Option<url::Url>, + border_color: Option<String>, + display_text: Option<String>, }, FetchQrCodeInformation { qr_code_fetch_url: url::Url, @@ -869,10 +871,14 @@ pub(crate) fn into_stripe_next_action( image_data_url, display_to_timestamp, qr_code_url, + border_color, + display_text, } => StripeNextAction::QrCodeInformation { image_data_url, display_to_timestamp, qr_code_url, + border_color, + display_text, }, payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => { StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url } diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 03cf9742f70..0b3c6cdd596 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -377,6 +377,8 @@ pub enum StripeNextAction { image_data_url: Option<url::Url>, display_to_timestamp: Option<i64>, qr_code_url: Option<url::Url>, + border_color: Option<String>, + display_text: Option<String>, }, FetchQrCodeInformation { qr_code_fetch_url: url::Url, @@ -422,10 +424,14 @@ pub(crate) fn into_stripe_next_action( image_data_url, display_to_timestamp, qr_code_url, + display_text, + border_color, } => StripeNextAction::QrCodeInformation { image_data_url, display_to_timestamp, qr_code_url, + display_text, + border_color, }, payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => { StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index ad56394c5f8..12483aac8e2 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -2960,6 +2960,8 @@ impl ForeignFrom<api_models::payments::QrCodeInformation> for api_models::paymen image_data_url: Some(image_data_url), qr_code_url: Some(qr_code_url), display_to_timestamp, + border_color: None, + display_text: None, }, api_models::payments::QrCodeInformation::QrDataUrl { image_data_url, @@ -2968,6 +2970,8 @@ impl ForeignFrom<api_models::payments::QrCodeInformation> for api_models::paymen image_data_url: Some(image_data_url), display_to_timestamp, qr_code_url: None, + border_color: None, + display_text: None, }, api_models::payments::QrCodeInformation::QrCodeImageUrl { qr_code_url, @@ -2976,6 +2980,20 @@ impl ForeignFrom<api_models::payments::QrCodeInformation> for api_models::paymen qr_code_url: Some(qr_code_url), image_data_url: None, display_to_timestamp, + border_color: None, + display_text: None, + }, + api_models::payments::QrCodeInformation::QrColorDataUrl { + color_image_data_url, + display_to_timestamp, + border_color, + display_text, + } => Self::QrCodeInformation { + qr_code_url: None, + image_data_url: Some(color_image_data_url), + display_to_timestamp, + border_color, + display_text, }, } }
2025-03-04T06:02:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR adds functionality to - Create QR image data URI for a given hex color - Send back the border color and display text message along with the QR data in `NextActionData` - which is consumed by SDK to take next action Described in #7405 ### 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 DuitNow is a realtime payment system which works by scanning QR codes. Displaying these QR codes has certain guidelines mentioned here - https://docs.developer.paynet.my/branding/duitnow/DuitNow%20Brand.pdf This PR sends required data in the confirm API response which is consumed by SDK. ## How did you test it? Tested locally by creating payment links and proceeding with DuitNow payment method. <details> <summary>Create a payment link (ensure DuitNow is enabled)</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_mdkyMYu7o5AvOHSe81Y5MYanl7eTn9rFTRg7DdMvIsJm88Iq5QtXrSihb94pVXmW' \ --data-raw '{"customer_id":"cus_AuvaBi0Ga8Wqx0AyKrYd","profile_id":"pro_7ez6O5T557WOZlcVlidL","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"amount":100,"currency":"MYR","payment_link":true,"capture_method":"automatic","billing":{"address":{"line1":"1467","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"MY","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"}},"email":"[email protected]","session_expiry":100000,"return_url":"https://example.com","payment_link_config":{"theme":"#003264","display_sdk_only":true,"hide_card_nickname_field":true,"payment_button_colour":"#FFA445","custom_message_for_card_terms":"Pour vérifier votre compte, un montant de 0,00 € sera débité lorsque vous aurez cliqué sur le bouton « Confirmer »","payment_button_text":"Confirmer","payment_button_text_colour":"#003264","skip_status_screen":true,"background_colour":"#F9F9F9"}}' Response {"payment_id":"pay_o8k60sUsjHfrG7a4gExy","merchant_id":"merchant_1741062746","status":"requires_payment_method","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":null,"client_secret":"pay_o8k60sUsjHfrG7a4gExy_secret_OVVV51kpUYJUdtXFJz1l","created":"2025-03-04T06:11:28.748Z","currency":"MYR","customer_id":"cus_AuvaBi0Ga8Wqx0AyKrYd","customer":{"id":"cus_AuvaBi0Ga8Wqx0AyKrYd","name":"John Nether","email":"[email protected]","phone":"6168205362","phone_country_code":"+1"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"MY","line1":"1467","line2":null,"line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"order_details":null,"email":"[email protected]","name":"John Nether","phone":"6168205362","return_url":"https://example.com/","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":"cus_AuvaBi0Ga8Wqx0AyKrYd","created_at":1741068688,"expires":1741072288,"secret":"epk_2abaa6e62d0d4b43af67b73aa52160c9"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1741062746/pay_o8k60sUsjHfrG7a4gExy?locale=en","secure_link":null,"payment_link_id":"plink_PLK7sgcmehAkqs93KUAq"},"profile_id":"pro_7ez6O5T557WOZlcVlidL","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":"2025-03-05T09:58:08.746Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-03-04T06:11:28.763Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null} </details> <details> <summary>Select and proceed with DuitNow</summary> <img width="498" alt="Screenshot 2025-03-04 at 11 41 48 AM" src="https://github.com/user-attachments/assets/80b2efcf-db64-49e1-ab9e-ac97ab10be6b" /> </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.112.0
9bcffa6436e6b9207b1711768737a13783a2e907
9bcffa6436e6b9207b1711768737a13783a2e907
juspay/hyperswitch
juspay__hyperswitch-7406
Bug: refactor(core): filter default routing config response based on connector type ## Description <!-- Describe your changes in detail --> We are filtering the response for payment and payout processors.
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 8d03e82a328..64207b4b5d7 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -1,6 +1,6 @@ pub mod helpers; pub mod transformers; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use api_models::routing::DynamicRoutingAlgoAccessor; @@ -11,6 +11,7 @@ use api_models::{ use async_trait::async_trait; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use common_utils::ext_traits::AsyncExt; +use common_utils::id_type::MerchantConnectorAccountId; use diesel_models::routing_algorithm::RoutingAlgorithm; use error_stack::ResultExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] @@ -18,7 +19,9 @@ use external_services::grpc_client::dynamic_routing::{ contract_routing_client::ContractBasedDynamicRouting, success_rate_client::SuccessBasedDynamicRouting, }; -use hyperswitch_domain_models::{mandates, payment_address}; +use hyperswitch_domain_models::{ + mandates, merchant_connector_account::MerchantConnectorAccount, payment_address, +}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use router_env::logger; use rustc_hash::FxHashSet; @@ -976,16 +979,66 @@ pub async fn retrieve_default_routing_config( ) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> { metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(1, &[]); let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + let key_store = state + .store + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_account.get_id(), + &state.store.get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + let id = profile_id .map(|profile_id| profile_id.get_string_repr().to_owned()) .unwrap_or_else(|| merchant_account.get_id().get_string_repr().to_string()); - helpers::get_merchant_default_config(db, &id, transaction_type) + let mut merchant_connector_details: HashMap< + MerchantConnectorAccountId, + MerchantConnectorAccount, + > = HashMap::new(); + state + .store + .find_merchant_connector_account_by_merchant_id_and_disabled_list( + key_manager_state, + merchant_account.get_id(), + false, + &key_store, + ) .await - .map(|conn_choice| { - metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]); - service_api::ApplicationResponse::Json(conn_choice) + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: format!( + "Unable to find merchant_connector_accounts associate with merchant_id: {}", + merchant_account.get_id().get_string_repr() + ), + })? + .iter() + .for_each(|mca| { + merchant_connector_details.insert(mca.get_id(), mca.clone()); + }); + + let connectors = helpers::get_merchant_default_config(db, &id, transaction_type) + .await? + .iter() + .filter(|connector| { + connector + .merchant_connector_id + .as_ref() + .is_some_and(|mca_id| { + merchant_connector_details.get(mca_id).is_some_and(|mca| { + (*transaction_type == common_enums::TransactionType::Payment + && mca.connector_type == common_enums::ConnectorType::PaymentProcessor) + || (*transaction_type == common_enums::TransactionType::Payout + && mca.connector_type + == common_enums::ConnectorType::PayoutProcessor) + }) + }) }) + .cloned() + .collect::<Vec<routing_types::RoutableConnectorChoice>>(); + metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]); + Ok(service_api::ApplicationResponse::Json(connectors)) } #[cfg(feature = "v2")]
2025-02-05T21:11:16Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> We are filtering the response for payment and payout processors. So this works as follows: If Payment's route is hit only PaymentProcessors will be listed and nothing else like PayoutConnectors etc. Payment : ``` curl --location 'http://localhost:8080/routing/default/profile' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' ``` If Payout's route is hit, only Payout's connector will be shown and nothing else. Payout : ``` curl --location 'http://localhost:8080/routing/payout/default/profile' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' ``` ![Screenshot 2025-03-04 at 12 51 02 PM](https://github.com/user-attachments/assets/e465d666-e405-4615-82dc-ce5ae1d2dd81) <img width="1333" alt="Screenshot 2025-03-04 at 1 02 15 PM" src="https://github.com/user-attachments/assets/a587b7c3-ee87-4caf-8b29-dcb281a1e6f4" /> ### 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 after creating JWT locally and adding 1 payment and 1 payout connector. Payment : ``` curl --location 'http://localhost:8080/routing/default/profile' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' ``` Payout : ``` curl --location 'http://localhost:8080/routing/payout/default/profile' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
d6e13dd0c87537e6696dd6dfc02280f825d116ab
d6e13dd0c87537e6696dd6dfc02280f825d116ab
juspay/hyperswitch
juspay__hyperswitch-7403
Bug: [ENHANCEMENT] Payment link enhancements Payment link flows to be updated, below is a list of enhancements - **UI** - Check the existing UI on Windows based browsers, and ensure it's rendered as expected **Flows** - In case `skip_status_screen` is true, re-opening the payment link on a terminal status should redirect to end URL (current behavior is to display the status screen) - In case a payment link was opened in any state other than `requires_payment_method`, handle the state correctly - for `requires_customer_action`, payment link should resume the journey where the user abandoned it
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index cd8b8458364..4ca9f57efb3 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -12587,6 +12587,14 @@ "type": "string", "description": "The url for Qr code given by the connector" }, + "display_text": { + "type": "string", + "nullable": true + }, + "border_color": { + "type": "string", + "nullable": true + }, "type": { "type": "string", "enum": [ @@ -13983,6 +13991,28 @@ "type": "string", "description": "Custom background colour for the payment link", "nullable": true + }, + "sdk_ui_rules": { + "type": "object", + "description": "SDK configuration rules", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "nullable": true + }, + "payment_link_ui_rules": { + "type": "object", + "description": "Payment link configuration rules", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "nullable": true } } }, @@ -14098,6 +14128,28 @@ "type": "string", "description": "Custom background colour for the payment link", "nullable": true + }, + "sdk_ui_rules": { + "type": "object", + "description": "SDK configuration rules", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "nullable": true + }, + "payment_link_ui_rules": { + "type": "object", + "description": "Payment link configuration rules", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "nullable": true } } }, @@ -15301,13 +15353,29 @@ "description": "The return url to which the user should be redirected to", "nullable": true }, - "associated_payment": { + "next_action": { "allOf": [ { - "$ref": "#/components/schemas/PaymentsResponse" + "$ref": "#/components/schemas/NextActionData" } ], "nullable": true + }, + "authentication_details": { + "allOf": [ + { + "$ref": "#/components/schemas/AuthenticationDetails" + } + ], + "nullable": true + }, + "associated_payment_methods": { + "type": "array", + "items": { + "$ref": "#/components/schemas/id_type.GlobalPaymentMethodId" + }, + "description": "The payment method that was created using this payment method session", + "nullable": true } } }, @@ -15542,60 +15610,6 @@ }, "additionalProperties": false }, - "PaymentMethodsSessionResponse": { - "type": "object", - "required": [ - "id", - "customer_id", - "expires_at", - "client_secret" - ], - "properties": { - "id": { - "type": "string", - "example": "12345_pms_01926c58bc6e77c09e809964e72af8c8" - }, - "customer_id": { - "type": "string", - "description": "The customer id for which the payment methods session is to be created", - "example": "12345_cus_01926c58bc6e77c09e809964e72af8c8" - }, - "billing": { - "allOf": [ - { - "$ref": "#/components/schemas/Address" - } - ], - "nullable": true - }, - "psp_tokenization": { - "allOf": [ - { - "$ref": "#/components/schemas/PspTokenization" - } - ], - "nullable": true - }, - "network_tokenization": { - "allOf": [ - { - "$ref": "#/components/schemas/NetworkTokenization" - } - ], - "nullable": true - }, - "expires_at": { - "type": "string", - "format": "date-time", - "description": "The iso timestamp when the session will expire\nTrying to retrieve the session or any operations on the session after this time will result in an error", - "example": "2023-01-18T11:04:09.922Z" - }, - "client_secret": { - "type": "string", - "description": "Client Secret" - } - } - }, "PaymentMethodsSessionUpdateRequest": { "type": "object", "properties": { diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 59791cc7504..d21bc362669 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -16543,6 +16543,28 @@ "type": "string", "description": "Custom background colour for the payment link", "nullable": true + }, + "sdk_ui_rules": { + "type": "object", + "description": "SDK configuration rules", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "nullable": true + }, + "payment_link_ui_rules": { + "type": "object", + "description": "Payment link configuration rules", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "nullable": true } } }, @@ -16658,6 +16680,28 @@ "type": "string", "description": "Custom background colour for the payment link", "nullable": true + }, + "sdk_ui_rules": { + "type": "object", + "description": "SDK configuration rules", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "nullable": true + }, + "payment_link_ui_rules": { + "type": "object", + "description": "Payment link configuration rules", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "nullable": true } } }, diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 5d31ea70994..d5a4d89910b 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -2810,6 +2810,10 @@ pub struct PaymentLinkConfigRequest { pub payment_button_text_colour: Option<String>, /// Custom background colour for the payment link pub background_colour: Option<String>, + /// SDK configuration rules + pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + /// Payment link configuration rules + pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] @@ -2891,6 +2895,10 @@ pub struct PaymentLinkConfig { pub payment_button_text_colour: Option<String>, /// Custom background colour for the payment link pub background_colour: Option<String>, + /// SDK configuration rules + pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + /// Payment link configuration rules + pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 12da310ac61..813408da0ea 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -7831,6 +7831,8 @@ pub struct PaymentLinkDetails { pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, + pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, } #[derive(Debug, serde::Serialize, Clone)] @@ -7846,6 +7848,8 @@ pub struct SecurePaymentLinkDetails { pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, + pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, } #[derive(Debug, serde::Serialize)] diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 744193bf51e..44f32c6eb4b 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -644,6 +644,8 @@ pub struct PaymentLinkConfigRequest { pub skip_status_screen: Option<bool>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, + pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index a2b3c406a2a..8845a92ba6a 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -187,6 +187,12 @@ pub struct PaymentLinkConfigRequestForPayments { pub payment_button_text_colour: Option<String>, /// Custom background colour for the payment link pub background_colour: Option<String>, + /// SDK configuration rules + pub sdk_ui_rules: + Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>, + /// Payment link configuration rules + pub payment_link_ui_rules: + Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkConfigRequestForPayments); diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index c97753a6dc0..2d2a4413afc 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -412,6 +412,8 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> skip_status_screen: item.skip_status_screen, background_colour: item.background_colour, payment_button_text_colour: item.payment_button_text_colour, + sdk_ui_rules: item.sdk_ui_rules, + payment_link_ui_rules: item.payment_link_ui_rules, } } fn convert_back(self) -> api_models::admin::PaymentLinkConfigRequest { @@ -433,6 +435,8 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> skip_status_screen, background_colour, payment_button_text_colour, + sdk_ui_rules, + payment_link_ui_rules, } = self; api_models::admin::PaymentLinkConfigRequest { theme, @@ -458,6 +462,8 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> skip_status_screen, background_colour, payment_button_text_colour, + sdk_ui_rules, + payment_link_ui_rules, } } } diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index e62d9946416..292f582df9a 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -135,6 +135,8 @@ pub async fn form_payment_link_data( skip_status_screen: None, background_colour: None, payment_button_text_colour: None, + sdk_ui_rules: None, + payment_link_ui_rules: None, } }; @@ -286,6 +288,8 @@ pub async fn form_payment_link_data( skip_status_screen: payment_link_config.skip_status_screen, background_colour: payment_link_config.background_colour.clone(), payment_button_text_colour: payment_link_config.payment_button_text_colour.clone(), + sdk_ui_rules: payment_link_config.sdk_ui_rules.clone(), + payment_link_ui_rules: payment_link_config.payment_link_ui_rules.clone(), }; Ok(( @@ -342,6 +346,8 @@ pub async fn initiate_secure_payment_link_flow( skip_status_screen: payment_link_config.skip_status_screen, background_colour: payment_link_config.background_colour, payment_button_text_colour: payment_link_config.payment_button_text_colour, + sdk_ui_rules: payment_link_config.sdk_ui_rules, + payment_link_ui_rules: payment_link_config.payment_link_ui_rules, }; let js_script = format!( "window.__PAYMENT_DETAILS = {}", @@ -653,6 +659,8 @@ pub fn get_payment_link_config_based_on_priority( skip_status_screen, background_colour, payment_button_text_colour, + sdk_ui_rules, + payment_link_ui_rules, ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, @@ -664,7 +672,9 @@ pub fn get_payment_link_config_based_on_priority( (payment_button_colour), (skip_status_screen), (background_colour), - (payment_button_text_colour) + (payment_button_text_colour), + (sdk_ui_rules), + (payment_link_ui_rules), ); let payment_link_config = @@ -690,6 +700,8 @@ pub fn get_payment_link_config_based_on_priority( payment_button_colour, background_colour, payment_button_text_colour, + sdk_ui_rules, + payment_link_ui_rules, }; Ok((payment_link_config, domain_name)) @@ -798,6 +810,8 @@ pub async fn get_payment_link_status( skip_status_screen: None, background_colour: None, payment_button_text_colour: None, + sdk_ui_rules: None, + payment_link_ui_rules: None, } }; diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js index 811ae799d0f..5b8267c57a9 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js @@ -231,8 +231,8 @@ function boot() { link.type = "image/x-icon"; document.head.appendChild(link); } - // Render UI + // Render UI if (paymentDetails.display_sdk_only) { renderSDKHeader(paymentDetails); renderBranding(paymentDetails); @@ -247,7 +247,6 @@ function boot() { renderSDKHeader(paymentDetails); } - // Deal w loaders show("#sdk-spinner"); hide("#page-spinner"); @@ -256,6 +255,12 @@ function boot() { // Add event listeners initializeEventListeners(paymentDetails); + // Update payment link styles + var paymentLinkUiRules = paymentDetails.payment_link_ui_rules; + if (paymentLinkUiRules !== null && typeof paymentLinkUiRules === "object" && Object.getPrototypeOf(paymentLinkUiRules) === Object.prototype) { + updatePaymentLinkUi(paymentLinkUiRules); + } + // Initialize SDK // @ts-ignore if (window.Hyper) { @@ -461,7 +466,7 @@ function handleSubmit(e) { window.top.location.href = url.toString(); } else { redirectToStatus(); - } + } }) .catch(function (error) { console.error("Error confirming payment_intent", error); @@ -801,7 +806,7 @@ function renderBranding(paymentDetails) { * - Renders background image in the payment details section * @param {PaymentDetails} paymentDetails */ -function renderBackgroundImage(paymentDetails) { +function renderBackgroundImage(paymentDetails) { var backgroundImage = paymentDetails.background_image; if (typeof backgroundImage === "object" && backgroundImage !== null) { var paymentDetailsNode = document.getElementById("hyper-checkout-details"); @@ -1104,3 +1109,24 @@ function renderSDKHeader(paymentDetails) { sdkHeaderNode.append(sdkHeaderItemNode); } } + +/** + * Trigger - post UI render + * Use - add CSS rules for the payment link + * @param {Object} paymentLinkUiRules + */ +function updatePaymentLinkUi(paymentLinkUiRules) { + Object.keys(paymentLinkUiRules).forEach(function (selector) { + try { + var node = document.querySelector(selector); + if (node instanceof HTMLElement) { + var styles = paymentLinkUiRules[selector]; + Object.keys(styles).forEach(function (property) { + node.style[property] = styles[property]; + }); + } + } catch (error) { + console.error("Failed to apply styles to selector", selector, error); + } + }) +} \ No newline at end of file diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js index 6abe5f7d5b2..ca6a944baaa 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js @@ -10,7 +10,8 @@ function initializeSDK() { // @ts-ignore var paymentDetails = window.__PAYMENT_DETAILS; - var client_secret = paymentDetails.client_secret; + var clientSecret = paymentDetails.client_secret; + var sdkUiRules = paymentDetails.sdk_ui_rules; var appearance = { variables: { colorPrimary: paymentDetails.theme || "rgb(0, 109, 249)", @@ -24,6 +25,9 @@ function initializeSDK() { colorBackground: "rgb(255, 255, 255)", }, }; + if (sdkUiRules !== null && typeof sdkUiRules === "object" && Object.getPrototypeOf(sdkUiRules) === Object.prototype) { + appearance.rules = sdkUiRules; + } // @ts-ignore hyper = window.Hyper(pub_key, { isPreloadEnabled: false, @@ -37,12 +41,12 @@ function initializeSDK() { // @ts-ignore widgets = hyper.widgets({ appearance: appearance, - clientSecret: client_secret, + clientSecret: clientSecret, locale: paymentDetails.locale, }); var type = paymentDetails.sdk_layout === "spaced_accordion" || - paymentDetails.sdk_layout === "accordion" + paymentDetails.sdk_layout === "accordion" ? "accordion" : paymentDetails.sdk_layout; var hideCardNicknameField = paymentDetails.hide_card_nickname_field; diff --git a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js index a8a00e4de9d..9b5a144d29a 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js @@ -31,7 +31,8 @@ if (!isFramed) { function initializeSDK() { // @ts-ignore var paymentDetails = window.__PAYMENT_DETAILS; - var client_secret = paymentDetails.client_secret; + var clientSecret = paymentDetails.client_secret; + var sdkUiRules = paymentDetails.sdk_ui_rules; var appearance = { variables: { colorPrimary: paymentDetails.theme || "rgb(0, 109, 249)", @@ -45,6 +46,9 @@ if (!isFramed) { colorBackground: "rgb(255, 255, 255)", }, }; + if (sdkUiRules !== null && typeof sdkUiRules === "object" && Object.getPrototypeOf(sdkUiRules) === Object.prototype) { + appearance.rules = sdkUiRules; + } // @ts-ignore hyper = window.Hyper(pub_key, { isPreloadEnabled: false, @@ -58,12 +62,12 @@ if (!isFramed) { // @ts-ignore widgets = hyper.widgets({ appearance: appearance, - clientSecret: client_secret, + clientSecret: clientSecret, locale: paymentDetails.locale, }); var type = paymentDetails.sdk_layout === "spaced_accordion" || - paymentDetails.sdk_layout === "accordion" + paymentDetails.sdk_layout === "accordion" ? "accordion" : paymentDetails.sdk_layout; diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 12483aac8e2..eb0f246fdcb 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -4431,6 +4431,8 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> skip_status_screen: config.skip_status_screen, background_colour: config.background_colour, payment_button_text_colour: config.payment_button_text_colour, + sdk_ui_rules: config.sdk_ui_rules, + payment_link_ui_rules: config.payment_link_ui_rules, } } } @@ -4499,6 +4501,8 @@ impl ForeignFrom<diesel_models::PaymentLinkConfigRequestForPayments> skip_status_screen: config.skip_status_screen, background_colour: config.background_colour, payment_button_text_colour: config.payment_button_text_colour, + sdk_ui_rules: config.sdk_ui_rules, + payment_link_ui_rules: config.payment_link_ui_rules, } } } diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 9557aabbe81..a112be46188 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -456,7 +456,7 @@ pub async fn connector_retrieve( let id = path.into_inner(); let payload = web::Json(admin::MerchantConnectorId { id: id.clone() }).into_inner(); - api::server_wrap( + Box::pin(api::server_wrap( flow, state, &req, @@ -477,7 +477,7 @@ pub async fn connector_retrieve( req.headers(), ), api_locking::LockAction::NotApplicable, - ) + )) .await } @@ -491,7 +491,7 @@ pub async fn connector_list( let flow = Flow::MerchantConnectorsList; let profile_id = path.into_inner(); - api::server_wrap( + Box::pin(api::server_wrap( flow, state, &req, @@ -507,7 +507,7 @@ pub async fn connector_list( req.headers(), ), api_locking::LockAction::NotApplicable, - ) + )) .await } diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rs index 92b5d667daa..64b46eb2f55 100644 --- a/crates/router/src/routes/ephemeral_key.rs +++ b/crates/router/src/routes/ephemeral_key.rs @@ -64,7 +64,7 @@ pub async fn client_secret_create( ) -> HttpResponse { let flow = Flow::EphemeralKeyCreate; let payload = json_payload.into_inner(); - api::server_wrap( + Box::pin(api::server_wrap( flow, state, &req, @@ -80,7 +80,7 @@ pub async fn client_secret_create( }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, - ) + )) .await } @@ -93,7 +93,7 @@ pub async fn client_secret_delete( ) -> HttpResponse { let flow = Flow::EphemeralKeyDelete; let payload = path.into_inner(); - api::server_wrap( + Box::pin(api::server_wrap( flow, state, &req, @@ -101,6 +101,6 @@ pub async fn client_secret_delete( |state, _: auth::AuthenticationData, req, _| helpers::delete_client_secret(state, req), &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, - ) + )) .await } diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rs index d89f3c65cbe..31e7638b3ef 100644 --- a/crates/router/src/routes/verification.rs +++ b/crates/router/src/routes/verification.rs @@ -53,7 +53,7 @@ pub async fn retrieve_apple_pay_verified_domains( let merchant_id = &params.merchant_id; let mca_id = &params.merchant_connector_account_id; - api::server_wrap( + Box::pin(api::server_wrap( flow, state, &req, @@ -73,6 +73,6 @@ pub async fn retrieve_apple_pay_verified_domains( req.headers(), ), api_locking::LockAction::NotApplicable, - ) + )) .await } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 514ddbbbb50..2b563f5644b 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -2164,6 +2164,8 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> payment_button_colour: item.payment_button_colour, background_colour: item.background_colour, payment_button_text_colour: item.payment_button_text_colour, + sdk_ui_rules: item.sdk_ui_rules, + payment_link_ui_rules: item.payment_link_ui_rules, } } } @@ -2192,6 +2194,8 @@ impl ForeignFrom<diesel_models::business_profile::PaymentLinkConfigRequest> payment_button_colour: item.payment_button_colour, background_colour: item.background_colour, payment_button_text_colour: item.payment_button_text_colour, + sdk_ui_rules: item.sdk_ui_rules, + payment_link_ui_rules: item.payment_link_ui_rules, } } }
2025-03-04T13:52:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR exposes customizations for payment links. Below configs are added - - SDK UI rules - https://docs.hyperswitch.io/explore-hyperswitch/merchant-controls/integration-guide/web/customization#id-4.-rules - Payment Link UI rules - similar to SDK UI rules, but for payment link template* ### 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 Gives granular control to the payment link consumer for designing their UI. ## How did you test it? Tested locally. <details> <summary>1. Add a payment link style ID</summary> cURL curl --location --request POST 'http://localhost:8080/account/merchant_1741095653/business_profile/pro_dgzCAaE0KhqCTj6cY5a7' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{"payment_link_config":{"allowed_domains":["*"],"business_specific_configs":{"style1":{"enabled_saved_payment_method":true,"theme":"#E71D36","logo":"https://hyperswitch.io/favicon.ico","sdk_ui_rules":{".Label":{"fontWeight":"700 !important","fontSize":"13px !important","color":"#003264 !important","opacity":"1 !important"}},"payment_link_ui_rules":{"#submit":{"color":"#003264","fontWeight":"700","fontSize":"18px","padding":"25px 0","borderRadius":"20px","backgroundColor":"#ffc439"},"#hyper-checkout-sdk":{"backgroundColor":"#003264"}}}}}}' Response {"merchant_id":"merchant_1741095653","profile_id":"pro_dgzCAaE0KhqCTj6cY5a7","profile_name":"IN_default","return_url":"https://google.com/success","enable_payment_response_hash":true,"payment_response_hash_key":"fVkaUtGhpJbDbwJ6bkDO1MX6yRgCNlJPSyaaMkOfe8izhPgWUGS8mdP8p95t5gqp","redirect_to_merchant_with_http_post":false,"webhook_details":{"webhook_version":"1.0.1","webhook_username":"random","webhook_password":"pass","webhook_url":"https://webhook.site/c5368f5d-882b-4d3a-b5be-f372294b6146","payment_created_enabled":true,"payment_succeeded_enabled":true,"payment_failed_enabled":true},"metadata":null,"routing_algorithm":null,"intent_fulfillment_time":900,"frm_routing_algorithm":null,"payout_routing_algorithm":null,"applepay_verified_domains":null,"session_expiry":900,"payment_link_config":{"domain_name":null,"theme":"#1A1A1A","logo":"https://hyperswitch.io/favicon.ico","seller_name":null,"sdk_layout":null,"display_sdk_only":null,"enabled_saved_payment_method":true,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":"Proceed to Payment!","custom_message_for_card_terms":"Hello","payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":{".Label":{"fontWeight":"700 !important","fontSize":"13px !important","opacity":"1 !important","backgroundColor":"red !important","color":"#003264 !important"}},"payment_link_ui_rules":null,"business_specific_configs":{"style2":{"theme":"#1A1A1A","logo":"https://hyperswitch.io/favicon.ico","seller_name":null,"sdk_layout":null,"display_sdk_only":null,"enabled_saved_payment_method":true,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":null,"custom_message_for_card_terms":null,"payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":null,"payment_link_ui_rules":null},"style1":{"theme":"#E71D36","logo":"https://hyperswitch.io/favicon.ico","seller_name":null,"sdk_layout":null,"display_sdk_only":null,"enabled_saved_payment_method":true,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":null,"custom_message_for_card_terms":null,"payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":{".Label":{"color":"#003264 !important","opacity":"1 !important","fontWeight":"700 !important","fontSize":"13px !important"}},"payment_link_ui_rules":{"#submit":{"color":"#003264","fontSize":"18px","backgroundColor":"#ffc439","borderRadius":"20px","padding":"25px 0","fontWeight":"700"},"#hyper-checkout-sdk":{"backgroundColor":"#003264"}}}},"allowed_domains":["*"],"branding_visibility":null},"authentication_connector_details":null,"use_billing_as_payment_method_billing":true,"extended_card_info_config":null,"collect_shipping_details_from_wallet_connector":false,"collect_billing_details_from_wallet_connector":false,"always_collect_shipping_details_from_wallet_connector":false,"always_collect_billing_details_from_wallet_connector":false,"is_connector_agnostic_mit_enabled":true,"payout_link_config":null,"outgoing_webhook_custom_http_headers":null,"tax_connector_id":null,"is_tax_connector_enabled":false,"is_network_tokenization_enabled":true,"is_auto_retries_enabled":false,"max_auto_retries_enabled":null,"always_request_extended_authorization":null,"is_click_to_pay_enabled":true,"authentication_product_ids":null,"card_testing_guard_config":{"card_ip_blocking_status":"disabled","card_ip_blocking_threshold":3,"guest_user_card_blocking_status":"disabled","guest_user_card_blocking_threshold":10,"customer_id_blocking_status":"disabled","customer_id_blocking_threshold":5,"card_testing_guard_expiry":3600},"is_clear_pan_retries_enabled":false} </details> <details> <summary>2. Create a payment link</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_R70SBQ7gQzMiqsCrbSGMBTEtsKbNkgc8sXo5yHgpEA0mvT8BktGLXrn9zPOxLwpf' \ --data '{"customer_id":"cus_jJuzSZ5cVZ5mgBGGUNYs","profile_id":"pro_dgzCAaE0KhqCTj6cY5a7","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"amount":100,"currency":"EUR","payment_link":true,"setup_future_usage":"off_session","capture_method":"automatic","session_expiry":100000,"return_url":"https://example.com","payment_link_config_id":"style1"}' Response {"payment_id":"pay_1QLObAU2blLbNSfehTJN","merchant_id":"merchant_1741095653","status":"requires_payment_method","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":null,"client_secret":"pay_1QLObAU2blLbNSfehTJN_secret_oRqjfv36rG6plNEBHvvQ","created":"2025-03-04T22:10:37.490Z","currency":"EUR","customer_id":"cus_jJuzSZ5cVZ5mgBGGUNYs","customer":{"id":"cus_jJuzSZ5cVZ5mgBGGUNYs","name":"John Nether","email":null,"phone":"6168205362","phone_country_code":"+1"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":null,"name":"John Nether","phone":"6168205362","return_url":"https://example.com/","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":"cus_jJuzSZ5cVZ5mgBGGUNYs","created_at":1741126237,"expires":1741129837,"secret":"epk_5255cf68bc6947db9fcf59f285eeb37b"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1741095653/pay_1QLObAU2blLbNSfehTJN?locale=en","secure_link":"http://localhost:8080/payment_link/s/merchant_1741095653/pay_1QLObAU2blLbNSfehTJN?locale=en","payment_link_id":"plink_Uve1VxVAdO7XJAkBQzMg"},"profile_id":"pro_dgzCAaE0KhqCTj6cY5a7","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":"2025-03-06T01:57:17.488Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-03-04T22:10:37.496Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null} <img width="646" alt="Screenshot 2025-03-05 at 3 41 38 AM" src="https://github.com/user-attachments/assets/5ceef6f4-e935-463d-904c-6855de2bd4a3" /> </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible ### Note **\* - EDIT 1**
v1.113.0
759474cd4866aa7a6fba055594b9a96de26681a4
759474cd4866aa7a6fba055594b9a96de26681a4
juspay/hyperswitch
juspay__hyperswitch-7391
Bug: docs:correction of content in the api-ref
diff --git a/api-reference/api-reference/payments/Introduction--to--payments.mdx b/api-reference/api-reference/payments/Introduction--to--payments.mdx index 4cccc9cde2c..2893aec261b 100644 --- a/api-reference/api-reference/payments/Introduction--to--payments.mdx +++ b/api-reference/api-reference/payments/Introduction--to--payments.mdx @@ -15,7 +15,7 @@ You have two options to use the Payments API: 2. **Self-Deploy** – Create merchants and API keys through Rest API. Each option has specific nuances, we have mentioned the differences in the below step by step guide -<Tip>We recommend using our [Dashboard](https://app.hyperswitch.io/dashboard/login) to generate API Key and setting up Connectors (Step 4)</Tip> for faster trial and simple setup +<Tip>We recommend using our [Dashboard](https://app.hyperswitch.io/dashboard/login) to generate API Key and setting up Connectors (Step 4) for faster trial and simple setup.</Tip> <Steps> <Step title="Create a Merchant Account"> This account is representative of you or your organization that would like to accept payments from different <Tooltip tip="Can be a payment method or payment service provider">payment connectors</Tooltip>
2025-02-27T07:12:48Z
Corrected the tip content. ## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [X] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Corrected the content of the tip. ### 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 #7391 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.112.0
d945da635dfc84a2135aef456292fa54d9d5982e
d945da635dfc84a2135aef456292fa54d9d5982e
juspay/hyperswitch
juspay__hyperswitch-7392
Bug: [BUG] GooglePay for Ayden Fixed GooglePay for Ayden Fixed
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 8aba3573f68..93a43f25b8a 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -568,6 +568,7 @@ pub enum AdyenPaymentMethod<'a> { Eps(Box<BankRedirectionWithIssuer<'a>>), #[serde(rename = "gcash")] Gcash(Box<GcashData>), + #[serde(rename = "googlepay")] Gpay(Box<AdyenGPay>), #[serde(rename = "gopay_wallet")] GoPay(Box<GoPayData>),
2025-02-27T12:28:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> GooglePay fixed in Ayden ### 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="1063" alt="Screenshot 2025-02-27 at 6 39 19 PM" src="https://github.com/user-attachments/assets/eead90cb-da62-4e5d-9ade-f8f0f2f2de19" /> ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Coa5dQU6Vo2ezZrfgvAlgmDed2NjJmuW1hTcmI5uMevC27Tkp4F16r5Om4HEb9UU' \ --data-raw '{ "amount": 6540, "currency": "USD", "amount_to_capture": 6540, "confirm": true, "profile_id": null, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "setup_future_usage": "on_session", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "phone_country_code": "+1", "routing": { "type": "single", "data": "stripe" }, "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_data": { "wallet": { "google_pay": { "type": "CARD", "description": "Amex •••• 0002", "info": { "assurance_details": { "account_verified": true, "card_holder_authenticated": false }, "card_details": "0002", "card_network": "AMEX" }, "tokenization_data": { "token": "{\"signature\":\"MEYCIQC7ferzG3SQgMMoJ18frh9oLAdQigN4jTAeAlx26IoCawIhAIL/6we459IuANws+AeNbeU5+eBnscy7FBjaANj9lJmd\",\"protocolVersion\":\"ECv1\",\"signedMessage\":\"{\\\"encryptedMessage\\\":\\\"VFe6XC/1MKP2O9ETH6Uv/NUe0MtyHjAe0uqDsZ3b1jtUw/crQ+LIAEhgFt0+B2r6pqJdg56yYzZ4nuuEiIVMvgDtMr6Lz8bHRDv620RSFT+lfZOHFAX0JtKAzUSbfzR50tnMFAlBEPBfOKCGVKboA0g2dfQhfhyYFX5pqgEM8rg0/YHl5FPpfSH1ZaZQxM/PXwF/ju84zB9doOVyYyT6/jUtnoW6FmGChVZPSuV3o++y9Q+lOEGTjOEQTsLrWtqiRit3atkiLguzo57xrK6TE9hK6+3XXv8o/7gbBQPaxlXYWSbjRK4mHkOmkC0LTSiPVvJkKlY0SHMjKz85jwcttWs3LgPSHkKkFv+VM4vQiXIjAbmX1KMfgbLcEVNfAWL+/j/IwSif66DVakkO277KcsVhpQC2y/p/1VMTDtg45guT2kMVJsqQORumwJPvYumVgpwIFmlg5uDKo7j0ioyeagp67lBdhZbsyvyJsyzFbSCyGoXaFCJbYqNQIVl8ioFuCIe50ePc79Mkxony\\\",\\\"ephemeralPublicKey\\\":\\\"BBWzyB4tX5yqOEDaryLLlX9h91M2298ChS0lYgHLbXwN/eEh0V8w2PX/psg12dY2do2ksP2NA3be/e+9NhvTlU0\\\\u003d\\\",\\\"tag\\\":\\\"123ZOhok0+5uiBUYaO3i5U/h73+YsXPbwK8IhinHVl8\\\\u003d\\\"}\"}", "type": "PAYMENT_GATEWAY" } } } }, "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": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 6540, "account_name": "transaction_processing" } ], "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, "payment_link": false, "payment_link_config": { "theme": "", "logo": "", "seller_name": "", "sdk_layout": "", "display_sdk_only": false, "enabled_saved_payment_method": false }, "payment_type": "normal", "request_incremental_authorization": false, "merchant_order_reference_id": "test_ord", "session_expiry": 900 }' ``` Response ``` { "payment_id": "pay_BHtu7Av3hbxF6YGyNg6y", "merchant_id": "merchant_1740661643", "status": "succeeded", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6540, "connector": "adyen", "client_secret": "pay_BHtu7Av3hbxF6YGyNg6y_secret_Ta6ChMs3WiuxCppvsKm8", "created": "2025-02-27T13:07:38.606Z", "currency": "USD", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "google_pay": { "last4": "0002", "card_network": "AMEX", "type": "CARD" } }, "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": "[email protected]" }, "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": "[email protected]" }, "order_details": [ { "brand": null, "amount": 6540, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "[email protected]", "name": "John Doe", "phone": "9999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "google_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer123", "created_at": 1740661658, "expires": 1740665258, "secret": "epk_fa7ee7a7801840348e3e6f6e6f20adf3" }, "manual_retry_allowed": false, "connector_transaction_id": "LMSBT86ZTGGNFL75", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "pay_BHtu7Av3hbxF6YGyNg6y_1", "payment_link": null, "profile_id": "pro_5CrLzkPfIhQSZT0e92na", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_kc9GbBR2tswsauYa0J2O", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-02-27T13:22:38.605Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "128.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-02-27T13:07:40.697Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": "test_ord", "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.112.0
5965d0f8acf486909951e427b578aae8d630de13
5965d0f8acf486909951e427b578aae8d630de13
juspay/hyperswitch
juspay__hyperswitch-7375
Bug: chore: address Rust 1.85.0 clippy lints Address the clippy lints occurring due to new rust version 1.85.0 See https://github.com/juspay/hyperswitch/issues/3391 for more information.
diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs index 1497c9e3622..02c25d722c1 100644 --- a/crates/hyperswitch_domain_models/src/customer.rs +++ b/crates/hyperswitch_domain_models/src/customer.rs @@ -232,8 +232,8 @@ impl super::behaviour::Conversion for Customer { connector_customer: self.connector_customer, default_payment_method_id: self.default_payment_method_id, updated_by: self.updated_by, - default_billing_address: self.default_billing_address.map(Encryption::from), - default_shipping_address: self.default_shipping_address.map(Encryption::from), + default_billing_address: self.default_billing_address, + default_shipping_address: self.default_shipping_address, version: self.version, status: self.status, }) diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs index 6fa9f9450c8..fd8e144f4f2 100644 --- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs +++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs @@ -344,7 +344,7 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon connector, reason, status_code, - } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.to_owned().map(Into::into), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)), + } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.to_owned(), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)), Self::PaymentAuthorizationFailed { data } => { AER::BadRequest(ApiError::new("CE", 1, "Payment failed during authorization with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()}))) } diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 545c058ce1c..c24fd506ace 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -283,11 +283,7 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentIntentRequest) -> errors::RouterResult<Self> { let routable_connector: Option<api_enums::RoutableConnectors> = - item.connector.and_then(|v| { - v.into_iter() - .next() - .map(api_enums::RoutableConnectors::from) - }); + item.connector.and_then(|v| v.into_iter().next()); let routing = routable_connector .map(|connector| { diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 03cf9742f70..896b06ed721 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -179,11 +179,7 @@ impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripeSetupIntentRequest) -> errors::RouterResult<Self> { let routable_connector: Option<api_enums::RoutableConnectors> = - item.connector.and_then(|v| { - v.into_iter() - .next() - .map(api_enums::RoutableConnectors::from) - }); + item.connector.and_then(|v| v.into_iter().next()); let routing = routable_connector .map(|connector| { diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index bc93b9c53eb..94ace1e2b25 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -3731,8 +3731,7 @@ impl ProfileCreateBridge for api::ProfileCreate { collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector .or(Some(false)), - outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers - .map(Into::into), + outgoing_webhook_custom_http_headers, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: self.is_tax_connector_enabled, always_collect_billing_details_from_wallet_connector: self @@ -3879,8 +3878,7 @@ impl ProfileCreateBridge for api::ProfileCreate { collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector_if_required .or(Some(false)), - outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers - .map(Into::into), + outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self @@ -4185,8 +4183,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, - outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers - .map(Into::into), + outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self @@ -4318,8 +4315,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector_if_required, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, - outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers - .map(Into::into), + outgoing_webhook_custom_http_headers, order_fulfillment_time: self .order_fulfillment_time .map(|order_fulfillment_time| order_fulfillment_time.into_inner()), diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 353c980c769..6699cf70db0 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -197,10 +197,8 @@ impl CustomerCreateBridge for customers::CustomerRequest { customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { let address = self.get_address(); - let address_details = address.map(api_models::payments::AddressDetails::from); - Ok(services::ApplicationResponse::Json( - customers::CustomerResponse::foreign_from((customer.clone(), address_details)), + customers::CustomerResponse::foreign_from((customer.clone(), address)), )) } } @@ -1265,10 +1263,8 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest { customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { let address = self.get_address(); - let address_details = address.map(api_models::payments::AddressDetails::from); - Ok(services::ApplicationResponse::Json( - customers::CustomerResponse::foreign_from((customer.clone(), address_details)), + customers::CustomerResponse::foreign_from((customer.clone(), address)), )) } } diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index ffb864ea072..f2e199d8584 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -905,7 +905,7 @@ pub async fn create_payment_method( merchant_id, key_store, merchant_account.storage_scheme, - payment_method_billing_address.map(Into::into), + payment_method_billing_address, ) .await .attach_printable("Failed to add Payment method to DB")?; @@ -1191,7 +1191,7 @@ pub async fn payment_method_intent_create( merchant_id, key_store, merchant_account.storage_scheme, - payment_method_billing_address.map(Into::into), + payment_method_billing_address, ) .await .attach_printable("Failed to add Payment method to DB")?; diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 1f37cc157e4..548007825e3 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -804,7 +804,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( payment_method_issuer: req.payment_method_issuer.clone(), scheme: req.card_network.clone().or(card.scheme.clone()), metadata: payment_method_metadata.map(Secret::new), - payment_method_data: payment_method_data_encrypted.map(Into::into), + payment_method_data: payment_method_data_encrypted, connector_mandate_details: connector_mandate_details.clone(), customer_acceptance: None, client_secret: None, @@ -823,7 +823,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( created_at: current_time, last_modified: current_time, last_used_at: current_time, - payment_method_billing_address: payment_method_billing_address.map(Into::into), + payment_method_billing_address, updated_by: None, version: domain::consts::API_VERSION, network_token_requestor_reference_id: None, @@ -1074,7 +1074,7 @@ pub async fn get_client_secret_or_add_payment_method( Some(enums::PaymentMethodStatus::AwaitingData), None, merchant_account.storage_scheme, - payment_method_billing_address.map(Into::into), + payment_method_billing_address, None, None, None, @@ -1167,7 +1167,7 @@ pub async fn get_client_secret_or_add_payment_method_for_migration( Some(enums::PaymentMethodStatus::AwaitingData), None, merchant_account.storage_scheme, - payment_method_billing_address.map(Into::into), + payment_method_billing_address, None, None, None, @@ -1687,7 +1687,7 @@ pub async fn add_payment_method( connector_mandate_details, req.network_transaction_id.clone(), merchant_account.storage_scheme, - payment_method_billing_address.map(Into::into), + payment_method_billing_address, None, None, None, @@ -1949,7 +1949,7 @@ pub async fn save_migration_payment_method( connector_mandate_details.clone(), network_transaction_id.clone(), merchant_account.storage_scheme, - payment_method_billing_address.map(Into::into), + payment_method_billing_address, None, None, None, 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 fab2a9144c7..f61255de84c 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -283,7 +283,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata); // The operation merges mandate data from both request and payment_attempt - let setup_mandate = mandate_data.map(Into::into); + let setup_mandate = mandate_data; let mandate_details_present = payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 06036c4bc59..5715f498477 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -19,7 +19,7 @@ use diesel_models::{ }; use error_stack::{self, ResultExt}; use hyperswitch_domain_models::{ - mandates::{MandateData, MandateDetails}, + mandates::MandateDetails, payments::{ payment_attempt::PaymentAttempt, payment_intent::CustomerData, FromRequestEncryptablePaymentIntent, @@ -493,7 +493,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> .transpose()?; // The operation merges mandate data from both request and payment_attempt - let setup_mandate = mandate_data.map(MandateData::from); + let setup_mandate = mandate_data; let surcharge_details = request.surcharge_details.map(|request_surcharge_details| { payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt)) diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 89a94552bc2..096b7ed0b39 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -421,7 +421,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> .transpose()?; // The operation merges mandate data from both request and payment_attempt - let setup_mandate = mandate_data.map(Into::into); + let setup_mandate = mandate_data; let mandate_details_present = payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); helpers::validate_mandate_data_and_future_usage( diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index b4e4db3d161..deb6dbac03d 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -393,21 +393,20 @@ where merchant_id, pm_metadata, customer_acceptance, - pm_data_encrypted.map(Into::into), + pm_data_encrypted, key_store, None, pm_status, network_transaction_id, merchant_account.storage_scheme, - encrypted_payment_method_billing_address - .map(Into::into), + encrypted_payment_method_billing_address, resp.card.and_then(|card| { card.card_network .map(|card_network| card_network.to_string()) }), network_token_requestor_ref_id, network_token_locker_id, - pm_network_token_data_encrypted.map(Into::into), + pm_network_token_data_encrypted, ) .await } else { @@ -512,14 +511,13 @@ where merchant_id, resp.metadata.clone().map(|val| val.expose()), customer_acceptance, - pm_data_encrypted.map(Into::into), + pm_data_encrypted, key_store, None, pm_status, network_transaction_id, merchant_account.storage_scheme, - encrypted_payment_method_billing_address - .map(Into::into), + encrypted_payment_method_billing_address, resp.card.and_then(|card| { card.card_network.map(|card_network| { card_network.to_string() @@ -527,7 +525,7 @@ where }), network_token_requestor_ref_id, network_token_locker_id, - pm_network_token_data_encrypted.map(Into::into), + pm_network_token_data_encrypted, ) .await } else { @@ -732,20 +730,20 @@ where merchant_id, pm_metadata, customer_acceptance, - pm_data_encrypted.map(Into::into), + pm_data_encrypted, key_store, None, pm_status, network_transaction_id, merchant_account.storage_scheme, - encrypted_payment_method_billing_address.map(Into::into), + encrypted_payment_method_billing_address, resp.card.and_then(|card| { card.card_network .map(|card_network| card_network.to_string()) }), network_token_requestor_ref_id, network_token_locker_id, - pm_network_token_data_encrypted.map(Into::into), + pm_network_token_data_encrypted, ) .await?; }; diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 661bd73b506..a3294d5627d 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -4002,7 +4002,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz currency: payment_data.currency, browser_info, email: payment_data.email, - payment_method_data: payment_data.payment_method_data.map(From::from), + payment_method_data: payment_data.payment_method_data, connector_transaction_id: payment_data .payment_attempt .get_connector_payment_id() @@ -4096,7 +4096,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProce let amount = payment_data.payment_attempt.get_total_amount(); Ok(Self { - payment_method_data: payment_method_data.map(From::from), + payment_method_data, email: payment_data.email, currency: Some(payment_data.currency), amount: Some(amount.get_amount_as_i64()), // need to change this once we move to connector module diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 7eb7925017e..332137b6a18 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -556,7 +556,7 @@ pub async fn save_payout_data_to_locker( merchant_account.get_id(), None, None, - card_details_encrypted.clone().map(Into::into), + card_details_encrypted.clone(), key_store, connector_mandate_details, None, diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs index c6b6946d15c..995975d12e8 100644 --- a/crates/router/src/services/authorization/roles.rs +++ b/crates/router/src/services/authorization/roles.rs @@ -165,7 +165,7 @@ impl From<diesel_models::role::Role> for RoleInfo { Self { role_id: role.role_id, role_name: role.role_name, - groups: role.groups.into_iter().map(Into::into).collect(), + groups: role.groups, scope: role.scope, entity_type: role.entity_type, is_invitable: true, diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 2852766cdd3..9764fb6222b 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -409,7 +409,7 @@ pub async fn create_profile_from_merchant_account( always_collect_shipping_details_from_wallet_connector: request .always_collect_shipping_details_from_wallet_connector .or(Some(false)), - outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers.map(Into::into), + outgoing_webhook_custom_http_headers, tax_connector_id: request.tax_connector_id, is_tax_connector_enabled: request.is_tax_connector_enabled, dynamic_routing_algorithm: None,
2025-02-25T12:54:09Z
## Type of Change - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR addresses the clippy lints occurring due to new rust version 1.85.0 https://rust-lang.github.io/rust-clippy/master/index.html#useless_conversion ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
6553e29e478a70e4d2f0124e5a55931377bd8123
6553e29e478a70e4d2f0124e5a55931377bd8123
juspay/hyperswitch
juspay__hyperswitch-7382
Bug: feat(core): create process tracker workflow create process tracker workflow
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 8f14dc8d860..0c58411dbf7 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -325,7 +325,7 @@ impl PaymentsCreateIntentRequest { } // This struct is only used internally, not visible in API Reference -#[derive(Debug, Clone, serde::Serialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index 1ee1a090ffa..7fda63fb6a5 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -103,6 +103,8 @@ pub enum ProcessTrackerStatus { ProcessStarted, // Finished by consumer Finish, + // Review the task + Review, } // Refund diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs index cd2c429c55e..f998ca5d237 100644 --- a/crates/diesel_models/src/process_tracker.rs +++ b/crates/diesel_models/src/process_tracker.rs @@ -210,6 +210,7 @@ pub enum ProcessTrackerRunner { OutgoingWebhookRetryWorkflow, AttachPayoutAccountWorkflow, PaymentMethodStatusUpdateWorkflow, + PassiveRecoveryWorkflow, } #[cfg(test)] @@ -265,4 +266,19 @@ pub mod business_status { /// Business status set for newly created tasks. pub const PENDING: &str = "Pending"; + + /// For the PCR Workflow + /// + /// This status indicates the completion of a execute task + pub const EXECUTE_WORKFLOW_COMPLETE: &str = "COMPLETED_EXECUTE_TASK"; + + /// This status indicates that the execute task was completed to trigger the psync task + pub const EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC: &str = "COMPLETED_EXECUTE_TASK_TO_TRIGGER_PSYNC"; + + /// This status indicates that the execute task was completed to trigger the review task + pub const EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW: &str = + "COMPLETED_EXECUTE_TASK_TO_TRIGGER_REVIEW"; + + /// This status indicates the completion of a psync task + pub const PSYNC_WORKFLOW_COMPLETE: &str = "COMPLETED_PSYNC_TASK"; } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index cc1a7054ded..fb08d7a7191 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -318,7 +318,7 @@ pub enum PaymentIntentUpdate { /// PreUpdate tracker of ConfirmIntent ConfirmIntent { status: common_enums::IntentStatus, - active_attempt_id: id_type::GlobalAttemptId, + active_attempt_id: Option<id_type::GlobalAttemptId>, updated_by: String, }, /// PostUpdate tracker of ConfirmIntent @@ -397,7 +397,7 @@ impl From<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal { updated_by, } => Self { status: Some(status), - active_attempt_id: Some(active_attempt_id), + active_attempt_id, modified_at: common_utils::date_time::now(), amount: None, amount_captured: None, diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index 63dc9a58632..a997d062bc8 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -252,7 +252,6 @@ pub async fn deep_health_check_func( #[derive(Debug, Copy, Clone)] pub struct WorkflowRunner; -#[cfg(feature = "v1")] #[async_trait::async_trait] impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner { async fn trigger_workflow<'a>( @@ -322,6 +321,9 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner { storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow => Ok(Box::new( workflows::payment_method_status_update::PaymentMethodStatusUpdateWorkflow, )), + storage::ProcessTrackerRunner::PassiveRecoveryWorkflow => Ok(Box::new( + workflows::passive_churn_recovery_workflow::ExecutePcrWorkflow, + )), } }; @@ -360,18 +362,6 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner { } } -#[cfg(feature = "v2")] -#[async_trait::async_trait] -impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner { - async fn trigger_workflow<'a>( - &'a self, - _state: &'a routes::SessionState, - _process: storage::ProcessTracker, - ) -> CustomResult<(), ProcessTrackerError> { - todo!() - } -} - async fn start_scheduler( state: &routes::AppState, scheduler_flow: scheduler::SchedulerFlow, diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 365cdaf3a12..fa243d0269a 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -57,4 +57,6 @@ pub mod webhooks; pub mod unified_authentication_service; +#[cfg(feature = "v2")] +pub mod passive_churn_recovery; pub mod relay; diff --git a/crates/router/src/core/passive_churn_recovery.rs b/crates/router/src/core/passive_churn_recovery.rs new file mode 100644 index 00000000000..3c77de98e7e --- /dev/null +++ b/crates/router/src/core/passive_churn_recovery.rs @@ -0,0 +1,207 @@ +pub mod transformers; +pub mod types; +use api_models::payments::PaymentsRetrieveRequest; +use common_utils::{self, id_type, types::keymanager::KeyManagerState}; +use diesel_models::process_tracker::business_status; +use error_stack::{self, ResultExt}; +use hyperswitch_domain_models::{ + errors::api_error_response, + payments::{PaymentIntent, PaymentStatusData}, +}; +use scheduler::errors; + +use crate::{ + core::{ + errors::RouterResult, + passive_churn_recovery::types as pcr_types, + payments::{self, operations::Operation}, + }, + db::StorageInterface, + logger, + routes::{metrics, SessionState}, + types::{ + api, + storage::{self, passive_churn_recovery as pcr}, + transformers::ForeignInto, + }, +}; + +pub async fn perform_execute_payment( + state: &SessionState, + execute_task_process: &storage::ProcessTracker, + tracking_data: &pcr::PcrWorkflowTrackingData, + pcr_data: &pcr::PcrPaymentData, + _key_manager_state: &KeyManagerState, + payment_intent: &PaymentIntent, +) -> Result<(), errors::ProcessTrackerError> { + let db = &*state.store; + let decision = pcr_types::Decision::get_decision_based_on_params( + state, + payment_intent.status, + false, + payment_intent.active_attempt_id.clone(), + pcr_data, + &tracking_data.global_payment_id, + ) + .await?; + // TODO decide if its a global failure or is it requeueable error + match decision { + pcr_types::Decision::Execute => { + let action = pcr_types::Action::execute_payment( + db, + pcr_data.merchant_account.get_id(), + payment_intent, + execute_task_process, + ) + .await?; + action + .execute_payment_task_response_handler( + db, + &pcr_data.merchant_account, + payment_intent, + execute_task_process, + &pcr_data.profile, + ) + .await?; + } + + pcr_types::Decision::Psync(attempt_status, attempt_id) => { + // find if a psync task is already present + let task = "PSYNC_WORKFLOW"; + let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; + let process_tracker_id = format!("{runner}_{task}_{}", attempt_id.get_string_repr()); + let psync_process = db.find_process_by_id(&process_tracker_id).await?; + + match psync_process { + Some(_) => { + let pcr_status: pcr_types::PcrAttemptStatus = attempt_status.foreign_into(); + + pcr_status + .update_pt_status_based_on_attempt_status_for_execute_payment( + db, + execute_task_process, + ) + .await?; + } + + None => { + // insert new psync task + insert_psync_pcr_task( + db, + pcr_data.merchant_account.get_id().clone(), + payment_intent.get_id().clone(), + pcr_data.profile.get_id().clone(), + attempt_id.clone(), + storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, + ) + .await?; + + // finish the current task + db.finish_process_with_business_status( + execute_task_process.clone(), + business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC, + ) + .await?; + } + }; + } + pcr_types::Decision::InvalidDecision => { + db.finish_process_with_business_status( + execute_task_process.clone(), + business_status::EXECUTE_WORKFLOW_COMPLETE, + ) + .await?; + logger::warn!("Abnormal State Identified") + } + } + + Ok(()) +} + +async fn insert_psync_pcr_task( + db: &dyn StorageInterface, + merchant_id: id_type::MerchantId, + payment_id: id_type::GlobalPaymentId, + profile_id: id_type::ProfileId, + payment_attempt_id: id_type::GlobalAttemptId, + runner: storage::ProcessTrackerRunner, +) -> RouterResult<storage::ProcessTracker> { + let task = "PSYNC_WORKFLOW"; + let process_tracker_id = format!("{runner}_{task}_{}", payment_attempt_id.get_string_repr()); + let schedule_time = common_utils::date_time::now(); + let psync_workflow_tracking_data = pcr::PcrWorkflowTrackingData { + global_payment_id: payment_id, + merchant_id, + profile_id, + payment_attempt_id, + }; + let tag = ["PCR"]; + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + psync_workflow_tracking_data, + schedule_time, + ) + .change_context(api_error_response::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct delete tokenized data process tracker task")?; + + let response = db + .insert_process(process_tracker_entry) + .await + .change_context(api_error_response::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct delete tokenized data process tracker task")?; + metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "PsyncPcr"))); + + Ok(response) +} + +pub async fn call_psync_api( + state: &SessionState, + global_payment_id: &id_type::GlobalPaymentId, + pcr_data: &pcr::PcrPaymentData, +) -> RouterResult<PaymentStatusData<api::PSync>> { + let operation = payments::operations::PaymentGet; + let req = PaymentsRetrieveRequest { + force_sync: false, + param: None, + expand_attempts: true, + }; + // TODO : Use api handler instead of calling get_tracker and payments_operation_core + // Get the tracker related information. This includes payment intent and payment attempt + let get_tracker_response = operation + .to_get_tracker()? + .get_trackers( + state, + global_payment_id, + &req, + &pcr_data.merchant_account, + &pcr_data.profile, + &pcr_data.key_store, + &hyperswitch_domain_models::payments::HeaderPayload::default(), + None, + ) + .await?; + + let (payment_data, _req, _, _, _) = Box::pin(payments::payments_operation_core::< + api::PSync, + _, + _, + _, + PaymentStatusData<api::PSync>, + >( + state, + state.get_req_state(), + pcr_data.merchant_account.clone(), + pcr_data.key_store.clone(), + &pcr_data.profile, + operation, + req, + get_tracker_response, + payments::CallConnectorAction::Trigger, + hyperswitch_domain_models::payments::HeaderPayload::default(), + )) + .await?; + Ok(payment_data) +} diff --git a/crates/router/src/core/passive_churn_recovery/transformers.rs b/crates/router/src/core/passive_churn_recovery/transformers.rs new file mode 100644 index 00000000000..ce47714353a --- /dev/null +++ b/crates/router/src/core/passive_churn_recovery/transformers.rs @@ -0,0 +1,39 @@ +use common_enums::AttemptStatus; + +use crate::{ + core::passive_churn_recovery::types::PcrAttemptStatus, types::transformers::ForeignFrom, +}; + +impl ForeignFrom<AttemptStatus> for PcrAttemptStatus { + fn foreign_from(s: AttemptStatus) -> Self { + match s { + AttemptStatus::Authorized | AttemptStatus::Charged | AttemptStatus::AutoRefunded => { + Self::Succeeded + } + + AttemptStatus::Started + | AttemptStatus::AuthenticationSuccessful + | AttemptStatus::Authorizing + | AttemptStatus::CodInitiated + | AttemptStatus::VoidInitiated + | AttemptStatus::CaptureInitiated + | AttemptStatus::Pending => Self::Processing, + + AttemptStatus::AuthenticationFailed + | AttemptStatus::AuthorizationFailed + | AttemptStatus::VoidFailed + | AttemptStatus::RouterDeclined + | AttemptStatus::CaptureFailed + | AttemptStatus::Failure => Self::Failed, + + AttemptStatus::Voided + | AttemptStatus::ConfirmationAwaited + | AttemptStatus::PartialCharged + | AttemptStatus::PartialChargedAndChargeable + | AttemptStatus::PaymentMethodAwaited + | AttemptStatus::AuthenticationPending + | AttemptStatus::DeviceDataCollectionPending + | AttemptStatus::Unresolved => Self::InvalidStatus(s.to_string()), + } + } +} diff --git a/crates/router/src/core/passive_churn_recovery/types.rs b/crates/router/src/core/passive_churn_recovery/types.rs new file mode 100644 index 00000000000..c47248a882a --- /dev/null +++ b/crates/router/src/core/passive_churn_recovery/types.rs @@ -0,0 +1,259 @@ +use common_enums::{self, AttemptStatus, IntentStatus}; +use common_utils::{self, ext_traits::OptionExt, id_type}; +use diesel_models::{enums, process_tracker::business_status}; +use error_stack::{self, ResultExt}; +use hyperswitch_domain_models::{ + business_profile, merchant_account, + payments::{PaymentConfirmData, PaymentIntent}, +}; +use time::PrimitiveDateTime; + +use crate::{ + core::{ + errors::{self, RouterResult}, + passive_churn_recovery::{self as core_pcr}, + }, + db::StorageInterface, + logger, + routes::SessionState, + types::{api::payments as api_types, storage, transformers::ForeignInto}, + workflows::passive_churn_recovery_workflow::get_schedule_time_to_retry_mit_payments, +}; + +type RecoveryResult<T> = error_stack::Result<T, errors::RecoveryError>; + +/// The status of Passive Churn Payments +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub enum PcrAttemptStatus { + Succeeded, + Failed, + Processing, + InvalidStatus(String), + // Cancelled, +} + +impl PcrAttemptStatus { + pub(crate) async fn update_pt_status_based_on_attempt_status_for_execute_payment( + &self, + db: &dyn StorageInterface, + execute_task_process: &storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + match &self { + Self::Succeeded | Self::Failed | Self::Processing => { + // finish the current execute task + db.finish_process_with_business_status( + execute_task_process.clone(), + business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC, + ) + .await?; + } + + Self::InvalidStatus(action) => { + logger::debug!( + "Invalid Attempt Status for the Recovery Payment : {}", + action + ); + let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { + status: enums::ProcessTrackerStatus::Review, + business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)), + }; + // update the process tracker status as Review + db.update_process(execute_task_process.clone(), pt_update) + .await?; + } + }; + Ok(()) + } +} +#[derive(Debug, Clone)] +pub enum Decision { + Execute, + Psync(AttemptStatus, id_type::GlobalAttemptId), + InvalidDecision, +} + +impl Decision { + pub async fn get_decision_based_on_params( + state: &SessionState, + intent_status: IntentStatus, + called_connector: bool, + active_attempt_id: Option<id_type::GlobalAttemptId>, + pcr_data: &storage::passive_churn_recovery::PcrPaymentData, + payment_id: &id_type::GlobalPaymentId, + ) -> RecoveryResult<Self> { + Ok(match (intent_status, called_connector, active_attempt_id) { + (IntentStatus::Failed, false, None) => Self::Execute, + (IntentStatus::Processing, true, Some(_)) => { + let psync_data = core_pcr::call_psync_api(state, payment_id, pcr_data) + .await + .change_context(errors::RecoveryError::PaymentCallFailed) + .attach_printable("Error while executing the Psync call")?; + let payment_attempt = psync_data + .payment_attempt + .get_required_value("Payment Attempt") + .change_context(errors::RecoveryError::ValueNotFound) + .attach_printable("Error while executing the Psync call")?; + Self::Psync(payment_attempt.status, payment_attempt.get_id().clone()) + } + _ => Self::InvalidDecision, + }) + } +} + +#[derive(Debug, Clone)] +pub enum Action { + SyncPayment(id_type::GlobalAttemptId), + RetryPayment(PrimitiveDateTime), + TerminalFailure, + SuccessfulPayment, + ReviewPayment, + ManualReviewAction, +} +impl Action { + pub async fn execute_payment( + db: &dyn StorageInterface, + merchant_id: &id_type::MerchantId, + payment_intent: &PaymentIntent, + process: &storage::ProcessTracker, + ) -> RecoveryResult<Self> { + // call the proxy api + let response = call_proxy_api::<api_types::Authorize>(payment_intent); + // handle proxy api's response + match response { + Ok(payment_data) => match payment_data.payment_attempt.status.foreign_into() { + PcrAttemptStatus::Succeeded => Ok(Self::SuccessfulPayment), + PcrAttemptStatus::Failed => { + Self::decide_retry_failure_action(db, merchant_id, process.clone()).await + } + + PcrAttemptStatus::Processing => { + Ok(Self::SyncPayment(payment_data.payment_attempt.id)) + } + PcrAttemptStatus::InvalidStatus(action) => { + logger::info!(?action, "Invalid Payment Status For PCR Payment"); + Ok(Self::ManualReviewAction) + } + }, + Err(err) => + // check for an active attempt being constructed or not + { + logger::error!(execute_payment_res=?err); + match payment_intent.active_attempt_id.clone() { + Some(attempt_id) => Ok(Self::SyncPayment(attempt_id)), + None => Ok(Self::ReviewPayment), + } + } + } + } + + pub async fn execute_payment_task_response_handler( + &self, + db: &dyn StorageInterface, + merchant_account: &merchant_account::MerchantAccount, + payment_intent: &PaymentIntent, + execute_task_process: &storage::ProcessTracker, + profile: &business_profile::Profile, + ) -> Result<(), errors::ProcessTrackerError> { + match self { + Self::SyncPayment(attempt_id) => { + core_pcr::insert_psync_pcr_task( + db, + merchant_account.get_id().to_owned(), + payment_intent.id.clone(), + profile.get_id().to_owned(), + attempt_id.clone(), + storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, + ) + .await + .change_context(errors::RecoveryError::ProcessTrackerFailure) + .attach_printable("Failed to create a psync workflow in the process tracker")?; + + db.as_scheduler() + .finish_process_with_business_status( + execute_task_process.clone(), + business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC, + ) + .await + .change_context(errors::RecoveryError::ProcessTrackerFailure) + .attach_printable("Failed to update the process tracker")?; + Ok(()) + } + + Self::RetryPayment(schedule_time) => { + let mut pt = execute_task_process.clone(); + // update the schedule time + pt.schedule_time = Some(*schedule_time); + + let pt_task_update = diesel_models::ProcessTrackerUpdate::StatusUpdate { + status: storage::enums::ProcessTrackerStatus::Pending, + business_status: Some(business_status::PENDING.to_owned()), + }; + db.as_scheduler() + .update_process(pt.clone(), pt_task_update) + .await?; + // TODO: update the connector called field and make the active attempt None + + Ok(()) + } + Self::TerminalFailure => { + // TODO: Record a failure transaction back to Billing Connector + Ok(()) + } + Self::SuccessfulPayment => Ok(()), + Self::ReviewPayment => Ok(()), + Self::ManualReviewAction => { + logger::debug!("Invalid Payment Status For PCR Payment"); + let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { + status: enums::ProcessTrackerStatus::Review, + business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)), + }; + // update the process tracker status as Review + db.as_scheduler() + .update_process(execute_task_process.clone(), pt_update) + .await?; + Ok(()) + } + } + } + + pub(crate) async fn decide_retry_failure_action( + db: &dyn StorageInterface, + merchant_id: &id_type::MerchantId, + pt: storage::ProcessTracker, + ) -> RecoveryResult<Self> { + let schedule_time = + get_schedule_time_to_retry_mit_payments(db, merchant_id, pt.retry_count + 1).await; + match schedule_time { + Some(schedule_time) => Ok(Self::RetryPayment(schedule_time)), + + None => Ok(Self::TerminalFailure), + } + } +} + +// This function would be converted to proxy_payments_core +fn call_proxy_api<F>(payment_intent: &PaymentIntent) -> RouterResult<PaymentConfirmData<F>> +where + F: Send + Clone + Sync, +{ + let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new( + payment_intent + .shipping_address + .clone() + .map(|address| address.into_inner()), + payment_intent + .billing_address + .clone() + .map(|address| address.into_inner()), + None, + Some(true), + ); + let response = PaymentConfirmData { + flow: std::marker::PhantomData, + payment_intent: payment_intent.clone(), + payment_attempt: todo!(), + payment_method_data: None, + payment_address, + }; + Ok(response) +} diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs index 0f42948e3f0..40b1918323c 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -210,8 +210,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, PaymentsConfir ) .await?; - let payment_attempt = db - .insert_payment_attempt( + let payment_attempt: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt = + db.insert_payment_attempt( key_manager_state, key_store, payment_attempt_domain_model, @@ -416,7 +416,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentConfirmData<F>, PaymentsConfirmInt hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::ConfirmIntent { status: intent_status, updated_by: storage_scheme.to_string(), - active_attempt_id: payment_data.payment_attempt.id.clone(), + active_attempt_id: Some(payment_data.payment_attempt.id.clone()), }; let authentication_type = payment_data.payment_attempt.authentication_type; diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 96a0d580056..bd033ff4c2a 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -28,6 +28,8 @@ pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; pub mod merchant_key_store; +#[cfg(feature = "v2")] +pub mod passive_churn_recovery; pub mod payment_attempt; pub mod payment_link; pub mod payment_method; diff --git a/crates/router/src/types/storage/passive_churn_recovery.rs b/crates/router/src/types/storage/passive_churn_recovery.rs new file mode 100644 index 00000000000..3cf3316a398 --- /dev/null +++ b/crates/router/src/types/storage/passive_churn_recovery.rs @@ -0,0 +1,18 @@ +use std::fmt::Debug; + +use common_utils::id_type; +use hyperswitch_domain_models::{business_profile, merchant_account, merchant_key_store}; +#[derive(serde::Serialize, serde::Deserialize, Debug)] +pub struct PcrWorkflowTrackingData { + pub merchant_id: id_type::MerchantId, + pub profile_id: id_type::ProfileId, + pub global_payment_id: id_type::GlobalPaymentId, + pub payment_attempt_id: id_type::GlobalAttemptId, +} + +#[derive(Debug, Clone)] +pub struct PcrPaymentData { + pub merchant_account: merchant_account::MerchantAccount, + pub profile: business_profile::Profile, + pub key_store: merchant_key_store::MerchantKeyStore, +} diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs index e86d49faf6c..4961932e067 100644 --- a/crates/router/src/workflows.rs +++ b/crates/router/src/workflows.rs @@ -2,12 +2,12 @@ pub mod api_key_expiry; #[cfg(feature = "payouts")] pub mod attach_payout_account_workflow; -#[cfg(feature = "v1")] pub mod outgoing_webhook_retry; -#[cfg(feature = "v1")] pub mod payment_method_status_update; pub mod payment_sync; -#[cfg(feature = "v1")] + pub mod refund_router; -#[cfg(feature = "v1")] + pub mod tokenized_data; + +pub mod passive_churn_recovery_workflow; diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs index c7df4aeff0c..9be893c7ac8 100644 --- a/crates/router/src/workflows/outgoing_webhook_retry.rs +++ b/crates/router/src/workflows/outgoing_webhook_retry.rs @@ -36,6 +36,7 @@ pub struct OutgoingWebhookRetryWorkflow; #[async_trait::async_trait] impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn execute_workflow<'a>( &'a self, @@ -226,6 +227,14 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { Ok(()) } + #[cfg(feature = "v2")] + async fn execute_workflow<'a>( + &'a self, + _state: &'a SessionState, + _process: storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + todo!() + } #[instrument(skip_all)] async fn error_handler<'a>( @@ -266,6 +275,7 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow { /// seconds between them by default. /// - `custom_merchant_mapping.merchant_id1`: Merchant-specific retry configuration for merchant /// with merchant ID `merchant_id1`. +#[cfg(feature = "v1")] #[instrument(skip_all)] pub(crate) async fn get_webhook_delivery_retry_schedule_time( db: &dyn StorageInterface, @@ -311,6 +321,7 @@ pub(crate) async fn get_webhook_delivery_retry_schedule_time( } /// Schedule the webhook delivery task for retry +#[cfg(feature = "v1")] #[instrument(skip_all)] pub(crate) async fn retry_webhook_delivery_task( db: &dyn StorageInterface, @@ -334,6 +345,7 @@ pub(crate) async fn retry_webhook_delivery_task( } } +#[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_outgoing_webhook_content_and_event_type( state: SessionState, diff --git a/crates/router/src/workflows/passive_churn_recovery_workflow.rs b/crates/router/src/workflows/passive_churn_recovery_workflow.rs new file mode 100644 index 00000000000..d67f91f1169 --- /dev/null +++ b/crates/router/src/workflows/passive_churn_recovery_workflow.rs @@ -0,0 +1,175 @@ +#[cfg(feature = "v2")] +use api_models::payments::PaymentsGetIntentRequest; +#[cfg(feature = "v2")] +use common_utils::ext_traits::{StringExt, ValueExt}; +#[cfg(feature = "v2")] +use error_stack::ResultExt; +#[cfg(feature = "v2")] +use hyperswitch_domain_models::payments::PaymentIntentData; +#[cfg(feature = "v2")] +use router_env::logger; +use scheduler::{consumer::workflows::ProcessTrackerWorkflow, errors}; +#[cfg(feature = "v2")] +use scheduler::{types::process_data, utils as scheduler_utils}; + +#[cfg(feature = "v2")] +use crate::{ + core::{ + passive_churn_recovery::{self as pcr}, + payments, + }, + db::StorageInterface, + errors::StorageError, + types::{ + api::{self as api_types}, + storage::passive_churn_recovery as pcr_storage_types, + }, +}; +use crate::{routes::SessionState, types::storage}; +pub struct ExecutePcrWorkflow; + +#[async_trait::async_trait] +impl ProcessTrackerWorkflow<SessionState> for ExecutePcrWorkflow { + #[cfg(feature = "v1")] + async fn execute_workflow<'a>( + &'a self, + _state: &'a SessionState, + _process: storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + Ok(()) + } + #[cfg(feature = "v2")] + async fn execute_workflow<'a>( + &'a self, + state: &'a SessionState, + process: storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + let tracking_data = process + .tracking_data + .clone() + .parse_value::<pcr_storage_types::PcrWorkflowTrackingData>( + "PCRWorkflowTrackingData", + )?; + let request = PaymentsGetIntentRequest { + id: tracking_data.global_payment_id.clone(), + }; + let key_manager_state = &state.into(); + let pcr_data = extract_data_and_perform_action(state, &tracking_data).await?; + let (payment_data, _, _) = payments::payments_intent_operation_core::< + api_types::PaymentGetIntent, + _, + _, + PaymentIntentData<api_types::PaymentGetIntent>, + >( + state, + state.get_req_state(), + pcr_data.merchant_account.clone(), + pcr_data.profile.clone(), + pcr_data.key_store.clone(), + payments::operations::PaymentGetIntent, + request, + tracking_data.global_payment_id.clone(), + hyperswitch_domain_models::payments::HeaderPayload::default(), + None, + ) + .await?; + + match process.name.as_deref() { + Some("EXECUTE_WORKFLOW") => { + pcr::perform_execute_payment( + state, + &process, + &tracking_data, + &pcr_data, + key_manager_state, + &payment_data.payment_intent, + ) + .await + } + Some("PSYNC_WORKFLOW") => todo!(), + + Some("REVIEW_WORKFLOW") => todo!(), + _ => Err(errors::ProcessTrackerError::JobNotFound), + } + } +} +#[cfg(feature = "v2")] +pub(crate) async fn extract_data_and_perform_action( + state: &SessionState, + tracking_data: &pcr_storage_types::PcrWorkflowTrackingData, +) -> Result<pcr_storage_types::PcrPaymentData, errors::ProcessTrackerError> { + let db = &state.store; + + let key_manager_state = &state.into(); + let key_store = db + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &tracking_data.merchant_id, + &db.get_master_key().to_vec().into(), + ) + .await?; + + let merchant_account = db + .find_merchant_account_by_merchant_id( + key_manager_state, + &tracking_data.merchant_id, + &key_store, + ) + .await?; + + let profile = db + .find_business_profile_by_profile_id( + key_manager_state, + &key_store, + &tracking_data.profile_id, + ) + .await?; + + let pcr_payment_data = pcr_storage_types::PcrPaymentData { + merchant_account, + profile, + key_store, + }; + Ok(pcr_payment_data) +} + +#[cfg(feature = "v2")] +pub(crate) async fn get_schedule_time_to_retry_mit_payments( + db: &dyn StorageInterface, + merchant_id: &common_utils::id_type::MerchantId, + retry_count: i32, +) -> Option<time::PrimitiveDateTime> { + let key = "pt_mapping_pcr_retries"; + let result = db + .find_config_by_key(key) + .await + .map(|value| value.config) + .and_then(|config| { + config + .parse_struct("RevenueRecoveryPaymentProcessTrackerMapping") + .change_context(StorageError::DeserializationFailed) + }); + + let mapping = result.map_or_else( + |error| { + if error.current_context().is_db_not_found() { + logger::debug!("Revenue Recovery retry config `{key}` not found, ignoring"); + } else { + logger::error!( + ?error, + "Failed to read Revenue Recovery retry config `{key}`" + ); + } + process_data::RevenueRecoveryPaymentProcessTrackerMapping::default() + }, + |mapping| { + logger::debug!(?mapping, "Using custom pcr payments retry config"); + mapping + }, + ); + + let time_delta = + scheduler_utils::get_pcr_payments_retry_schedule_time(mapping, merchant_id, retry_count); + + scheduler_utils::get_time_from_delta(time_delta) +} diff --git a/crates/router/src/workflows/payment_method_status_update.rs b/crates/router/src/workflows/payment_method_status_update.rs index 124417e3355..dba3bace252 100644 --- a/crates/router/src/workflows/payment_method_status_update.rs +++ b/crates/router/src/workflows/payment_method_status_update.rs @@ -111,6 +111,14 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodStatusUpdateWorkflow Ok(()) } + #[cfg(feature = "v2")] + async fn execute_workflow<'a>( + &'a self, + _state: &'a SessionState, + _process: storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + todo!() + } async fn error_handler<'a>( &'a self, _state: &'a SessionState, diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index fb83922935e..64c4853d14b 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -31,8 +31,8 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow { #[cfg(feature = "v2")] async fn execute_workflow<'a>( &'a self, - state: &'a SessionState, - process: storage::ProcessTracker, + _state: &'a SessionState, + _process: storage::ProcessTracker, ) -> Result<(), sch_errors::ProcessTrackerError> { todo!() } diff --git a/crates/router/src/workflows/refund_router.rs b/crates/router/src/workflows/refund_router.rs index 515e34c0689..82e7d8a45de 100644 --- a/crates/router/src/workflows/refund_router.rs +++ b/crates/router/src/workflows/refund_router.rs @@ -1,13 +1,14 @@ use scheduler::consumer::workflows::ProcessTrackerWorkflow; -use crate::{ - core::refunds as refund_flow, errors, logger::error, routes::SessionState, types::storage, -}; +#[cfg(feature = "v1")] +use crate::core::refunds as refund_flow; +use crate::{errors, logger::error, routes::SessionState, types::storage}; pub struct RefundWorkflowRouter; #[async_trait::async_trait] impl ProcessTrackerWorkflow<SessionState> for RefundWorkflowRouter { + #[cfg(feature = "v1")] async fn execute_workflow<'a>( &'a self, state: &'a SessionState, @@ -15,6 +16,14 @@ impl ProcessTrackerWorkflow<SessionState> for RefundWorkflowRouter { ) -> Result<(), errors::ProcessTrackerError> { Ok(Box::pin(refund_flow::start_refund_workflow(state, &process)).await?) } + #[cfg(feature = "v2")] + async fn execute_workflow<'a>( + &'a self, + _state: &'a SessionState, + _process: storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + todo!() + } async fn error_handler<'a>( &'a self, diff --git a/crates/router/src/workflows/tokenized_data.rs b/crates/router/src/workflows/tokenized_data.rs index bc1842205ae..2f2474df66c 100644 --- a/crates/router/src/workflows/tokenized_data.rs +++ b/crates/router/src/workflows/tokenized_data.rs @@ -1,13 +1,14 @@ use scheduler::consumer::workflows::ProcessTrackerWorkflow; -use crate::{ - core::payment_methods::vault, errors, logger::error, routes::SessionState, types::storage, -}; +#[cfg(feature = "v1")] +use crate::core::payment_methods::vault; +use crate::{errors, logger::error, routes::SessionState, types::storage}; pub struct DeleteTokenizeDataWorkflow; #[async_trait::async_trait] impl ProcessTrackerWorkflow<SessionState> for DeleteTokenizeDataWorkflow { + #[cfg(feature = "v1")] async fn execute_workflow<'a>( &'a self, state: &'a SessionState, @@ -16,6 +17,15 @@ impl ProcessTrackerWorkflow<SessionState> for DeleteTokenizeDataWorkflow { Ok(vault::start_tokenize_data_workflow(state, &process).await?) } + #[cfg(feature = "v2")] + async fn execute_workflow<'a>( + &'a self, + _state: &'a SessionState, + _process: storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + todo!() + } + async fn error_handler<'a>( &'a self, _state: &'a SessionState, diff --git a/crates/scheduler/src/consumer/types/process_data.rs b/crates/scheduler/src/consumer/types/process_data.rs index f68ad4795df..26d0fdf7022 100644 --- a/crates/scheduler/src/consumer/types/process_data.rs +++ b/crates/scheduler/src/consumer/types/process_data.rs @@ -82,3 +82,39 @@ impl Default for OutgoingWebhookRetryProcessTrackerMapping { } } } + +/// Configuration for outgoing webhook retries. +#[derive(Debug, Serialize, Deserialize)] +pub struct RevenueRecoveryPaymentProcessTrackerMapping { + /// Default (fallback) retry configuration used when no merchant-specific retry configuration + /// exists. + pub default_mapping: RetryMapping, + + /// Merchant-specific retry configuration. + pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>, +} + +impl Default for RevenueRecoveryPaymentProcessTrackerMapping { + fn default() -> Self { + Self { + default_mapping: RetryMapping { + // 1st attempt happens after 1 minute of it being + start_after: 60, + + frequencies: vec![ + // 2nd and 3rd attempts happen at intervals of 3 hours each + (60 * 60 * 3, 2), + // 4th, 5th, 6th attempts happen at intervals of 6 hours each + (60 * 60 * 6, 3), + // 7th, 8th, 9th attempts happen at intervals of 9 hour each + (60 * 60 * 9, 3), + // 10th, 11th and 12th attempts happen at intervals of 12 hours each + (60 * 60 * 12, 3), + // 13th, 14th and 15th attempts happen at intervals of 18 hours each + (60 * 60 * 18, 3), + ], + }, + custom_merchant_mapping: HashMap::new(), + } + } +} diff --git a/crates/scheduler/src/errors.rs b/crates/scheduler/src/errors.rs index 1fb7599aed0..254c4979524 100644 --- a/crates/scheduler/src/errors.rs +++ b/crates/scheduler/src/errors.rs @@ -4,7 +4,7 @@ use external_services::email::EmailError; use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse; pub use redis_interface::errors::RedisError; pub use storage_impl::errors::ApplicationError; -use storage_impl::errors::StorageError; +use storage_impl::errors::{RecoveryError, StorageError}; use crate::env::logger::{self, error}; @@ -46,6 +46,8 @@ pub enum ProcessTrackerError { EApiErrorResponse, #[error("Received Error ClientError")] EClientError, + #[error("Received RecoveryError: {0:?}")] + ERecoveryError(error_stack::Report<RecoveryError>), #[error("Received Error StorageError: {0:?}")] EStorageError(error_stack::Report<StorageError>), #[error("Received Error RedisError: {0:?}")] @@ -131,3 +133,8 @@ error_to_process_tracker_error!( error_stack::Report<EmailError>, ProcessTrackerError::EEmailError(error_stack::Report<EmailError>) ); + +error_to_process_tracker_error!( + error_stack::Report<RecoveryError>, + ProcessTrackerError::ERecoveryError(error_stack::Report<RecoveryError>) +); diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs index 0dbea173eae..3d7f637de90 100644 --- a/crates/scheduler/src/utils.rs +++ b/crates/scheduler/src/utils.rs @@ -350,6 +350,25 @@ pub fn get_outgoing_webhook_retry_schedule_time( } } +pub fn get_pcr_payments_retry_schedule_time( + mapping: process_data::RevenueRecoveryPaymentProcessTrackerMapping, + merchant_id: &common_utils::id_type::MerchantId, + retry_count: i32, +) -> Option<i32> { + let mapping = match mapping.custom_merchant_mapping.get(merchant_id) { + Some(map) => map.clone(), + None => mapping.default_mapping, + }; + // TODO: check if the current scheduled time is not more than the configured timerange + + // For first try, get the `start_after` time + if retry_count == 0 { + Some(mapping.start_after) + } else { + get_delay(retry_count, &mapping.frequencies) + } +} + /// Get the delay based on the retry count pub fn get_delay<'a>( retry_count: i32, diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index d75911d593c..657e9b000a5 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -299,3 +299,15 @@ pub enum HealthCheckGRPCServiceError { #[error("Failed to establish connection with gRPC service")] FailedToCallService, } + +#[derive(thiserror::Error, Debug, Clone)] +pub enum RecoveryError { + #[error("Failed to make a recovery payment")] + PaymentCallFailed, + #[error("Encountered a Process Tracker Task Failure")] + ProcessTrackerFailure, + #[error("The encountered task is invalid")] + InvalidTask, + #[error("The Intended data was not found")] + ValueNotFound, +}
2025-01-28T06:07:28Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - This PR ,creates a process_tracker execute workflow , to trigger a MIT Payment retry - The first retry attempt , would create a Execute task entry in the PT which would do a api call to the pg to do the MIT payment, - Its based on the intent status and the called connector param and active_attemt_id, we take a decision, If Decision: - **Execute** (i.e, the payment_intent status is in processing and there is no active attempt present) > **Action**: The payment is done , and based on the attempt status get the actions >If its a **sync Action** , then the payment status is processing -> create another task to perform psync **;** Finish the current task > If the payment_status is a **success** -> Send back a successful webhook **;** Finish the current task > If the payment is a **terminal_failure** -> Send back a failure webhook **;** Finish The Current Task > If the payment is a **retryable payment** the action would be **Retry** -> update the current task process to pending and increment the retry count by 1 > If its an unintended attempt status move it to Manual Review **;** Mark the current task’s pt status as ‘Review’ > If there was an error check if , => If the payment intent doesn’t have an **active_attempt_id** , a new pt task `REVIEW_TASK` is introduced **;** Finish the current task => If there is a **active_attempt_id** then, create another task to perform psync **;** Finish the current task - **Psync** (i.e., the payment_intent status is in processing but the connector has been called and there is an active attempt) > If an existing process_tracker entry for the `PSYNC TASK`exists, then => **Action**: match attempt status and update the process tracker status based on that. => Finish the current task > If there isn’t any `PSYNC_TASK` in process tracker, => **Action**: Create a new psync_task in process tracker => Finish the current task - **ReviewTaskForFailedPayment**(To check if the failure is a terminal failure or a retryable one in which the db update for connector_called field and active_attempt_id did not happen successfully) | **ReviewTaskForSuccessfulPayment** (to prevent from double charge) > Create a `Review_Task` , which is would to handle the abnormal states of a payment (it would re evaluate the decision taken on payment_intent’s params) ; finish the current task > `This is implemented in the following` [PR](https://github.com/juspay/hyperswitch/pull/7178) - InvalidTask > If there is an ambiguous state then log it and finish the current task ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? > This is a v2 PR, cannot be tested , until this [PR](https://github.com/juspay/hyperswitch/pull/7215) gets merged ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.112.0
d945da635dfc84a2135aef456292fa54d9d5982e
d945da635dfc84a2135aef456292fa54d9d5982e
juspay/hyperswitch
juspay__hyperswitch-7363
Bug: chore: resolve v2 warnings in diesel_models Resolve v2 warnings in diesel_models.
diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs index 769a185c13c..be7f1b7ebeb 100644 --- a/crates/diesel_models/src/merchant_connector_account.rs +++ b/crates/diesel_models/src/merchant_connector_account.rs @@ -11,7 +11,7 @@ use crate::enums as storage_enums; #[cfg(feature = "v1")] use crate::schema::merchant_connector_account; #[cfg(feature = "v2")] -use crate::{enums, schema_v2::merchant_connector_account, types}; +use crate::schema_v2::merchant_connector_account; #[cfg(feature = "v1")] #[derive( diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 63f039c32f9..0ec57d9a911 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -966,7 +966,7 @@ impl PaymentAttemptUpdateInternal { #[cfg(feature = "v2")] impl PaymentAttemptUpdate { - pub fn apply_changeset(self, source: PaymentAttempt) -> PaymentAttempt { + pub fn apply_changeset(self, _source: PaymentAttempt) -> PaymentAttempt { todo!() // let PaymentAttemptUpdateInternal { // net_amount, @@ -1188,7 +1188,7 @@ impl PaymentAttemptUpdate { #[cfg(feature = "v2")] impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { - fn from(payment_attempt_update: PaymentAttemptUpdate) -> Self { + fn from(_payment_attempt_update: PaymentAttemptUpdate) -> Self { todo!() // match payment_attempt_update { // PaymentAttemptUpdate::Update { diff --git a/crates/diesel_models/src/query/merchant_account.rs b/crates/diesel_models/src/query/merchant_account.rs index ab51953b6ef..0b641217d4d 100644 --- a/crates/diesel_models/src/query/merchant_account.rs +++ b/crates/diesel_models/src/query/merchant_account.rs @@ -1,5 +1,8 @@ +#[cfg(feature = "v1")] use common_types::consts::API_VERSION; -use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; +#[cfg(feature = "v1")] +use diesel::BoolExpressionMethods; +use diesel::{associations::HasTable, ExpressionMethods, Table}; use super::generics; #[cfg(feature = "v1")] diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs index 2543ab41461..1226f44221a 100644 --- a/crates/diesel_models/src/query/payment_attempt.rs +++ b/crates/diesel_models/src/query/payment_attempt.rs @@ -1,9 +1,11 @@ +#[cfg(feature = "v1")] use std::collections::HashSet; use async_bb8_diesel::AsyncRunQueryDsl; +#[cfg(feature = "v1")] +use diesel::Table; use diesel::{ - associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, - QueryDsl, Table, + associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, QueryDsl, }; use error_stack::{report, ResultExt}; @@ -12,14 +14,14 @@ use super::generics; use crate::schema::payment_attempt::dsl; #[cfg(feature = "v2")] use crate::schema_v2::payment_attempt::dsl; +#[cfg(feature = "v1")] +use crate::{enums::IntentStatus, payment_attempt::PaymentAttemptUpdate, PaymentIntent}; use crate::{ - enums::{self, IntentStatus}, + enums::{self}, errors::DatabaseError, - payment_attempt::{ - PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate, PaymentAttemptUpdateInternal, - }, + payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdateInternal}, query::generics::db_metrics, - PaymentIntent, PgPooledConn, StorageResult, + PgPooledConn, StorageResult, }; impl PaymentAttemptNew { diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs index 62f6f37ba52..efb9198a28f 100644 --- a/crates/diesel_models/src/query/payment_method.rs +++ b/crates/diesel_models/src/query/payment_method.rs @@ -1,7 +1,11 @@ use async_bb8_diesel::AsyncRunQueryDsl; +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] +use diesel::Table; use diesel::{ - associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, - QueryDsl, Table, + associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, QueryDsl, }; use error_stack::ResultExt; diff --git a/crates/diesel_models/src/query/user/sample_data.rs b/crates/diesel_models/src/query/user/sample_data.rs index 8ef4b1e9303..40cd264c052 100644 --- a/crates/diesel_models/src/query/user/sample_data.rs +++ b/crates/diesel_models/src/query/user/sample_data.rs @@ -14,9 +14,11 @@ use crate::schema_v2::{ refund::dsl as refund_dsl, }; use crate::{ - errors, schema::dispute::dsl as dispute_dsl, user, Dispute, DisputeNew, PaymentAttempt, - PaymentIntent, PaymentIntentNew, PgPooledConn, Refund, RefundNew, StorageResult, + errors, schema::dispute::dsl as dispute_dsl, Dispute, DisputeNew, PaymentAttempt, + PaymentIntent, PgPooledConn, Refund, RefundNew, StorageResult, }; +#[cfg(feature = "v1")] +use crate::{user, PaymentIntentNew}; #[cfg(feature = "v1")] pub async fn insert_payment_intents( diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index 9212d416cb7..26c1834eb6d 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -1,20 +1,23 @@ +#[cfg(feature = "v1")] use common_enums::{ AttemptStatus, AuthenticationType, CaptureMethod, Currency, PaymentExperience, PaymentMethod, PaymentMethodType, }; +#[cfg(feature = "v1")] use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; +#[cfg(feature = "v1")] use common_utils::types::{ConnectorTransactionId, MinorUnit}; +#[cfg(feature = "v1")] use serde::{Deserialize, Serialize}; +#[cfg(feature = "v1")] use time::PrimitiveDateTime; #[cfg(feature = "v1")] -use crate::schema::payment_attempt; -#[cfg(feature = "v2")] -use crate::schema_v2::payment_attempt; use crate::{ enums::{MandateDataType, MandateDetails}, + schema::payment_attempt, ConnectorMandateReferenceId, PaymentAttemptNew, };
2025-02-24T10:36:27Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR resolves the v2 warnings generated in diesel_models. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
eabef328c665cfbaf953a5eb15bd15484c62dcf7
eabef328c665cfbaf953a5eb15bd15484c62dcf7
juspay/hyperswitch
juspay__hyperswitch-7388
Bug: feat(users): Add V2 User APIs to Support Modularity for Merchant Accounts Add v2 routes for supporting dashboard functions: - create new v2 merchant account - list v2 merchant accounts for user in org - switch to a v2 merchant account Also: - add merchant account permission for recon
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index aab8f518abe..5e0564b4187 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -19,8 +19,9 @@ use crate::user::{ SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest, SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse, TwoFactorAuthStatusResponse, TwoFactorStatus, UpdateUserAccountDetailsRequest, - UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate, - UserOrgMerchantCreateRequest, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, + UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantAccountResponse, + UserMerchantCreate, UserOrgMerchantCreateRequest, VerifyEmailRequest, + VerifyRecoveryCodeRequest, VerifyTotpRequest, }; common_utils::impl_api_event_type!( @@ -39,6 +40,7 @@ common_utils::impl_api_event_type!( CreateInternalUserRequest, CreateTenantUserRequest, UserOrgMerchantCreateRequest, + UserMerchantAccountResponse, UserMerchantCreate, AuthorizeResponse, ConnectAccountRequest, diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index ea979bfe735..aa39877f0c7 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -133,6 +133,7 @@ pub struct UserOrgMerchantCreateRequest { #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserMerchantCreate { pub company_name: String, + pub product_type: Option<common_enums::MerchantProductType>, } #[derive(serde::Serialize, Debug, Clone)] @@ -151,6 +152,7 @@ pub struct GetUserDetailsResponse { pub profile_id: id_type::ProfileId, pub entity_type: EntityType, pub theme_id: Option<String>, + pub version: common_enums::ApiVersion, } #[derive(Debug, serde::Deserialize, serde::Serialize)] @@ -382,9 +384,11 @@ pub struct ListOrgsForUserResponse { } #[derive(Debug, serde::Serialize)] -pub struct ListMerchantsForUserInOrgResponse { +pub struct UserMerchantAccountResponse { pub merchant_id: id_type::MerchantId, pub merchant_name: OptionalEncryptableName, + pub product_type: Option<common_enums::MerchantProductType>, + pub version: common_enums::ApiVersion, } #[derive(Debug, serde::Serialize)] diff --git a/crates/common_enums/src/enums/accounts.rs b/crates/common_enums/src/enums/accounts.rs index 9a5247512e4..d9c83312d6b 100644 --- a/crates/common_enums/src/enums/accounts.rs +++ b/crates/common_enums/src/enums/accounts.rs @@ -17,9 +17,8 @@ use utoipa::ToSchema; #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MerchantProductType { - Orchestration, #[default] - Legacy, + Orchestration, Vault, Recon, Recovery, diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs index b6b7571d32f..fef000a3954 100644 --- a/crates/hyperswitch_domain_models/src/merchant_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_account.rs @@ -140,6 +140,7 @@ pub struct MerchantAccountSetter { pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: diesel_models::enums::ReconStatus, pub is_platform_account: bool, + pub version: common_enums::ApiVersion, pub product_type: Option<common_enums::MerchantProductType>, } @@ -158,6 +159,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { organization_id, recon_status, is_platform_account, + version, product_type, } = item; Self { @@ -172,6 +174,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { organization_id, recon_status, is_platform_account, + version, product_type, } } @@ -191,6 +194,7 @@ pub struct MerchantAccount { pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: diesel_models::enums::ReconStatus, pub is_platform_account: bool, + pub version: common_enums::ApiVersion, pub product_type: Option<common_enums::MerchantProductType>, } @@ -631,6 +635,7 @@ impl super::behaviour::Conversion for MerchantAccount { organization_id: item.organization_id, recon_status: item.recon_status, is_platform_account: item.is_platform_account, + version: item.version, product_type: item.product_type, }) } diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index d4eb12e39bf..3601f229827 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -1,3 +1,4 @@ +use common_enums; use common_utils::consts::MAX_ALLOWED_MERCHANT_NAME_LENGTH; pub const MAX_NAME_LENGTH: usize = 70; @@ -45,3 +46,7 @@ pub const EMAIL_SUBJECT_RESET_PASSWORD: &str = "Get back to Hyperswitch - Reset pub const EMAIL_SUBJECT_NEW_PROD_INTENT: &str = "New Prod Intent"; pub const EMAIL_SUBJECT_WELCOME_TO_COMMUNITY: &str = "Thank you for signing up on Hyperswitch Dashboard!"; + +pub const DEFAULT_PROFILE_NAME: &str = "default"; +pub const DEFAULT_PRODUCT_TYPE: common_enums::MerchantProductType = + common_enums::MerchantProductType::Orchestration; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index dca58f11329..106c904ef7b 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -673,6 +673,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { organization_id: organization.get_organization_id(), recon_status: diesel_models::enums::ReconStatus::NotRequested, is_platform_account: false, + version: hyperswitch_domain_models::consts::API_VERSION, product_type: self.product_type, }), ) diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 4f19f040bdb..f0a6df94453 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -128,13 +128,62 @@ pub async fn get_user_details( .await .change_context(UserErrors::InternalServerError)?; + let key_manager_state = &(&state).into(); + + let merchant_key_store = state + .store + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &user_from_token.merchant_id, + &state.store.get_master_key().to_vec().into(), + ) + .await; + + let version = if let Ok(merchant_key_store) = merchant_key_store { + let merchant_account = state + .store + .find_merchant_account_by_merchant_id( + key_manager_state, + &user_from_token.merchant_id, + &merchant_key_store, + ) + .await; + + if let Ok(merchant_account) = merchant_account { + merchant_account.version + } else if merchant_account + .as_ref() + .map_err(|e| e.current_context().is_db_not_found()) + .err() + .unwrap_or(false) + { + common_enums::ApiVersion::V2 + } else { + Err(merchant_account + .err() + .map(|e| e.change_context(UserErrors::InternalServerError)) + .unwrap_or(UserErrors::InternalServerError.into()))? + } + } else if merchant_key_store + .as_ref() + .map_err(|e| e.current_context().is_db_not_found()) + .err() + .unwrap_or(false) + { + common_enums::ApiVersion::V2 + } else { + Err(merchant_key_store + .err() + .map(|e| e.change_context(UserErrors::InternalServerError)) + .unwrap_or(UserErrors::InternalServerError.into()))? + }; + let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity( &state, &user_from_token, EntityType::Profile, ) .await?; - Ok(ApplicationResponse::Json( user_api::GetUserDetailsResponse { merchant_id: user_from_token.merchant_id, @@ -149,6 +198,7 @@ pub async fn get_user_details( profile_id: user_from_token.profile_id, entity_type: role_info.get_entity_type(), theme_id: theme.map(|theme| theme.theme_id), + version, }, )) } @@ -1466,9 +1516,9 @@ pub async fn create_org_merchant_for_user( .insert_organization(db_organization) .await .change_context(UserErrors::InternalServerError)?; - + let default_product_type = consts::user::DEFAULT_PRODUCT_TYPE; let merchant_account_create_request = - utils::user::create_merchant_account_request_for_org(req, org)?; + utils::user::create_merchant_account_request_for_org(req, org, default_product_type)?; admin::create_merchant_account(state.clone(), merchant_account_create_request) .await @@ -1482,15 +1532,22 @@ pub async fn create_merchant_account( state: SessionState, user_from_token: auth::UserFromToken, req: user_api::UserMerchantCreate, -) -> UserResponse<()> { +) -> UserResponse<user_api::UserMerchantAccountResponse> { let user_from_db = user_from_token.get_user_from_db(&state).await?; let new_merchant = domain::NewUserMerchant::try_from((user_from_db, req, user_from_token))?; - new_merchant + let domain_merchant_account = new_merchant .create_new_merchant_and_insert_in_db(state.to_owned()) .await?; - Ok(ApplicationResponse::StatusOk) + Ok(ApplicationResponse::Json( + user_api::UserMerchantAccountResponse { + merchant_id: domain_merchant_account.get_id().to_owned(), + merchant_name: domain_merchant_account.merchant_name, + product_type: domain_merchant_account.product_type, + version: domain_merchant_account.version, + }, + )) } pub async fn list_user_roles_details( @@ -2858,7 +2915,7 @@ pub async fn list_orgs_for_user( pub async fn list_merchants_for_user_in_org( state: SessionState, user_from_token: auth::UserFromToken, -) -> UserResponse<Vec<user_api::ListMerchantsForUserInOrgResponse>> { +) -> UserResponse<Vec<user_api::UserMerchantAccountResponse>> { let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, @@ -2917,19 +2974,18 @@ pub async fn list_merchants_for_user_in_org( } }; - if merchant_accounts.is_empty() { - Err(UserErrors::InternalServerError).attach_printable("No merchant found for a user")?; - } + // TODO: Add a check to see if merchant accounts are empty, and handle accordingly, when a single route will be used instead + // of having two separate routes. Ok(ApplicationResponse::Json( merchant_accounts .into_iter() - .map( - |merchant_account| user_api::ListMerchantsForUserInOrgResponse { - merchant_name: merchant_account.merchant_name.clone(), - merchant_id: merchant_account.get_id().to_owned(), - }, - ) + .map(|merchant_account| user_api::UserMerchantAccountResponse { + merchant_name: merchant_account.merchant_name.clone(), + merchant_id: merchant_account.get_id().to_owned(), + product_type: merchant_account.product_type.clone(), + version: merchant_account.version, + }) .collect::<Vec<_>>(), )) } diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 349fb91efc3..fc5e2b94d1c 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -183,6 +183,7 @@ pub fn mk_app( server_app = server_app .service(routes::Organization::server(state.clone())) .service(routes::MerchantAccount::server(state.clone())) + .service(routes::User::server(state.clone())) .service(routes::ApiKeys::server(state.clone())) .service(routes::Routing::server(state.clone())); @@ -195,7 +196,6 @@ pub fn mk_app( .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())) .service(routes::Verify::server(state.clone())) .service(routes::Analytics::server(state.clone())) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 7bb42134aa7..6d687fea2d5 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2091,6 +2091,43 @@ impl Verify { pub struct User; +#[cfg(all(feature = "olap", feature = "v2"))] +impl User { + pub fn server(state: AppState) -> Scope { + let mut route = web::scope("/v2/user").app_data(web::Data::new(state)); + + route = route.service( + web::resource("/create_merchant") + .route(web::post().to(user::user_merchant_account_create)), + ); + route = route.service( + web::scope("/list") + .service( + web::resource("/merchant") + .route(web::get().to(user::list_merchants_for_user_in_org)), + ) + .service( + web::resource("/profile") + .route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)), + ), + ); + + route = route.service( + web::scope("/switch") + .service( + web::resource("/merchant") + .route(web::post().to(user::switch_merchant_for_user_in_org)), + ) + .service( + web::resource("/profile") + .route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)), + ), + ); + + route + } +} + #[cfg(all(feature = "olap", feature = "v1"))] impl User { pub fn server(state: AppState) -> Scope { diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs index 0cdb68ec8d7..6333de5f19b 100644 --- a/crates/router/src/services/authorization/permission_groups.rs +++ b/crates/router/src/services/authorization/permission_groups.rs @@ -180,7 +180,7 @@ pub static USERS: [Resource; 2] = [Resource::User, Resource::Account]; pub static ACCOUNT: [Resource; 3] = [Resource::Account, Resource::ApiKey, Resource::WebhookEvent]; -pub static RECON_OPS: [Resource; 7] = [ +pub static RECON_OPS: [Resource; 8] = [ Resource::ReconToken, Resource::ReconFiles, Resource::ReconUpload, @@ -188,10 +188,12 @@ pub static RECON_OPS: [Resource; 7] = [ Resource::ReconConfig, Resource::ReconAndSettlementAnalytics, Resource::ReconReports, + Resource::Account, ]; -pub static RECON_REPORTS: [Resource; 3] = [ +pub static RECON_REPORTS: [Resource; 4] = [ Resource::ReconToken, Resource::ReconAndSettlementAnalytics, Resource::ReconReports, + Resource::Account, ]; diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index a51ccfdc710..4854d1b4786 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -19,6 +19,7 @@ use diesel_models::{ user_role::{UserRole, UserRoleNew}, }; use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::api::ApplicationResponse; use masking::{ExposeInterface, PeekInterface, Secret}; use once_cell::sync::Lazy; use rand::distributions::{Alphanumeric, DistString}; @@ -37,7 +38,7 @@ use crate::{ db::GlobalStorageInterface, routes::SessionState, services::{self, authentication::UserFromToken}, - types::transformers::ForeignFrom, + types::{domain, transformers::ForeignFrom}, utils::user::password, }; @@ -390,6 +391,7 @@ pub struct NewUserMerchant { merchant_id: id_type::MerchantId, company_name: Option<UserCompanyName>, new_organization: NewUserOrganization, + product_type: Option<common_enums::MerchantProductType>, } impl TryFrom<UserCompanyName> for MerchantName { @@ -414,6 +416,10 @@ impl NewUserMerchant { self.new_organization.clone() } + pub fn get_product_type(&self) -> Option<common_enums::MerchantProductType> { + self.product_type.clone() + } + pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> { if state .store @@ -450,7 +456,7 @@ impl NewUserMerchant { organization_id: self.new_organization.get_organization_id(), metadata: None, merchant_details: None, - product_type: None, + product_type: self.get_product_type(), }) } @@ -477,28 +483,115 @@ impl NewUserMerchant { enable_payment_response_hash: None, redirect_to_merchant_with_http_post: None, pm_collect_link_config: None, - product_type: None, + product_type: self.get_product_type(), }) } + #[cfg(feature = "v1")] pub async fn create_new_merchant_and_insert_in_db( &self, state: SessionState, - ) -> UserResult<()> { + ) -> UserResult<domain::MerchantAccount> { self.check_if_already_exists_in_db(state.clone()).await?; let merchant_account_create_request = self .create_merchant_account_request() .attach_printable("unable to construct merchant account create request")?; - Box::pin(admin::create_merchant_account( - state.clone(), - merchant_account_create_request, + let ApplicationResponse::Json(merchant_account_response) = Box::pin( + admin::create_merchant_account(state.clone(), merchant_account_create_request), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error while creating a merchant")? + else { + return Err(UserErrors::InternalServerError.into()); + }; + + let key_manager_state = &(&state).into(); + let merchant_key_store = state + .store + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &merchant_account_response.merchant_id, + &state.store.get_master_key().to_vec().into(), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to retrieve merchant key store by merchant_id")?; + + let merchant_account = state + .store + .find_merchant_account_by_merchant_id( + key_manager_state, + &merchant_account_response.merchant_id, + &merchant_key_store, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to retrieve merchant account by merchant_id")?; + Ok(merchant_account) + } + + #[cfg(feature = "v2")] + pub async fn create_new_merchant_and_insert_in_db( + &self, + state: SessionState, + ) -> UserResult<domain::MerchantAccount> { + self.check_if_already_exists_in_db(state.clone()).await?; + + let merchant_account_create_request = self + .create_merchant_account_request() + .attach_printable("unable to construct merchant account create request")?; + + let ApplicationResponse::Json(merchant_account_response) = Box::pin( + admin::create_merchant_account(state.clone(), merchant_account_create_request), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error while creating a merchant")? + else { + return Err(UserErrors::InternalServerError.into()); + }; + + let profile_create_request = admin_api::ProfileCreate { + profile_name: consts::user::DEFAULT_PROFILE_NAME.to_string(), + ..Default::default() + }; + + let key_manager_state = &(&state).into(); + let merchant_key_store = state + .store + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &merchant_account_response.id, + &state.store.get_master_key().to_vec().into(), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to retrieve merchant key store by merchant_id")?; + + let merchant_account = state + .store + .find_merchant_account_by_merchant_id( + key_manager_state, + &merchant_account_response.id, + &merchant_key_store, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to retrieve merchant account by merchant_id")?; + + Box::pin(admin::create_profile( + state, + profile_create_request, + merchant_account.clone(), + merchant_key_store, )) .await .change_context(UserErrors::InternalServerError) - .attach_printable("Error while creating a merchant")?; - Ok(()) + .attach_printable("Error while creating a profile")?; + Ok(merchant_account) } } @@ -507,13 +600,13 @@ impl TryFrom<user_api::SignUpRequest> for NewUserMerchant { fn try_from(value: user_api::SignUpRequest) -> UserResult<Self> { let merchant_id = id_type::MerchantId::new_from_unix_timestamp(); - let new_organization = NewUserOrganization::from(value); - + let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE); Ok(Self { company_name: None, merchant_id, new_organization, + product_type, }) } } @@ -524,11 +617,12 @@ impl TryFrom<user_api::ConnectAccountRequest> for NewUserMerchant { fn try_from(value: user_api::ConnectAccountRequest) -> UserResult<Self> { let merchant_id = id_type::MerchantId::new_from_unix_timestamp(); let new_organization = NewUserOrganization::from(value); - + let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE); Ok(Self { company_name: None, merchant_id, new_organization, + product_type, }) } } @@ -539,11 +633,13 @@ impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserMerchant { let company_name = Some(UserCompanyName::new(value.company_name.clone())?); let merchant_id = MerchantId::new(value.company_name.clone())?; let new_organization = NewUserOrganization::try_from(value)?; + let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE); Ok(Self { company_name, merchant_id: id_type::MerchantId::try_from(merchant_id)?, new_organization, + product_type, }) } } @@ -563,6 +659,7 @@ impl TryFrom<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for company_name: None, merchant_id, new_organization, + product_type: None, }) } } @@ -576,6 +673,7 @@ impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUserMerchant { company_name: None, merchant_id, new_organization, + product_type: None, }) } } @@ -588,6 +686,7 @@ impl From<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for Ne company_name: None, merchant_id, new_organization, + product_type: None, } } } @@ -607,6 +706,7 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant { Ok(Self { merchant_id, company_name: Some(UserCompanyName::new(value.1.company_name.clone())?), + product_type: value.1.product_type.clone(), new_organization: NewUserOrganization::from(value), }) } diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index b386185eeca..89612fc1892 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -286,6 +286,7 @@ pub fn is_sso_auth_type(auth_type: UserAuthType) -> bool { pub fn create_merchant_account_request_for_org( req: user_api::UserOrgMerchantCreateRequest, org: organization::Organization, + product_type: common_enums::MerchantProductType, ) -> UserResult<api_models::admin::MerchantAccountCreate> { let merchant_id = if matches!(env::which(), env::Env::Production) { id_type::MerchantId::try_from(domain::MerchantId::new(req.merchant_name.clone().expose())?)? @@ -315,7 +316,7 @@ pub fn create_merchant_account_request_for_org( enable_payment_response_hash: None, redirect_to_merchant_with_http_post: None, pm_collect_link_config: None, - product_type: None, + product_type: Some(product_type), }) }
2025-02-27T06:26:07Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> As part of the modularity effort, we are introducing user support to enable dashboard interactions with v2 merchant accounts. This allows users to create, list, and switch between merchant accounts within their organization. This also allows users to list profiles and switch profiles when using v2 merchant accounts. ## Key Changes ### 1. User Support for v2 Merchant Accounts Introduced APIs to facilitate user interactions with v2 merchant accounts: - **Create Merchant Account API (v1 & v2)**: Allows users to create a merchant account. - **List Merchant Accounts API**: Retrieves all v2 merchant accounts associated with a user in an organization. - **Switch Merchant Account API**: Enables users to switch to a different v2 merchant account. ### 2. Modified Response Structure - The response for **Create Merchant Account (v1 & v2)** now returns an object instead of just `StatusOk (200)`. The response object includes: - `merchant_id` - `merchant_name` - `product_type` - `version` - The **List Merchant Accounts API** now returns a vector of these objects instead of a raw list. ### 3. Request Structure Update - The **Create Merchant Account API** request now includes an optional `product_type` field. - This field is currently optional but will be made mandatory once both the frontend and backend are stabilized. ### 4. Recon - Added **Merchant Account** permission for Recon related activities. ### 5. User Support for v2 Profiles Introduced APIs to facilitate user interactions with v2 profiles: - **List Profiles API**: Retrieves all v2 profiles associated with a user in a merchant. - **Switch Profile API**: Enables users to switch to a different v2 profile in the merchant. ### 6. Modified get_user_details API: - Modified **get_user_details API** response type to return the version as well, enabling FE to have more context while trying to fetch the merchant account 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 <!-- 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). --> With the modularization of the payments solution, managing multiple merchant accounts becomes essential. This update ensures a seamless user experience for handling v1 and v2 merchant accounts and profiles within an organization. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> The flow looks like this: - Sign Up / Sign In through V1 merchant account --> Create Merchant Account (V1 or V2) --> List Merchant Accounts (V1 and V2)--> Switch Merchant Account (V1 and V2) ### Testing V2 Flow: Sign In to a V1 merchant account #### Create v2 Merchant Account: ```bash curl --location 'http://localhost:8000/v2/user/create_merchant' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWI5ZGZjNWUtZjA2My00YWY3LThkNzUtYmFmOTgzZmU0ODE4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF92S09zQU9odGc2S3hpSldlR3Y2YiIsInJvbGVfaWQiOiJvcmdfYWRtaW4iLCJleHAiOjE3NDE3NTk2MjUsIm9yZ19pZCI6Im9yZ19kUENaYU51bmNaRDY5aVZXb0hKcyIsInByb2ZpbGVfaWQiOiJwcm9fQjV4UWZxUWE4dkNCaXpoc2FnTmkiLCJ0ZW5hbnRfaWQiOiJwdWJsaWMifQ.MMJ68FinbhA4dShNvbrOsofU_nTaw1MjGnUrEkmkeOk' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWI5ZGZjNWUtZjA2My00YWY3LThkNzUtYmFmOTgzZmU0ODE4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF92S09zQU9odGc2S3hpSldlR3Y2YiIsInJvbGVfaWQiOiJvcmdfYWRtaW4iLCJleHAiOjE3NDE3NTk2MjUsIm9yZ19pZCI6Im9yZ19kUENaYU51bmNaRDY5aVZXb0hKcyIsInByb2ZpbGVfaWQiOiJwcm9fQjV4UWZxUWE4dkNCaXpoc2FnTmkiLCJ0ZW5hbnRfaWQiOiJwdWJsaWMifQ.MMJ68FinbhA4dShNvbrOsofU_nTaw1MjGnUrEkmkeOk' \ --data '{ "company_name": "TestingMerchantAccountCreateV2", "product_type": "vault" } ' ``` Sample Output: ```json { "merchant_id": "testingmerchantaccountcreatev2_Ku5OxNIapqaot1P8rlQr", "merchant_name": "TestingMerchantAccountCreateV2", "product_type": "vault", "version": "v2" } ``` #### List V2 Merchant Accounts for User in Org: ```bash curl --location 'http://localhost:8000/v2/user/list/merchant' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWI5ZGZjNWUtZjA2My00YWY3LThkNzUtYmFmOTgzZmU0ODE4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF92S09zQU9odGc2S3hpSldlR3Y2YiIsInJvbGVfaWQiOiJvcmdfYWRtaW4iLCJleHAiOjE3NDE3NTk2MjUsIm9yZ19pZCI6Im9yZ19kUENaYU51bmNaRDY5aVZXb0hKcyIsInByb2ZpbGVfaWQiOiJwcm9fQjV4UWZxUWE4dkNCaXpoc2FnTmkiLCJ0ZW5hbnRfaWQiOiJwdWJsaWMifQ.MMJ68FinbhA4dShNvbrOsofU_nTaw1MjGnUrEkmkeOk' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWI5ZGZjNWUtZjA2My00YWY3LThkNzUtYmFmOTgzZmU0ODE4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF92S09zQU9odGc2S3hpSldlR3Y2YiIsInJvbGVfaWQiOiJvcmdfYWRtaW4iLCJleHAiOjE3NDE3NTk2MjUsIm9yZ19pZCI6Im9yZ19kUENaYU51bmNaRDY5aVZXb0hKcyIsInByb2ZpbGVfaWQiOiJwcm9fQjV4UWZxUWE4dkNCaXpoc2FnTmkiLCJ0ZW5hbnRfaWQiOiJwdWJsaWMifQ.MMJ68FinbhA4dShNvbrOsofU_nTaw1MjGnUrEkmkeOk' ``` Sample Output: ```json [ { "merchant_id": "merchant_vKOsAOhtg6KxiJWeGv6b", "merchant_name": "merchant", "product_type": "orchestration", "version": "v2" }, { "merchant_id": "testingmerchantaccountcreatev2_Ku5OxNIapqaot1P8rlQr", "merchant_name": "TestingMerchantAccountCreateV2", "product_type": "vault", "version": "v2" } ] ``` #### Switch to V2 merchant Account: ```bash curl --location 'http://localhost:8000/v2/user/switch/merchant' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWI5ZGZjNWUtZjA2My00YWY3LThkNzUtYmFmOTgzZmU0ODE4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF92S09zQU9odGc2S3hpSldlR3Y2YiIsInJvbGVfaWQiOiJvcmdfYWRtaW4iLCJleHAiOjE3NDE3NTk2MjUsIm9yZ19pZCI6Im9yZ19kUENaYU51bmNaRDY5aVZXb0hKcyIsInByb2ZpbGVfaWQiOiJwcm9fQjV4UWZxUWE4dkNCaXpoc2FnTmkiLCJ0ZW5hbnRfaWQiOiJwdWJsaWMifQ.MMJ68FinbhA4dShNvbrOsofU_nTaw1MjGnUrEkmkeOk' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWI5ZGZjNWUtZjA2My00YWY3LThkNzUtYmFmOTgzZmU0ODE4IiwibWVyY2hhbnRfaWQiOiJ0ZXN0aW5nbWVyY2hhbnRhY2NvdW50Y3JlYXRldjJfS3U1T3hOSWFwcWFvdDFQOHJsUXIiLCJyb2xlX2lkIjoib3JnX2FkbWluIiwiZXhwIjoxNzQxNzU5NzYyLCJvcmdfaWQiOiJvcmdfZFBDWmFOdW5jWkQ2OWlWV29ISnMiLCJwcm9maWxlX2lkIjoicHJvX2huN2RqaVpKckJTMnYxS1hjdWIxIiwidGVuYW50X2lkIjoicHVibGljIn0.kxj8dXx4KBXRl-Ayfy6qVJxZF5hLvwqxouJ2ENubm8Q' \ --data '{ "merchant_id": "testingmerchantaccountcreatev2_Ku5OxNIapqaot1P8rlQr" }' ``` Sample Output: ```json { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWI5ZGZjNWUtZjA2My00YWY3LThkNzUtYmFmOTgzZmU0ODE4IiwibWVyY2hhbnRfaWQiOiJ0ZXN0aW5nbWVyY2hhbnRhY2NvdW50Y3JlYXRldjJfS3U1T3hOSWFwcWFvdDFQOHJsUXIiLCJyb2xlX2lkIjoib3JnX2FkbWluIiwiZXhwIjoxNzQxNzU5NzYyLCJvcmdfaWQiOiJvcmdfZFBDWmFOdW5jWkQ2OWlWV29ISnMiLCJwcm9maWxlX2lkIjoicHJvX2huN2RqaVpKckJTMnYxS1hjdWIxIiwidGVuYW50X2lkIjoicHVibGljIn0.kxj8dXx4KBXRl-Ayfy6qVJxZF5hLvwqxouJ2ENubm8Q", "token_type": "user_info" } ``` #### Switch to V2 Profile: ```bash curl --location 'http://localhost:8000/v2/user/switch/profile' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNzhjMjBkNzQtN2FkYy00NmE5LWEzN2UtNGFhOWMzOWE0ZDY4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF9DaGxVcVNSakNyc1pQMTI3VmVUeCIsInJvbGVfaWQiOiJvcmdfYWRtaW4iLCJleHAiOjE3NDE4NjIxOTQsIm9yZ19pZCI6Im9yZ19VSWlNWFBvVFRsZVBXOElRU2V3MyIsInByb2ZpbGVfaWQiOiJwcm9fZnhHdTBKZm1mbUVmQVEwUGpiY1ciLCJ0ZW5hbnRfaWQiOiJwdWJsaWMifQ.8QVJGDmL-ybeQ8Rx8On_ACt7_GsFQVkE8-jZtT9fNXg' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNzhjMjBkNzQtN2FkYy00NmE5LWEzN2UtNGFhOWMzOWE0ZDY4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF9DaGxVcVNSakNyc1pQMTI3VmVUeCIsInJvbGVfaWQiOiJvcmdfYWRtaW4iLCJleHAiOjE3NDE4NjIzODYsIm9yZ19pZCI6Im9yZ19VSWlNWFBvVFRsZVBXOElRU2V3MyIsInByb2ZpbGVfaWQiOiJwcm9fVWpKWUpGektSaGtvUmlZVHU4ckMiLCJ0ZW5hbnRfaWQiOiJwdWJsaWMifQ.Yo6_JeAN1fv6GTqFZJWpvsNfm3BhxqPOjP2KRYNMH-A' \ --data '{ "profile_id": "pro_UjJYJFzKRhkoRiYTu8rC" }' ``` Sample Output: ```json { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNzhjMjBkNzQtN2FkYy00NmE5LWEzN2UtNGFhOWMzOWE0ZDY4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF9DaGxVcVNSakNyc1pQMTI3VmVUeCIsInJvbGVfaWQiOiJvcmdfYWRtaW4iLCJleHAiOjE3NDE4NjIzODYsIm9yZ19pZCI6Im9yZ19VSWlNWFBvVFRsZVBXOElRU2V3MyIsInByb2ZpbGVfaWQiOiJwcm9fVWpKWUpGektSaGtvUmlZVHU4ckMiLCJ0ZW5hbnRfaWQiOiJwdWJsaWMifQ.Yo6_JeAN1fv6GTqFZJWpvsNfm3BhxqPOjP2KRYNMH-A", "token_type": "user_info" } ``` #### List V2 Profile for a v2 merchant account: ```bash curl --location 'http://localhost:8000/v2/user/list/profile' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNzhjMjBkNzQtN2FkYy00NmE5LWEzN2UtNGFhOWMzOWE0ZDY4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF9DaGxVcVNSakNyc1pQMTI3VmVUeCIsInJvbGVfaWQiOiJvcmdfYWRtaW4iLCJleHAiOjE3NDE4NjIxOTQsIm9yZ19pZCI6Im9yZ19VSWlNWFBvVFRsZVBXOElRU2V3MyIsInByb2ZpbGVfaWQiOiJwcm9fZnhHdTBKZm1mbUVmQVEwUGpiY1ciLCJ0ZW5hbnRfaWQiOiJwdWJsaWMifQ.8QVJGDmL-ybeQ8Rx8On_ACt7_GsFQVkE8-jZtT9fNXg' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNzhjMjBkNzQtN2FkYy00NmE5LWEzN2UtNGFhOWMzOWE0ZDY4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF9DaGxVcVNSakNyc1pQMTI3VmVUeCIsInJvbGVfaWQiOiJvcmdfYWRtaW4iLCJleHAiOjE3NDE4NjIxOTQsIm9yZ19pZCI6Im9yZ19VSWlNWFBvVFRsZVBXOElRU2V3MyIsInByb2ZpbGVfaWQiOiJwcm9fZnhHdTBKZm1mbUVmQVEwUGpiY1ciLCJ0ZW5hbnRfaWQiOiJwdWJsaWMifQ.8QVJGDmL-ybeQ8Rx8On_ACt7_GsFQVkE8-jZtT9fNXg' ``` Sample Output: ```json [ { "profile_id": "pro_UjJYJFzKRhkoRiYTu8rC", "profile_name": "TestingV4-Profile" }, { "profile_id": "pro_fxGu0JfmfmEfAQ0PjbcW", "profile_name": "default" } ] ``` ### Testing V1 flow: Sign in to V1 merchant account #### Create V1 merchant Account: ```bash curl --location 'http://localhost:8080/user/create_merchant' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTk0OTE4YzUtOTM0OS00YjEzLWIzZDItZDc0Mzg0OTk3MWNkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxNTg4NTI2Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTc2MTM0OCwib3JnX2lkIjoib3JnX3NYdWNFTGFKSURtVFU2YVlsbmJZIiwicHJvZmlsZV9pZCI6InByb184QnNld0tIRUlaa3ppdUhKa282YiIsInRlbmFudF9pZCI6InB1YmxpYyJ9.lyeIOXMCXVdDaE7ACHxzoFgAZeCY0rjDRFq1rSxu1NE' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTk0OTE4YzUtOTM0OS00YjEzLWIzZDItZDc0Mzg0OTk3MWNkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxNTg4NTI2Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTc2MTM0OCwib3JnX2lkIjoib3JnX3NYdWNFTGFKSURtVFU2YVlsbmJZIiwicHJvZmlsZV9pZCI6InByb184QnNld0tIRUlaa3ppdUhKa282YiIsInRlbmFudF9pZCI6InB1YmxpYyJ9.lyeIOXMCXVdDaE7ACHxzoFgAZeCY0rjDRFq1rSxu1NE' \ --data '{ "company_name": "TestingV1", "product_type": "recovery" }' ``` Sample Output: ```json { "merchant_id": "merchant_1741588579", "merchant_name": "TestingV1", "product_type": "recovery", "version": "v1" } ``` #### List V1 Merchant Accounts for User in Org: ```bash curl --location 'http://localhost:8080/user/list/merchant' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTk0OTE4YzUtOTM0OS00YjEzLWIzZDItZDc0Mzg0OTk3MWNkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxNTg4NTI2Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTc2MTM0OCwib3JnX2lkIjoib3JnX3NYdWNFTGFKSURtVFU2YVlsbmJZIiwicHJvZmlsZV9pZCI6InByb184QnNld0tIRUlaa3ppdUhKa282YiIsInRlbmFudF9pZCI6InB1YmxpYyJ9.lyeIOXMCXVdDaE7ACHxzoFgAZeCY0rjDRFq1rSxu1NE' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTk0OTE4YzUtOTM0OS00YjEzLWIzZDItZDc0Mzg0OTk3MWNkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxNTg4NTI2Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTc2MTM0OCwib3JnX2lkIjoib3JnX3NYdWNFTGFKSURtVFU2YVlsbmJZIiwicHJvZmlsZV9pZCI6InByb184QnNld0tIRUlaa3ppdUhKa282YiIsInRlbmFudF9pZCI6InB1YmxpYyJ9.lyeIOXMCXVdDaE7ACHxzoFgAZeCY0rjDRFq1rSxu1NE' ``` Sample Output: ```json [ { "merchant_id": "merchant_1741588526", "merchant_name": null, "product_type": "orchestration", "version": "v1" }, { "merchant_id": "merchant_1741588579", "merchant_name": "TestingV1", "product_type": "recovery", "version": "v1" } ] ``` #### Switch to V1 Merchant Account: ```bash curl --location 'http://localhost:8080/user/switch/merchant' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTk0OTE4YzUtOTM0OS00YjEzLWIzZDItZDc0Mzg0OTk3MWNkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxNTg4NTI2Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTc2MTM0OCwib3JnX2lkIjoib3JnX3NYdWNFTGFKSURtVFU2YVlsbmJZIiwicHJvZmlsZV9pZCI6InByb184QnNld0tIRUlaa3ppdUhKa282YiIsInRlbmFudF9pZCI6InB1YmxpYyJ9.lyeIOXMCXVdDaE7ACHxzoFgAZeCY0rjDRFq1rSxu1NE' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTk0OTE4YzUtOTM0OS00YjEzLWIzZDItZDc0Mzg0OTk3MWNkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxNTg4NTc5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTc2MTUwNSwib3JnX2lkIjoib3JnX3NYdWNFTGFKSURtVFU2YVlsbmJZIiwicHJvZmlsZV9pZCI6InByb19PVnQ0OTIzYmdoS0dVRU13Y1JiOSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.5yi6unFpacer1FO_wcxxQIHRls_mjDjPraIHD6BO0ME' \ --data '{ "merchant_id": "merchant_1741588579" }' ``` Sample Output: ```json { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTk0OTE4YzUtOTM0OS00YjEzLWIzZDItZDc0Mzg0OTk3MWNkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxNTg4NTc5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTc2MTUwNSwib3JnX2lkIjoib3JnX3NYdWNFTGFKSURtVFU2YVlsbmJZIiwicHJvZmlsZV9pZCI6InByb19PVnQ0OTIzYmdoS0dVRU13Y1JiOSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.5yi6unFpacer1FO_wcxxQIHRls_mjDjPraIHD6BO0ME", "token_type": "user_info" } ``` #### get_user_details ```bash curl --location 'https://integ-api.hyperswitch.io/user' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMTlmN2IzZjctMmEwOS00NTllLTllNGItZTRlODcwZDMwMjEwIiwibWVyY2hhbnRfaWQiOiJ0ZXN0Zmxvd3YyX1pMNmV3aFBiZUhIMWU5dmlVc2JoIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTk0MzQ0Miwib3JnX2lkIjoib3JnX3MzUGVzYTQxRk1aNng3VVJOT0RPIiwicHJvZmlsZV9pZCI6InByb19zbjVFTFV0eGpFSnphN0dnYzhmRCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.EbmlEihGnAM_DW08BAyyeDHFZlBWmCm8Q0bRlAPnEfM' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMTlmN2IzZjctMmEwOS00NTllLTllNGItZTRlODcwZDMwMjEwIiwibWVyY2hhbnRfaWQiOiJ0ZXN0Zmxvd3YyX1pMNmV3aFBiZUhIMWU5dmlVc2JoIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTk0MzQ0Miwib3JnX2lkIjoib3JnX3MzUGVzYTQxRk1aNng3VVJOT0RPIiwicHJvZmlsZV9pZCI6InByb19zbjVFTFV0eGpFSnphN0dnYzhmRCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.EbmlEihGnAM_DW08BAyyeDHFZlBWmCm8Q0bRlAPnEfM' ``` Sample Output: ```json { "merchant_id": "testflowv2_ZL6ewhPbeHH1e9viUsbh", "name": "sandeep.kumar", "email": "[email protected]", "verification_days_left": null, "role_id": "org_admin", "org_id": "org_s3Pesa41FMZ6x7URNODO", "is_two_factor_auth_setup": false, "recovery_codes_left": null, "profile_id": "pro_sn5ELUtxjEJza7Ggc8fD", "entity_type": "organization", "theme_id": null, "version": "v2" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
e9496007889350f78af5875566c806f79c397544
e9496007889350f78af5875566c806f79c397544
juspay/hyperswitch
juspay__hyperswitch-7379
Bug: [REFACTOR] Multiple SDK queries fixed Multiple SDK queries fixed: Modified field_type text to some unique enum Corrected multiple required fields Voucher payments error billing.phone.number is required fixed Cashapp and Swish payment_experience fixed.
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 6ae46a5ede0..c2a1261508a 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -232,6 +232,7 @@ pub enum FieldType { UserShippingAddressPincode, UserShippingAddressState, UserShippingAddressCountry { options: Vec<String> }, + UserSocialSecurityNumber, UserBlikCode, UserBank, UserBankAccountNumber, diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs index ed3319816d5..63c7d99ee17 100644 --- a/crates/connector_configs/src/transformer.rs +++ b/crates/connector_configs/src/transformer.rs @@ -66,6 +66,9 @@ impl DashboardRequestPayload { (_, PaymentMethodType::DirectCarrierBilling) => { Some(api_models::enums::PaymentExperience::CollectOtp) } + (_, PaymentMethodType::Cashapp) | (_, PaymentMethodType::Swish) => { + Some(api_models::enums::PaymentExperience::DisplayQrCode) + } _ => Some(api_models::enums::PaymentExperience::RedirectToUrl), }, } diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index b63c4eea2a1..6c3ba6982b3 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -189,6 +189,7 @@ merchant_secret="Source verification key" payment_method_type = "momo" [[adyen.wallet]] payment_method_type = "swish" + payment_experience = "display_qr_code" [[adyen.wallet]] payment_method_type = "touch_n_go" [[adyen.voucher]] @@ -3297,6 +3298,7 @@ merchant_secret="Source verification key" payment_method_type = "ali_pay" [[stripe.wallet]] payment_method_type = "cashapp" + payment_experience = "display_qr_code" is_verifiable = true [stripe.connector_auth.HeaderKey] api_key="Secret Key" diff --git a/crates/hyperswitch_domain_models/src/address.rs b/crates/hyperswitch_domain_models/src/address.rs index c9beb359c43..f8e38ae8a35 100644 --- a/crates/hyperswitch_domain_models/src/address.rs +++ b/crates/hyperswitch_domain_models/src/address.rs @@ -23,10 +23,18 @@ impl Address { .email .clone() .or(other.and_then(|other| other.email.clone())), - phone: self - .phone - .clone() - .or(other.and_then(|other| other.phone.clone())), + phone: { + self.phone + .clone() + .and_then(|phone_details| { + if phone_details.number.is_some() { + Some(phone_details) + } else { + None + } + }) + .or_else(|| other.and_then(|other| other.phone.clone())) + }, } } } diff --git a/crates/router/src/configs/defaults/payment_connector_required_fields.rs b/crates/router/src/configs/defaults/payment_connector_required_fields.rs index 3849054045c..89058884c9d 100644 --- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs +++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs @@ -3566,9 +3566,9 @@ impl Default for settings::RequiredFields { } ), ( - "payment_method_data.billing.phone.number".to_string(), + "billing.phone.number".to_string(), RequiredFieldInfo { - required_field: "billing.phone.number".to_string(), + required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, @@ -7072,9 +7072,9 @@ impl Default for settings::RequiredFields { } ), ( - "payment_method_data.billing.phone.number".to_string(), + "billing.phone.number".to_string(), RequiredFieldInfo { - required_field: "billing.phone.number".to_string(), + required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, @@ -9850,9 +9850,9 @@ impl Default for settings::RequiredFields { common: HashMap::new(), non_mandate: HashMap::from([ ( - "payment_method_data.billing.phone.number".to_string(), + "billing.phone.number".to_string(), RequiredFieldInfo { - required_field: "billing.phone.number".to_string(), + required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, @@ -11195,7 +11195,7 @@ impl Default for settings::RequiredFields { } ), ( - "payment_method_data.billing.phone.number".to_string(), + "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone_number".to_string(), @@ -11425,9 +11425,9 @@ impl Default for settings::RequiredFields { } ), ( - "payment_method_data.billing.phone.number".to_string(), + "billing.phone.number".to_string(), RequiredFieldInfo { - required_field: "billing.phone.number".to_string(), + required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, @@ -11547,9 +11547,9 @@ impl Default for settings::RequiredFields { } ), ( - "payment_method_data.billing.phone.number".to_string(), + "billing.phone.number".to_string(), RequiredFieldInfo { - required_field: "billing.phone.number".to_string(), + required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, @@ -11675,7 +11675,7 @@ impl Default for settings::RequiredFields { RequiredFieldInfo { required_field: "payment_method_data.voucher.boleto.social_security_number".to_string(), display_name: "social_security_number".to_string(), - field_type: enums::FieldType::Text, + field_type: enums::FieldType::UserSocialSecurityNumber, value: None, } ), @@ -13299,7 +13299,7 @@ impl Default for settings::RequiredFields { ( "payment_method_data.gift_card.number".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.gift_card.number".to_string(), + required_field: "payment_method_data.gift_card.givex.number".to_string(), display_name: "gift_card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, @@ -13308,7 +13308,7 @@ impl Default for settings::RequiredFields { ( "payment_method_data.gift_card.cvc".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.gift_card.cvc".to_string(), + required_field: "payment_method_data.gift_card.givex.cvc".to_string(), display_name: "gift_card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index d072463020a..05fd1c4d5e0 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -4557,8 +4557,10 @@ where (router_data, should_continue_payment) } } - Some(domain::PaymentMethodData::GiftCard(_)) => { - if connector.connector_name == router_types::Connector::Adyen { + Some(domain::PaymentMethodData::GiftCard(gift_card_data)) => { + if connector.connector_name == router_types::Connector::Adyen + && matches!(gift_card_data.deref(), domain::GiftCardData::Givex(..)) + { router_data = router_data.preprocessing_steps(state, connector).await?; let is_error_in_response = router_data.response.is_err();
2025-02-26T07:27:49Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Multiple SDK queries fixed: 1. Modified field_type text to some unique enum 2. Corrected multiple required fields 3. Voucher payments error billing.phone.number is required fixed 4. Cashapp and Swish payment_experience fixed. 5. Preprocessing to be done only for Givex in gift_cards ### 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)? --> Voucher payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_7u1WfwhlOfuf9PlZpwf54Ejwwi7d6cEBn51jXQiQXBzoQEY4C0CMB8ddkJ6ES0GZ' \ --data-raw '{ "amount": 1000, "currency": "JPY", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "voucher", "payment_method_type": "seven_eleven", "payment_method_data": { "voucher": { "seven_eleven": {} }, "billing": { "address": { "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "" }, "email": "[email protected]" } } }' ``` Response ``` { "payment_id": "pay_uoGRFxEqHLGs9mJHh4gs", "merchant_id": "merchant_1740480565", "status": "requires_customer_action", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "adyen", "client_secret": "pay_uoGRFxEqHLGs9mJHh4gs_secret_iWcNQpBKiRXtrJE3Ywei", "created": "2025-02-25T16:02:51.611Z", "currency": "JPY", "customer_id": null, "customer": { "id": null, "name": null, "email": null, "phone": null, "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": "voucher", "payment_method_data": { "voucher": { "seven_eleven": { "first_name": null, "last_name": null, "email": null, "phone_number": null } }, "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "" }, "email": "[email protected]" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.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_uoGRFxEqHLGs9mJHh4gs/merchant_1740480565/pay_uoGRFxEqHLGs9mJHh4gs_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "seven_eleven", "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": "XZ6J6GDVKX2R3M75", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "XZ6J6GDVKX2R3M75", "payment_link": null, "profile_id": "pro_XQL7oWxF1wAf4kznf1Ti", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_uzopYnVyxTBm7bzDBhJI", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-02-25T16:17:51.611Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-02-25T16:02:56.270Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null } ``` Other refactoring is related to SDK and Dashboard WASM, so no need to test. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
a5f898f915a79c52fa2033f8f3f7ee043b83e5e4
a5f898f915a79c52fa2033f8f3f7ee043b83e5e4
juspay/hyperswitch
juspay__hyperswitch-7362
Bug: chore: resolve v2 warnings in common_utils Resolve all v2 warnings in common_utils crate.
diff --git a/crates/common_utils/src/id_type/global_id.rs b/crates/common_utils/src/id_type/global_id.rs index 1e376dfe4de..bb296d7ef1a 100644 --- a/crates/common_utils/src/id_type/global_id.rs +++ b/crates/common_utils/src/id_type/global_id.rs @@ -134,7 +134,7 @@ impl GlobalId { ) -> Result<Self, GlobalIdError> { let length_id = LengthId::from(input_string)?; let input_string = &length_id.0 .0; - let (cell_id, remaining) = input_string + let (cell_id, _remaining) = input_string .split_once("_") .ok_or(GlobalIdError::InvalidIdFormat)?; diff --git a/crates/common_utils/src/id_type/global_id/customer.rs b/crates/common_utils/src/id_type/global_id/customer.rs index e0de91d8aed..014d56c9aad 100644 --- a/crates/common_utils/src/id_type/global_id/customer.rs +++ b/crates/common_utils/src/id_type/global_id/customer.rs @@ -1,6 +1,4 @@ -use error_stack::ResultExt; - -use crate::{errors, generate_id_with_default_len, generate_time_ordered_id_without_prefix, types}; +use crate::errors; crate::global_id_type!( GlobalCustomerId, @@ -29,7 +27,7 @@ impl GlobalCustomerId { } impl TryFrom<GlobalCustomerId> for crate::id_type::CustomerId { - type Error = error_stack::Report<crate::errors::ValidationError>; + type Error = error_stack::Report<errors::ValidationError>; fn try_from(value: GlobalCustomerId) -> Result<Self, Self::Error> { Self::try_from(std::borrow::Cow::from(value.get_string_repr().to_owned())) diff --git a/crates/common_utils/src/id_type/global_id/payment.rs b/crates/common_utils/src/id_type/global_id/payment.rs index e43e33c619a..94ffbed57af 100644 --- a/crates/common_utils/src/id_type/global_id/payment.rs +++ b/crates/common_utils/src/id_type/global_id/payment.rs @@ -1,7 +1,7 @@ use common_enums::enums; use error_stack::ResultExt; -use crate::{errors, generate_id_with_default_len, generate_time_ordered_id_without_prefix, types}; +use crate::errors; crate::global_id_type!( GlobalPaymentId, @@ -42,7 +42,6 @@ impl GlobalPaymentId { impl TryFrom<std::borrow::Cow<'static, str>> for GlobalPaymentId { type Error = error_stack::Report<errors::ValidationError>; fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> { - use error_stack::ResultExt; let merchant_ref_id = super::GlobalId::from_string(value).change_context( errors::ValidationError::IncorrectValueProvided { field_name: "payment_id", @@ -86,7 +85,6 @@ impl GlobalAttemptId { impl TryFrom<std::borrow::Cow<'static, str>> for GlobalAttemptId { type Error = error_stack::Report<errors::ValidationError>; fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> { - use error_stack::ResultExt; let global_attempt_id = super::GlobalId::from_string(value).change_context( errors::ValidationError::IncorrectValueProvided { field_name: "payment_id", diff --git a/crates/common_utils/src/id_type/global_id/refunds.rs b/crates/common_utils/src/id_type/global_id/refunds.rs index 0aac9bf5808..eb8dad6b3aa 100644 --- a/crates/common_utils/src/id_type/global_id/refunds.rs +++ b/crates/common_utils/src/id_type/global_id/refunds.rs @@ -1,6 +1,6 @@ use error_stack::ResultExt; -use crate::{errors, generate_id_with_default_len, generate_time_ordered_id_without_prefix, types}; +use crate::errors; /// A global id that can be used to identify a refund #[derive( @@ -36,7 +36,6 @@ impl GlobalRefundId { impl TryFrom<std::borrow::Cow<'static, str>> for GlobalRefundId { type Error = error_stack::Report<errors::ValidationError>; fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> { - use error_stack::ResultExt; let merchant_ref_id = super::GlobalId::from_string(value).change_context( errors::ValidationError::IncorrectValueProvided { field_name: "refund_id",
2025-02-24T09:50:06Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR resolves the v2 warnings generated in common_utils. ### 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 sanity of common_utils on both v1 and v2 ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
eabef328c665cfbaf953a5eb15bd15484c62dcf7
eabef328c665cfbaf953a5eb15bd15484c62dcf7
juspay/hyperswitch
juspay__hyperswitch-7354
Bug: chore: resolve v2 warnings in api_models Resolve all v2 warnings in api_models crate.
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index ae66147b104..ffbbdeb351e 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -14,7 +14,6 @@ use common_utils::{crypto::OptionalEncryptableName, ext_traits::ValueExt}; use masking::ExposeInterface; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; -use url; use utoipa::ToSchema; use super::payments::AddressDetails; diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index a6b2c53d282..76d1201c2e7 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -5,34 +5,28 @@ use super::{ PaymentStartRedirectionRequest, PaymentsCreateIntentRequest, PaymentsGetIntentRequest, PaymentsIntentResponse, PaymentsRequest, }; -#[cfg(all( - any(feature = "v2", feature = "v1"), - not(feature = "payment_methods_v2") -))] -use crate::payment_methods::CustomerPaymentMethodsListResponse; #[cfg(feature = "v1")] -use crate::payments::{PaymentListFilterConstraints, PaymentListResponseV2}; -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -use crate::{events, payment_methods::CustomerPaymentMethodsListResponse}; +use crate::payments::{ + ExtendedCardInfoResponse, PaymentIdType, PaymentListFilterConstraints, PaymentListResponseV2, + PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest, + PaymentsCompleteAuthorizeRequest, PaymentsDynamicTaxCalculationRequest, + PaymentsDynamicTaxCalculationResponse, PaymentsExternalAuthenticationRequest, + PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest, + PaymentsManualUpdateRequest, PaymentsManualUpdateResponse, PaymentsPostSessionTokensRequest, + PaymentsPostSessionTokensResponse, PaymentsRejectRequest, PaymentsRetrieveRequest, + PaymentsStartRequest, PaymentsUpdateMetadataRequest, PaymentsUpdateMetadataResponse, +}; use crate::{ payment_methods::{ self, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse, PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, - PaymentMethodCollectLinkResponse, PaymentMethodDeleteResponse, PaymentMethodListRequest, - PaymentMethodListResponse, PaymentMethodMigrateResponse, PaymentMethodResponse, - PaymentMethodUpdate, + PaymentMethodCollectLinkResponse, PaymentMethodListRequest, PaymentMethodListResponse, + PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodUpdate, }, payments::{ - self, ExtendedCardInfoResponse, PaymentIdType, PaymentListConstraints, PaymentListFilters, - PaymentListFiltersV2, PaymentListResponse, PaymentsAggregateResponse, - PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest, - PaymentsCompleteAuthorizeRequest, PaymentsDynamicTaxCalculationRequest, - PaymentsDynamicTaxCalculationResponse, PaymentsExternalAuthenticationRequest, - PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest, - PaymentsManualUpdateRequest, PaymentsManualUpdateResponse, - PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse, PaymentsRejectRequest, - PaymentsRetrieveRequest, PaymentsSessionResponse, PaymentsStartRequest, - PaymentsUpdateMetadataRequest, PaymentsUpdateMetadataResponse, RedirectionResponse, + self, PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2, + PaymentListResponse, PaymentsAggregateResponse, PaymentsSessionResponse, + RedirectionResponse, }, }; @@ -272,7 +266,7 @@ impl ApiEventMetric for payment_methods::DefaultPaymentMethod { } #[cfg(feature = "v2")] -impl ApiEventMetric for PaymentMethodDeleteResponse { +impl ApiEventMetric for payment_methods::PaymentMethodDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.id.clone(), @@ -283,7 +277,7 @@ impl ApiEventMetric for PaymentMethodDeleteResponse { } #[cfg(feature = "v1")] -impl ApiEventMetric for PaymentMethodDeleteResponse { +impl ApiEventMetric for payment_methods::PaymentMethodDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_id.clone(), @@ -293,7 +287,7 @@ impl ApiEventMetric for PaymentMethodDeleteResponse { } } -impl ApiEventMetric for CustomerPaymentMethodsListResponse {} +impl ApiEventMetric for payment_methods::CustomerPaymentMethodsListResponse {} impl ApiEventMetric for PaymentMethodListRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/api_models/src/events/refund.rs b/crates/api_models/src/events/refund.rs index 888918d836e..14e1984a760 100644 --- a/crates/api_models/src/events/refund.rs +++ b/crates/api_models/src/events/refund.rs @@ -1,13 +1,12 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; +use crate::refunds::{ + self, RefundAggregateResponse, RefundListFilters, RefundListMetaData, RefundListRequest, + RefundListResponse, +}; #[cfg(feature = "v1")] -use crate::refunds::RefundRequest; -#[cfg(feature = "v2")] -use crate::refunds::RefundsCreateRequest; use crate::refunds::{ - RefundAggregateResponse, RefundListFilters, RefundListMetaData, RefundListRequest, - RefundListResponse, RefundManualUpdateRequest, RefundResponse, RefundUpdateRequest, - RefundsRetrieveRequest, + RefundManualUpdateRequest, RefundRequest, RefundUpdateRequest, RefundsRetrieveRequest, }; #[cfg(feature = "v1")] @@ -24,14 +23,14 @@ impl ApiEventMetric for RefundRequest { } #[cfg(feature = "v2")] -impl ApiEventMetric for RefundsCreateRequest { +impl ApiEventMetric for refunds::RefundsCreateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v1")] -impl ApiEventMetric for RefundResponse { +impl ApiEventMetric for refunds::RefundResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Refund { payment_id: Some(self.payment_id.clone()), @@ -41,7 +40,7 @@ impl ApiEventMetric for RefundResponse { } #[cfg(feature = "v2")] -impl ApiEventMetric for RefundResponse { +impl ApiEventMetric for refunds::RefundResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Refund { payment_id: self.payment_id.clone(), diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 4313d224019..0f53776e644 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -3,18 +3,16 @@ use std::collections::{HashMap, HashSet}; use std::str::FromStr; use cards::CardNumber; +#[cfg(feature = "v1")] +use common_utils::crypto::OptionalEncryptableName; use common_utils::{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH, - crypto::OptionalEncryptableName, errors, ext_traits::OptionExt, id_type, link_utils, pii, types::{MinorUnit, Percentage, Surcharge}, }; -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use masking::PeekInterface; -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -use masking::{ExposeInterface, PeekInterface}; use serde::de; use utoipa::{schema, ToSchema}; @@ -2430,6 +2428,10 @@ pub enum MigrationStatus { Failed, } +#[cfg(all( + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2") +))] type PaymentMethodMigrationResponseType = ( Result<PaymentMethodMigrateResponse, String>, PaymentMethodRecord, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 011fd7e4431..29b0c050b67 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1,6 +1,7 @@ +#[cfg(feature = "v1")] +use std::fmt; use std::{ collections::{HashMap, HashSet}, - fmt, num::NonZeroI64, }; pub mod additional_info; @@ -9,6 +10,7 @@ use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; +#[cfg(feature = "v1")] use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; @@ -25,24 +27,25 @@ use common_utils::{ use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; -use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; +#[cfg(feature = "v1")] +use serde::{de, Deserializer}; +use serde::{ser::Serializer, Deserialize, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; -#[cfg(feature = "v1")] -use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] -use crate::mandates::ProcessorPaymentToken; +use crate::mandates; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, - disputes, enums as api_enums, + enums as api_enums, mandates::RecurringDetails, - refunds, ValidateFieldAndGet, }; +#[cfg(feature = "v1")] +use crate::{disputes, ephemeral_key::EphemeralKeyCreateResponse, refunds, ValidateFieldAndGet}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { @@ -5304,7 +5307,7 @@ pub struct ProxyPaymentsRequest { pub amount: AmountDetails, - pub recurring_details: ProcessorPaymentToken, + pub recurring_details: mandates::ProcessorPaymentToken, pub shipping: Option<Address>, @@ -7779,6 +7782,7 @@ mod payment_id_type { deserializer.deserialize_any(PaymentIdVisitor) } + #[allow(dead_code)] pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> @@ -8576,8 +8580,8 @@ impl PaymentRevenueRecoveryMetadata { ) { self.payment_connector_transmission = Some(payment_connector_transmission); } - pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { - ProcessorPaymentToken { + pub fn get_payment_token_for_api_request(&self) -> mandates::ProcessorPaymentToken { + mandates::ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token
2025-02-24T07:15:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR resolves the v2 warnings generated in api_models. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
50cbe20ee1da0392f4f590bade9f866435356b87
50cbe20ee1da0392f4f590bade9f866435356b87
juspay/hyperswitch
juspay__hyperswitch-7338
Bug: add payment_method_type duplication check for samsung pay As we do not have a unique identifier to store when we save a wallet, we are unable to prevent payment method duplication. As a result, when a customer uses a saved wallet, we end up saving it again. During the next payment, the customer will see two buttons for the same wallet in the customer PML. To address this issue, we check if the wallet is already saved. If the particular wallet is already saved, we simply update the 'last used' status for the same wallet, rather than creating a new entry. This payment method duplication check is already implemented for Apple Pay and Google Pay, similar check needs to be added for samsung pay as well
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 54514f6e05a..c286ae04d5f 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1651,6 +1651,12 @@ pub enum PaymentMethodType { DirectCarrierBilling, } +impl PaymentMethodType { + pub fn should_check_for_customer_saved_payment_method_type(self) -> bool { + matches!(self, Self::ApplePay | Self::GooglePay | Self::SamsungPay) + } +} + impl masking::SerializableSecret for PaymentMethodType {} /// Indicates the type of payment method. Eg: 'card', 'wallet', etc. diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 1803e12f0b2..8020c3d4d5f 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -591,10 +591,13 @@ pub async fn get_token_pm_type_mandate_details( mandate_generic_data.mandate_connector, mandate_generic_data.payment_method_info, ) - } else if request.payment_method_type - == Some(api_models::enums::PaymentMethodType::ApplePay) - || request.payment_method_type - == Some(api_models::enums::PaymentMethodType::GooglePay) + } else if request + .payment_method_type + .map(|payment_method_type_value| { + payment_method_type_value + .should_check_for_customer_saved_payment_method_type() + }) + .unwrap_or(false) { let payment_request_customer_id = request.get_customer_id(); if let Some(customer_id) = diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index d46977d8c99..b4e4db3d161 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -655,9 +655,11 @@ where }, None => { let customer_saved_pm_option = if payment_method_type - == Some(api_models::enums::PaymentMethodType::ApplePay) - || payment_method_type - == Some(api_models::enums::PaymentMethodType::GooglePay) + .map(|payment_method_type_value| { + payment_method_type_value + .should_check_for_customer_saved_payment_method_type() + }) + .unwrap_or(false) { match state .store
2025-02-21T09:00:17Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> As we do not have a unique identifier to store when we save a wallet, we are unable to prevent payment method duplication. As a result, when a customer uses a saved wallet, we end up saving it again. During the next payment, the customer will see two buttons for the same wallet in the customer PML. To address this issue, we check if the wallet is already saved. If the particular wallet is already saved, we simply update the 'last used' status for the same wallet, rather than creating a new entry. This payment method duplication check is already implemented for Apple Pay and Google Pay, and in this PR, I have extended it to include Samsung Pay as well. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a merchant connector account with google pay or samsung pay enabled -> Enable the below config ``` curl --location 'localhost:8080/configs/' \ --header 'api-key: api-key' \ --header 'Content-Type: application/json' \ --data '{ "key": "skip_saving_wallet_at_connector_merchant_1740130285", "value": "[\"samsung_pay\",\"google_pay\"]" }' ``` ``` { "key": "skip_saving_wallet_at_connector_merchant_1740130285", "value": "[\"samsung_pay\",\"google_pay\"]" } ``` -> Make a samsung pay payment with `"setup_future_usage": "off_session"` ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api-key' \ --data-raw '{ "amount": 2300, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 2300, "customer_id": "cu_1740120198", "setup_future_usage": "off_session", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "return_url": "https://google.com", "email": "[email protected]", "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": "samsung_pay", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "payment_method_data": { "wallet": { "samsung_pay": { "payment_credential": { "3_d_s": { "type": "S", "version": "100", "data": "samsung pay token" }, "payment_card_brand": "VI", "payment_currency_type": "USD", "payment_last4_fpan": "1661", "method": "3DS", "recurring_payment": false } } } } } ' ``` ``` { "payment_id": "pay_2p8lTfi6OM7SZrj6PBnR", "merchant_id": "merchant_1740130285", "status": "succeeded", "amount": 2300, "net_amount": 2300, "shipping_cost": null, "amount_capturable": 0, "amount_received": 2300, "connector": "cybersource", "client_secret": "pay_2p8lTfi6OM7SZrj6PBnR_secret_gMXnHSdwMhvGnpslHATf", "created": "2025-02-21T09:33:01.655Z", "currency": "USD", "customer_id": "cu_1740120198", "customer": { "id": "cu_1740120198", "name": "Joseph Doe", "email": "[email protected]", "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": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "samsung_pay": { "last4": "1661", "card_network": "Visa", "type": null } }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": null, "line3": null, "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "samsung_pay", "connector_label": "cybersource_US_default_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1740120198", "created_at": 1740130381, "expires": 1740133981, "secret": "epk_6ce927c963fa4105a8ab9228f97416b7" }, "manual_retry_allowed": false, "connector_transaction_id": "7401303829696483104805", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_2p8lTfi6OM7SZrj6PBnR_1", "payment_link": null, "profile_id": "pro_Gi6ZTv5ZEsUTOmapC9Rq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_1qwQigfi1hdSHlCKLEOw", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-02-21T09:48:01.655Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-02-21T09:33:04.066Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null } ``` -> List customer payment methods for the above customer. We can see that there is only one payment method that is saved ``` curl --location 'http://localhost:8080/customers/cu_1740120198/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: api-key' ``` ``` { "customer_payment_methods": [ { "payment_token": "token_NHsoBD91m4hXF1jHayz0", "payment_method_id": "pm_BuHQFVj1XP70L0hlwzrT", "customer_id": "cu_1740120198", "payment_method": "wallet", "payment_method_type": "samsung_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": "2025-02-21T09:33:04.086Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2025-02-21T09:33:04.086Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": null, "line3": null, "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null } } ], "is_guest_customer": null } ``` -> Make a google pay payment for the same customer and make customer pml. The response will contain the google pay at the top indicating it is the recently used payment method type. ``` curl --location 'http://localhost:8080/customers/cu_1740120198/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: api-key' ``` ``` { "customer_payment_methods": [ { "payment_token": "token_CLtCX0lG2248Tg9x8TCs", "payment_method_id": "pm_YQISjUrUW9YHJT0Szb7P", "customer_id": "cu_1740120198", "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": "2025-02-21T09:38:01.648Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2025-02-21T09:38:01.648Z", "default_payment_method_set": false, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": null, "line3": null, "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null } }, { "payment_token": "token_1w5WhYajhQbs8ghjTCXP", "payment_method_id": "pm_BuHQFVj1XP70L0hlwzrT", "customer_id": "cu_1740120198", "payment_method": "wallet", "payment_method_type": "samsung_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": "2025-02-21T09:33:04.086Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2025-02-21T09:33:04.086Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": null, "line3": null, "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null } } ], "is_guest_customer": null } ``` -> Now make one more samsung pay payment for the same customer ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api-key' \ --data-raw '{ "amount": 2300, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 2300, "customer_id": "cu_1740120198", "setup_future_usage": "off_session", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "return_url": "https://google.com", "email": "[email protected]", "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": "samsung_pay", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "payment_method_data": { "wallet": { "samsung_pay": { "payment_credential": { "3_d_s": { "type": "S", "version": "100", "data": "samsung pay token" }, "payment_card_brand": "VI", "payment_currency_type": "USD", "payment_last4_fpan": "1661", "method": "3DS", "recurring_payment": false } } } } } ' ``` ``` { "payment_id": "pay_4ixWGjRYTrngGcTYhhYO", "merchant_id": "merchant_1740130285", "status": "succeeded", "amount": 2300, "net_amount": 2300, "shipping_cost": null, "amount_capturable": 0, "amount_received": 2300, "connector": "cybersource", "client_secret": "pay_4ixWGjRYTrngGcTYhhYO_secret_PbeOhfHgCOZNYYYTmzcB", "created": "2025-02-21T09:40:10.925Z", "currency": "USD", "customer_id": "cu_1740120198", "customer": { "id": "cu_1740120198", "name": "Joseph Doe", "email": "[email protected]", "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": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "samsung_pay": { "last4": "1661", "card_network": "Visa", "type": null } }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": null, "line3": null, "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "samsung_pay", "connector_label": "cybersource_US_default_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1740120198", "created_at": 1740130810, "expires": 1740134410, "secret": "epk_86d9427e2e0641ae9d888d0aee1892e9" }, "manual_retry_allowed": false, "connector_transaction_id": "7401308119186931304807", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_4ixWGjRYTrngGcTYhhYO_1", "payment_link": null, "profile_id": "pro_Gi6ZTv5ZEsUTOmapC9Rq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_1qwQigfi1hdSHlCKLEOw", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-02-21T09:55:10.925Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-02-21T09:40:13.489Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null } ``` -> Make customer pml. The response should contain samsung pay at the top indicating it is the recently used payment method type and also there should only be one samsung pay button ``` curl --location 'http://localhost:8080/customers/cu_1740120198/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: api-key' ``` ``` { "customer_payment_methods": [ { "payment_token": "token_6QkmZgFGtk17Spmc0Krc", "payment_method_id": "pm_BuHQFVj1XP70L0hlwzrT", "customer_id": "cu_1740120198", "payment_method": "wallet", "payment_method_type": "samsung_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": "2025-02-21T09:33:04.086Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2025-02-21T09:40:13.492Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": null, "line3": null, "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null } }, { "payment_token": "token_uUhRNFlDlK8pkDXapajC", "payment_method_id": "pm_YQISjUrUW9YHJT0Szb7P", "customer_id": "cu_1740120198", "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": "2025-02-21T09:38:01.648Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2025-02-21T09:38:01.648Z", "default_payment_method_set": false, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": null, "line3": null, "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null } } ], "is_guest_customer": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.112.0
de865bd13440f965c0d3ffbe44a71925978212dd
de865bd13440f965c0d3ffbe44a71925978212dd
juspay/hyperswitch
juspay__hyperswitch-7346
Bug: FEAT[CONNECTOR]: Add feature_matrix support for coinbase, iatapay, nexixpay and square connectors add feature matrix endpoint to 4 more connectors: - coinbase - nexixpay - iatapay - square and also update the pm filters list for these 4 connectors scripts: ```check.sh #!/bin/bash # The lengthy string fetched from another script that i lost it somewhere a="AED,AFN,ALL,AMD,ANG,AOA,API,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BOV,BRL,BSD,BTC,BTN,BWP,BYR,BZD,CAD,CDF,CDN,CFA,CFP,CHE,CHF,CHW,CLF,CLP,CNY,COP,COU,CRC,CUC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,END,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,ISO,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LTL,LVL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRO,MUR,MVR,MWK,MXN,MXV,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PDX,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STD,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,USN,USS,UYI,UYU,UZS,VEF,VND,VUV,WIR,WST,XAF,XAG,XAU,XBA,XBB,XBC,XBD,XCD,XDR,XOF,XPD,XPF,XPT,XTS,XUS,XXX,YER,ZAR,ZMK,ZMW" # taken from /crates/common_enums/src/enums.rs declare -a currency_enum=( AED AFN ALL AMD ANG AOA ARS AUD AWG AZN BAM BBD BDT BGN BHD BIF BMD BND BOB BRL BSD BTN BWP BYN BZD CAD CDF CHF CLP CNY COP CRC CUP CVE CZK DJF DKK DOP DZD EGP ERN ETB EUR FJD FKP GBP GEL GHS GIP GMD GNF GTQ GYD HKD HNL HRK HTG HUF IDR ILS INR IQD IRR ISK JMD JOD JPY KES KGS KHR KMF KPW KRW KWD KYD KZT LAK LBP LKR LRD LSL LYD MAD MDL MGA MKD MMK MNT MOP MRU MUR MVR MWK MXN MYR MZN NAD NGN NIO NOK NPR NZD OMR PAB PEN PGK PHP PKR PLN PYG QAR RON RSD RUB RWF SAR SBD SCR SDG SEK SGD SHP SLE SLL SOS SRD SSP STN SVC SYP SZL THB TJS TMT TND TOP TRY TTD TWD TZS UAH UGX USD UYU UZS VES VND VUV WST XAF XCD XOF XPF YER ZAR ZMW ZWL ) # Convert string 'a' to array IFS=',' read -ra string_array <<< "$a" echo "Values in string 'a' that are not in Currency enum:" for value in "${string_array[@]}"; do found=false for enum_value in "${currency_enum[@]}"; do if [ "$value" = "$enum_value" ]; then found=true break fi done if [ "$found" = false ]; then echo "$value" fi done ``` ```checkv2.sh #!/bin/bash # The lengthy string a a="AED,AFN,ALL,AMD,ANG,AOA,API,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BOV,BRL,BSD,BTC,BTN,BWP,BYR,BZD,CAD,CDF,CDN,CFA,CFP,CHE,CHF,CHW,CLF,CLP,CNY,COP,COU,CRC,CUC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,END,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,ISO,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LTL,LVL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRO,MUR,MVR,MWK,MXN,MXV,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PDX,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STD,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,USN,USS,UYI,UYU,UZS,VEF,VND,VUV,WIR,WST,XAF,XAG,XAU,XBA,XBB,XBC,XBD,XCD,XDR,XOF,XPD,XPF,XPT,XTS,XUS,XXX,YER,ZAR,ZMK,ZMW" # String b with values to remove b=" Values in string 'a' that are not in Currency enum: API BOV BTC BYR CDN CFA CFP CHE CHW CLF COU CUC END ISO LTL LVL MRO MXV PDX STD USN USS UYI VEF WIR XAG XAU XBA XBB XBC XBD XDR XPD XPT XTS XUS XXX ZMK " # Function to remove values from b in string a remove_values() { local input_string="$1" local remove_values="$2" # Convert input string to array IFS=',' read -ra input_array <<< "$input_string" # Convert remove values to array readarray -t remove_array <<< "$remove_values" # Create new array for filtered values declare -a filtered_array # Check each value from input for value in "${input_array[@]}"; do skip=false # Compare with values to remove for remove_value in "${remove_array[@]}"; do # Remove any trailing whitespace or newline from remove_value remove_value=$(echo "$remove_value" | tr -d '[:space:]') if [ "$value" = "$remove_value" ]; then skip=true break fi done # If value should not be skipped, add it to filtered array if [ "$skip" = false ]; then filtered_array+=("$value") fi done # Join array elements with commas local result=$(IFS=,; echo "${filtered_array[*]}") echo "$result" } # Call the function and store result result=$(remove_values "$a" "$b") echo "Original string length: $(echo $a | tr -cd ',' | wc -c)" echo "New string length: $(echo $result | tr -cd ',' | wc -c)" echo "Removed $(( $(echo $a | tr -cd ',' | wc -c) - $(echo $result | tr -cd ',' | wc -c) )) values" echo -e "\nNew string:" echo "$result" ```
diff --git a/config/config.example.toml b/config/config.example.toml index 3457d330c9a..410b8dbe037 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -579,8 +579,25 @@ debit = { currency = "USD" } klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } [pm_filters.nexixpay] -credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } -debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } +credit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } +debit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } + +[pm_filters.square] +credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +debit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } + +[pm_filters.iatapay] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } +ideal = { country = "NL", currency = "EUR" } +local_bank_redirect = { country = "AT,BE,EE,FI,FR,DE,IE,IT,LV,LT,LU,NL,PT,ES,GB,IN,HK,SG,TH,BR,MX,GH,VN,MY,PH,JO,AU,CO", currency = "EUR,GBP,INR,HKD,SGD,THB,BRL,MXN,GHS,VND,MYR,PHP,JOD,AUD,COP" } +duit_now = { country = "MY", currency = "MYR" } +fps = { country = "GB", currency = "GBP" } +prompt_pay = { country = "TH", currency = "THB" } +viet_qr = { country = "VN", currency = "VND" } + +[pm_filters.coinbase] +crypto_currency = { country = "ZA,US,BR,CA,TR,SG,VN,GB,DE,FR,ES,PT,IT,NL,AU" } [pm_filters.novalnet] credit = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,BR,BS,BW,BY,BZ,CA,CD,CH,CL,CN,CO,CR,CU,CY,CZ,DE,DJ,DK,DO,DZ,EE,EG,ET,ES,FI,FJ,FR,GB,GE,GH,GI,GM,GR,GT,GY,HK,HN,HR,HU,ID,IE,IL,IN,IS,IT,JM,JO,JP,KE,KH,KR,KW,KY,KZ,LB,LK,LT,LV,LY,MA,MC,MD,ME,MG,MK,MN,MO,MT,MV,MW,MX,MY,NG,NI,NO,NP,NL,NZ,OM,PA,PE,PG,PH,PK,PL,PT,PY,QA,RO,RS,RU,RW,SA,SB,SC,SE,SG,SH,SI,SK,SL,SO,SM,SR,ST,SV,SY,TH,TJ,TN,TO,TR,TW,TZ,UA,UG,US,UY,UZ,VE,VA,VN,VU,WS,CF,AG,DM,GD,KN,LC,VC,YE,ZA,ZM", currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,GBP,GEL,GHS,GIP,GMD,GTQ,GYD,HKD,HNL,HRK,HUF,IDR,ILS,INR,ISK,JMD,JOD,JPY,KES,KHR,KRW,KWD,KYD,KZT,LBP,LKR,LYD,MAD,MDL,MGA,MKD,MNT,MOP,MVR,MWK,MXN,MYR,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLL,SOS,SRD,STN,SVC,SYP,THB,TJS,TND,TOP,TRY,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,YER,ZAR,ZMW"} diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 079134e6d03..2cc2d86ade1 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -346,8 +346,25 @@ samsung_pay = { currency = "USD,GBP,EUR" } paze = { currency = "USD" } [pm_filters.nexixpay] -credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } -debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } +credit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } +debit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } + +[pm_filters.square] +credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +debit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } + +[pm_filters.iatapay] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } +ideal = { country = "NL", currency = "EUR" } +local_bank_redirect = { country = "AT,BE,EE,FI,FR,DE,IE,IT,LV,LT,LU,NL,PT,ES,GB,IN,HK,SG,TH,BR,MX,GH,VN,MY,PH,JO,AU,CO", currency = "EUR,GBP,INR,HKD,SGD,THB,BRL,MXN,GHS,VND,MYR,PHP,JOD,AUD,COP" } +duit_now = { country = "MY", currency = "MYR" } +fps = { country = "GB", currency = "GBP" } +prompt_pay = { country = "TH", currency = "THB" } +viet_qr = { country = "VN", currency = "VND" } + +[pm_filters.coinbase] +crypto_currency = { country = "ZA,US,BR,CA,TR,SG,VN,GB,DE,FR,ES,PT,IT,NL,AU" } [pm_filters.novalnet] credit = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,BR,BS,BW,BY,BZ,CA,CD,CH,CL,CN,CO,CR,CU,CY,CZ,DE,DJ,DK,DO,DZ,EE,EG,ET,ES,FI,FJ,FR,GB,GE,GH,GI,GM,GR,GT,GY,HK,HN,HR,HU,ID,IE,IL,IN,IS,IT,JM,JO,JP,KE,KH,KR,KW,KY,KZ,LB,LK,LT,LV,LY,MA,MC,MD,ME,MG,MK,MN,MO,MT,MV,MW,MX,MY,NG,NI,NO,NP,NL,NZ,OM,PA,PE,PG,PH,PK,PL,PT,PY,QA,RO,RS,RU,RW,SA,SB,SC,SE,SG,SH,SI,SK,SL,SO,SM,SR,ST,SV,SY,TH,TJ,TN,TO,TR,TW,TZ,UA,UG,US,UY,UZ,VE,VA,VN,VU,WS,CF,AG,DM,GD,KN,LC,VC,YE,ZA,ZM", currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,GBP,GEL,GHS,GIP,GMD,GTQ,GYD,HKD,HNL,HRK,HUF,IDR,ILS,INR,ISK,JMD,JOD,JPY,KES,KHR,KRW,KWD,KYD,KZT,LBP,LKR,LYD,MAD,MDL,MGA,MKD,MNT,MOP,MVR,MWK,MXN,MYR,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLL,SOS,SRD,STN,SVC,SYP,THB,TJS,TND,TOP,TRY,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,YER,ZAR,ZMW"} diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 79ed26906ef..a291cff5c6f 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -308,7 +308,6 @@ debit = { currency = "USD" } apple_pay = { currency = "USD" } google_pay = { currency = "USD" } - [pm_filters.cybersource] credit = { currency = "USD,GBP,EUR,PLN" } debit = { currency = "USD,GBP,EUR,PLN" } @@ -318,8 +317,25 @@ samsung_pay = { currency = "USD,GBP,EUR" } paze = { currency = "USD" } [pm_filters.nexixpay] -credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } -debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } +credit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } +debit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } + +[pm_filters.square] +credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +debit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } + +[pm_filters.iatapay] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } +ideal = { country = "NL", currency = "EUR" } +local_bank_redirect = { country = "AT,BE,EE,FI,FR,DE,IE,IT,LV,LT,LU,NL,PT,ES,GB,IN,HK,SG,TH,BR,MX,GH,VN,MY,PH,JO,AU,CO", currency = "EUR,GBP,INR,HKD,SGD,THB,BRL,MXN,GHS,VND,MYR,PHP,JOD,AUD,COP" } +duit_now = { country = "MY", currency = "MYR" } +fps = { country = "GB", currency = "GBP" } +prompt_pay = { country = "TH", currency = "THB" } +viet_qr = { country = "VN", currency = "VND" } + +[pm_filters.coinbase] +crypto_currency = { country = "ZA,US,BR,CA,TR,SG,VN,GB,DE,FR,ES,PT,IT,NL,AU" } [pm_filters.novalnet] credit = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,BR,BS,BW,BY,BZ,CA,CD,CH,CL,CN,CO,CR,CU,CY,CZ,DE,DJ,DK,DO,DZ,EE,EG,ET,ES,FI,FJ,FR,GB,GE,GH,GI,GM,GR,GT,GY,HK,HN,HR,HU,ID,IE,IL,IN,IS,IT,JM,JO,JP,KE,KH,KR,KW,KY,KZ,LB,LK,LT,LV,LY,MA,MC,MD,ME,MG,MK,MN,MO,MT,MV,MW,MX,MY,NG,NI,NO,NP,NL,NZ,OM,PA,PE,PG,PH,PK,PL,PT,PY,QA,RO,RS,RU,RW,SA,SB,SC,SE,SG,SH,SI,SK,SL,SO,SM,SR,ST,SV,SY,TH,TJ,TN,TO,TR,TW,TZ,UA,UG,US,UY,UZ,VE,VA,VN,VU,WS,CF,AG,DM,GD,KN,LC,VC,YE,ZA,ZM", currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,GBP,GEL,GHS,GIP,GMD,GTQ,GYD,HKD,HNL,HRK,HUF,IDR,ILS,INR,ISK,JMD,JOD,JPY,KES,KHR,KRW,KWD,KYD,KZT,LBP,LKR,LYD,MAD,MDL,MGA,MKD,MNT,MOP,MVR,MWK,MXN,MYR,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLL,SOS,SRD,STN,SVC,SYP,THB,TJS,TND,TOP,TRY,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,YER,ZAR,ZMW"} diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index a92deafb20a..13a3f12228b 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -319,8 +319,25 @@ samsung_pay = { currency = "USD,GBP,EUR" } paze = { currency = "USD" } [pm_filters.nexixpay] -credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } -debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } +credit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } +debit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } + +[pm_filters.square] +credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +debit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } + +[pm_filters.iatapay] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } +ideal = { country = "NL", currency = "EUR" } +local_bank_redirect = { country = "AT,BE,EE,FI,FR,DE,IE,IT,LV,LT,LU,NL,PT,ES,GB,IN,HK,SG,TH,BR,MX,GH,VN,MY,PH,JO,AU,CO", currency = "EUR,GBP,INR,HKD,SGD,THB,BRL,MXN,GHS,VND,MYR,PHP,JOD,AUD,COP" } +duit_now = { country = "MY", currency = "MYR" } +fps = { country = "GB", currency = "GBP" } +prompt_pay = { country = "TH", currency = "THB" } +viet_qr = { country = "VN", currency = "VND" } + +[pm_filters.coinbase] +crypto_currency = { country = "ZA,US,BR,CA,TR,SG,VN,GB,DE,FR,ES,PT,IT,NL,AU" } [pm_filters.novalnet] credit = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,BR,BS,BW,BY,BZ,CA,CD,CH,CL,CN,CO,CR,CU,CY,CZ,DE,DJ,DK,DO,DZ,EE,EG,ET,ES,FI,FJ,FR,GB,GE,GH,GI,GM,GR,GT,GY,HK,HN,HR,HU,ID,IE,IL,IN,IS,IT,JM,JO,JP,KE,KH,KR,KW,KY,KZ,LB,LK,LT,LV,LY,MA,MC,MD,ME,MG,MK,MN,MO,MT,MV,MW,MX,MY,NG,NI,NO,NP,NL,NZ,OM,PA,PE,PG,PH,PK,PL,PT,PY,QA,RO,RS,RU,RW,SA,SB,SC,SE,SG,SH,SI,SK,SL,SO,SM,SR,ST,SV,SY,TH,TJ,TN,TO,TR,TW,TZ,UA,UG,US,UY,UZ,VE,VA,VN,VU,WS,CF,AG,DM,GD,KN,LC,VC,YE,ZA,ZM", currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,GBP,GEL,GHS,GIP,GMD,GTQ,GYD,HKD,HNL,HRK,HUF,IDR,ILS,INR,ISK,JMD,JOD,JPY,KES,KHR,KRW,KWD,KYD,KZT,LBP,LKR,LYD,MAD,MDL,MGA,MKD,MNT,MOP,MVR,MWK,MXN,MYR,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLL,SOS,SRD,STN,SVC,SYP,THB,TJS,TND,TOP,TRY,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,YER,ZAR,ZMW"} @@ -357,7 +374,6 @@ mifinity = { country = "BR,CN,SG,MY,DE,CH,DK,GB,ES,AD,GI,FI,FR,GR,HR,IT,JP,MX,AR [pm_filters.prophetpay] card_redirect.currency = "USD" - [pm_filters.stax] ach = { country = "US", currency = "USD" } diff --git a/config/development.toml b/config/development.toml index 13ed82c81f6..871352452ef 100644 --- a/config/development.toml +++ b/config/development.toml @@ -532,8 +532,25 @@ samsung_pay = { currency = "USD,GBP,EUR" } paze = { currency = "USD" } [pm_filters.nexixpay] -credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } -debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } +credit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } +debit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } + +[pm_filters.square] +credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +debit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } + +[pm_filters.iatapay] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } +ideal = { country = "NL", currency = "EUR" } +local_bank_redirect = { country = "AT,BE,EE,FI,FR,DE,IE,IT,LV,LT,LU,NL,PT,ES,GB,IN,HK,SG,TH,BR,MX,GH,VN,MY,PH,JO,AU,CO", currency = "EUR,GBP,INR,HKD,SGD,THB,BRL,MXN,GHS,VND,MYR,PHP,JOD,AUD,COP" } +duit_now = { country = "MY", currency = "MYR" } +fps = { country = "GB", currency = "GBP" } +prompt_pay = { country = "TH", currency = "THB" } +viet_qr = { country = "VN", currency = "VND" } + +[pm_filters.coinbase] +crypto_currency = { country = "ZA,US,BR,CA,TR,SG,VN,GB,DE,FR,ES,PT,IT,NL,AU" } [pm_filters.novalnet] credit = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,BR,BS,BW,BY,BZ,CA,CD,CH,CL,CN,CO,CR,CU,CY,CZ,DE,DJ,DK,DO,DZ,EE,EG,ET,ES,FI,FJ,FR,GB,GE,GH,GI,GM,GR,GT,GY,HK,HN,HR,HU,ID,IE,IL,IN,IS,IT,JM,JO,JP,KE,KH,KR,KW,KY,KZ,LB,LK,LT,LV,LY,MA,MC,MD,ME,MG,MK,MN,MO,MT,MV,MW,MX,MY,NG,NI,NO,NP,NL,NZ,OM,PA,PE,PG,PH,PK,PL,PT,PY,QA,RO,RS,RU,RW,SA,SB,SC,SE,SG,SH,SI,SK,SL,SO,SM,SR,ST,SV,SY,TH,TJ,TN,TO,TR,TW,TZ,UA,UG,US,UY,UZ,VE,VA,VN,VU,WS,CF,AG,DM,GD,KN,LC,VC,YE,ZA,ZM", currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,GBP,GEL,GHS,GIP,GMD,GTQ,GYD,HKD,HNL,HRK,HUF,IDR,ILS,INR,ISK,JMD,JOD,JPY,KES,KHR,KRW,KWD,KYD,KZT,LBP,LKR,LYD,MAD,MDL,MGA,MKD,MNT,MOP,MVR,MWK,MXN,MYR,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLL,SOS,SRD,STN,SVC,SYP,THB,TJS,TND,TOP,TRY,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,YER,ZAR,ZMW" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 0031c37f022..109a3d42a1f 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -484,8 +484,25 @@ samsung_pay = { currency = "USD,GBP,EUR" } paze = { currency = "USD" } [pm_filters.nexixpay] -credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } -debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } +credit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } +debit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } + +[pm_filters.square] +credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +debit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } + +[pm_filters.iatapay] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } +ideal = { country = "NL", currency = "EUR" } +local_bank_redirect = { country = "AT,BE,EE,FI,FR,DE,IE,IT,LV,LT,LU,NL,PT,ES,GB,IN,HK,SG,TH,BR,MX,GH,VN,MY,PH,JO,AU,CO", currency = "EUR,GBP,INR,HKD,SGD,THB,BRL,MXN,GHS,VND,MYR,PHP,JOD,AUD,COP" } +duit_now = { country = "MY", currency = "MYR" } +fps = { country = "GB", currency = "GBP" } +prompt_pay = { country = "TH", currency = "THB" } +viet_qr = { country = "VN", currency = "VND" } + +[pm_filters.coinbase] +crypto_currency = { country = "ZA,US,BR,CA,TR,SG,VN,GB,DE,FR,ES,PT,IT,NL,AU" } [pm_filters.novalnet] credit = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,BR,BS,BW,BY,BZ,CA,CD,CH,CL,CN,CO,CR,CU,CY,CZ,DE,DJ,DK,DO,DZ,EE,EG,ET,ES,FI,FJ,FR,GB,GE,GH,GI,GM,GR,GT,GY,HK,HN,HR,HU,ID,IE,IL,IN,IS,IT,JM,JO,JP,KE,KH,KR,KW,KY,KZ,LB,LK,LT,LV,LY,MA,MC,MD,ME,MG,MK,MN,MO,MT,MV,MW,MX,MY,NG,NI,NO,NP,NL,NZ,OM,PA,PE,PG,PH,PK,PL,PT,PY,QA,RO,RS,RU,RW,SA,SB,SC,SE,SG,SH,SI,SK,SL,SO,SM,SR,ST,SV,SY,TH,TJ,TN,TO,TR,TW,TZ,UA,UG,US,UY,UZ,VE,VA,VN,VU,WS,CF,AG,DM,GD,KN,LC,VC,YE,ZA,ZM", currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,GBP,GEL,GHS,GIP,GMD,GTQ,GYD,HKD,HNL,HRK,HUF,IDR,ILS,INR,ISK,JMD,JOD,JPY,KES,KHR,KRW,KWD,KYD,KZT,LBP,LKR,LYD,MAD,MDL,MGA,MKD,MNT,MOP,MVR,MWK,MXN,MYR,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLL,SOS,SRD,STN,SVC,SYP,THB,TJS,TND,TOP,TRY,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,YER,ZAR,ZMW"} diff --git a/crates/hyperswitch_connectors/src/connectors/coinbase.rs b/crates/hyperswitch_connectors/src/connectors/coinbase.rs index f58437ff079..a567d5b5c82 100644 --- a/crates/hyperswitch_connectors/src/connectors/coinbase.rs +++ b/crates/hyperswitch_connectors/src/connectors/coinbase.rs @@ -22,7 +22,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundsRouterData, @@ -39,6 +42,7 @@ use hyperswitch_interfaces::{ types::{PaymentsAuthorizeType, PaymentsSyncType, Response}, webhooks, }; +use lazy_static::lazy_static; use masking::Mask; use transformers as coinbase; @@ -135,24 +139,7 @@ impl ConnectorCommon for Coinbase { } } -impl ConnectorValidation for Coinbase { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - enums::CaptureMethod::Automatic - | enums::CaptureMethod::Manual - | enums::CaptureMethod::SequentialAutomatic => Ok(()), - enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - utils::construct_not_supported_error_report(capture_method, self.id()), - ), - } - } -} +impl ConnectorValidation for Coinbase {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Coinbase @@ -445,4 +432,50 @@ impl webhooks::IncomingWebhook for Coinbase { } } -impl ConnectorSpecifications for Coinbase {} +lazy_static! { + static ref COINBASE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: + "Coinbase is a place for people and businesses to buy, sell, and manage crypto.", + description: + "Square is the largest business technology platform serving all kinds of businesses.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + static ref COINBASE_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let mut coinbase_supported_payment_methods = SupportedPaymentMethods::new(); + + coinbase_supported_payment_methods.add( + enums::PaymentMethod::Crypto, + enums::PaymentMethodType::CryptoCurrency, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::NotSupported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + coinbase_supported_payment_methods + }; + static ref COINBASE_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = + vec![enums::EventClass::Payments, enums::EventClass::Refunds,]; +} + +impl ConnectorSpecifications for Coinbase { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&*COINBASE_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*COINBASE_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&*COINBASE_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/iatapay.rs b/crates/hyperswitch_connectors/src/connectors/iatapay.rs index 9db00b61101..f9ab2f3159f 100644 --- a/crates/hyperswitch_connectors/src/connectors/iatapay.rs +++ b/crates/hyperswitch_connectors/src/connectors/iatapay.rs @@ -1,6 +1,6 @@ pub mod transformers; -use api_models::webhooks::IncomingWebhookEvent; +use api_models::{enums, webhooks::IncomingWebhookEvent}; use base64::Engine; use common_utils::{ consts::BASE64_ENGINE, @@ -23,7 +23,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, @@ -41,6 +44,7 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; +use lazy_static::lazy_static; use masking::{Mask, PeekInterface}; use transformers::{self as iatapay, IatapayPaymentsResponse}; @@ -744,4 +748,126 @@ impl IncomingWebhook for Iatapay { } } -impl ConnectorSpecifications for Iatapay {} +lazy_static! { + static ref IATAPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Iatapay", + description: + "IATA Pay is a payment method for travellers to pay for air tickets purchased online by directly debiting their bank account.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + + static ref IATAPAY_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic + ]; + + let mut iatapay_supported_payment_methods = SupportedPaymentMethods::new(); + + iatapay_supported_payment_methods.add( + enums::PaymentMethod::Upi, + enums::PaymentMethodType::UpiCollect, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None + } + ); + + iatapay_supported_payment_methods.add( + enums::PaymentMethod::Upi, + enums::PaymentMethodType::UpiIntent, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None + } + ); + + iatapay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Ideal, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None + } + ); + + iatapay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::LocalBankRedirect, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None + } + ); + + iatapay_supported_payment_methods.add( + enums::PaymentMethod::RealTimePayment, + enums::PaymentMethodType::DuitNow, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None + } + ); + + iatapay_supported_payment_methods.add( + enums::PaymentMethod::RealTimePayment, + enums::PaymentMethodType::Fps, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None + } + ); + + iatapay_supported_payment_methods.add( + enums::PaymentMethod::RealTimePayment, + enums::PaymentMethodType::PromptPay, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None + } + ); + + iatapay_supported_payment_methods.add( + enums::PaymentMethod::RealTimePayment, + enums::PaymentMethodType::VietQr, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None + } + ); + + iatapay_supported_payment_methods + }; + + static ref IATAPAY_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = + vec![enums::EventClass::Payments, enums::EventClass::Refunds,]; +} + +impl ConnectorSpecifications for Iatapay { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&*IATAPAY_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*IATAPAY_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&*IATAPAY_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs index 9ec2ac73903..8a9c804cbf2 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs @@ -25,7 +25,10 @@ use hyperswitch_domain_models::{ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, @@ -43,6 +46,7 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks, }; +use lazy_static::lazy_static; use masking::{ExposeInterface, Mask}; use serde_json::Value; use transformers as nexixpay; @@ -204,22 +208,6 @@ impl ConnectorCommon for Nexixpay { } impl ConnectorValidation for Nexixpay { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - enums::CaptureMethod::Automatic - | enums::CaptureMethod::Manual - | enums::CaptureMethod::SequentialAutomatic => Ok(()), - enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - utils::construct_not_implemented_error_report(capture_method, self.id()), - ), - } - } fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, @@ -999,4 +987,83 @@ impl webhooks::IncomingWebhook for Nexixpay { } } -impl ConnectorSpecifications for Nexixpay {} +lazy_static! { + static ref NEXIXPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Nexixpay", + description: "Nexixpay is an Italian bank that specialises in payment systems such as Nexi Payments (formerly known as CartaSi).", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + + static ref NEXIXPAY_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { + + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + ]; + + let mut nexixpay_supported_payment_methods = SupportedPaymentMethods::new(); + + nexixpay_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::Supported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ) + } + ); + nexixpay_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::Supported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network, + } + }), + ) + } + ); + + nexixpay_supported_payment_methods + }; + + static ref NEXIXPAY_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); +} + +impl ConnectorSpecifications for Nexixpay { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&*NEXIXPAY_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*NEXIXPAY_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&*NEXIXPAY_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/square.rs b/crates/hyperswitch_connectors/src/connectors/square.rs index e07d85800ff..9615d4afdd7 100644 --- a/crates/hyperswitch_connectors/src/connectors/square.rs +++ b/crates/hyperswitch_connectors/src/connectors/square.rs @@ -26,7 +26,10 @@ use hyperswitch_domain_models::{ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsAuthorizeSessionTokenRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, @@ -44,6 +47,7 @@ use hyperswitch_interfaces::{ types::{self, PaymentsAuthorizeType, Response}, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; +use lazy_static::lazy_static; use masking::{Mask, Maskable, PeekInterface}; use transformers::{ self as square, SquareAuthType, SquarePaymentsRequest, SquareRefundRequest, SquareTokenRequest, @@ -52,7 +56,7 @@ use transformers::{ use crate::{ constants::headers, types::ResponseRouterData, - utils::{self, get_header_key_value, RefundsRequestData}, + utils::{get_header_key_value, RefundsRequestData}, }; #[derive(Debug, Clone)] @@ -158,24 +162,7 @@ impl ConnectorCommon for Square { } } -impl ConnectorValidation for Square { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - enums::CaptureMethod::Automatic - | enums::CaptureMethod::Manual - | enums::CaptureMethod::SequentialAutomatic => Ok(()), - enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - utils::construct_not_implemented_error_report(capture_method, self.id()), - ), - } - } -} +impl ConnectorValidation for Square {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Square { //TODO: implement sessions flow @@ -927,4 +914,85 @@ impl IncomingWebhook for Square { } } -impl ConnectorSpecifications for Square {} +lazy_static! { + static ref SQUARE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Square", + description: + "Square is the largest business technology platform serving all kinds of businesses.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + static ref SQUARE_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::UnionPay, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::JCB, + ]; + + let mut square_supported_payment_methods = SupportedPaymentMethods::new(); + + square_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + square_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network, + } + }), + ), + }, + ); + + square_supported_payment_methods + }; + static ref SQUARE_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = + vec![enums::EventClass::Payments, enums::EventClass::Refunds,]; +} + +impl ConnectorSpecifications for Square { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&*SQUARE_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*SQUARE_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&*SQUARE_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 6766d7cb7e6..d0804039b39 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -108,8 +108,8 @@ elavon.base_url = "https://api.demo.convergepay.com/VirtualMerchantDemo/" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox" fiuu.base_url = "https://sandbox.merchant.razer.com/" -fiuu.secondary_base_url="https://sandbox.merchant.razer.com/" -fiuu.third_base_url="https://api.merchant.razer.com/" +fiuu.secondary_base_url = "https://sandbox.merchant.razer.com/" +fiuu.third_base_url = "https://api.merchant.razer.com/" forte.base_url = "https://sandbox.forte.net/api/v3" getnet.base_url = "https://api-test.getneteurope.com/engine/rest" globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/" @@ -121,7 +121,7 @@ iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1" inespay.base_url = "https://apiflow.inespay.com/san/v21" itaubank.base_url = "https://sandbox.devportal.itau.com.br/" jpmorgan.base_url = "https://api-mock.payments.jpmorgan.com/api/v2" -jpmorgan.secondary_base_url="https://id.payments.jpmorgan.com" +jpmorgan.secondary_base_url = "https://id.payments.jpmorgan.com" klarna.base_url = "https://api{{klarna_region}}.playground.klarna.com/" mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" @@ -140,7 +140,7 @@ nuvei.base_url = "https://ppp-test.nuvei.com/" opayo.base_url = "https://pi-test.sagepay.com/" opennode.base_url = "https://dev-api.opennode.com" paybox.base_url = "https://preprod-ppps.paybox.com/PPPS.php" -paybox.secondary_base_url="https://preprod-tpeweb.paybox.com/" +paybox.secondary_base_url = "https://preprod-tpeweb.paybox.com/" payeezy.base_url = "https://api-cert.payeezy.com/" payme.base_url = "https://sandbox.payme.io/" payone.base_url = "https://payment.preprod.payone.com/" @@ -183,8 +183,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", @@ -272,22 +271,43 @@ cards = [ ] [pm_filters.volt] -open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"} +open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL" } [pm_filters.razorpay] -upi_collect = {country = "IN", currency = "INR"} +upi_collect = { country = "IN", currency = "INR" } [pm_filters.adyen] boleto = { country = "BR", currency = "BRL" } -sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"} +sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR" } paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } -klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"} +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD" } ideal = { country = "NL", currency = "EUR" } [pm_filters.bambora] credit = { country = "US,CA", currency = "USD" } debit = { country = "US,CA", currency = "USD" } +[pm_filters.nexixpay] +credit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } +debit = { country = "PL,CZ,RO,SE,CH,HU,US,GB,DK,UA,MK,BG,HR,BA,IS,RS,GI", currency = "PLN,CZK,RON,SEK,CHF,HUF,USD,GBP,DKK,UAH,MKD,BGN,HRK,BAM,ISK,RSD,GIP" } + +[pm_filters.square] +credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +debit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } + +[pm_filters.iatapay] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } +ideal = { country = "NL", currency = "EUR" } +local_bank_redirect = { country = "AT,BE,EE,FI,FR,DE,IE,IT,LV,LT,LU,NL,PT,ES,GB,IN,HK,SG,TH,BR,MX,GH,VN,MY,PH,JO,AU,CO", currency = "EUR,GBP,INR,HKD,SGD,THB,BRL,MXN,GHS,VND,MYR,PHP,JOD,AUD,COP" } +duit_now = { country = "MY", currency = "MYR" } +fps = { country = "GB", currency = "GBP" } +prompt_pay = { country = "TH", currency = "THB" } +viet_qr = { country = "VN", currency = "VND" } + +[pm_filters.coinbase] +crypto_currency = { country = "ZA,US,BR,CA,TR,SG,VN,GB,DE,FR,ES,PT,IT,NL,AU" } + [pm_filters.zen] credit = { not_available_flows = { capture_method = "manual" } } debit = { not_available_flows = { capture_method = "manual" } } @@ -304,10 +324,10 @@ red_pagos = { country = "UY", currency = "UYU" } [tokenization] stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization" } -mollie = {long_lived_token = false, payment_method = "card"} +mollie = { 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"} +gocardless = { long_lived_token = true, payment_method = "bank_debit" } +billwerk = { long_lived_token = false, payment_method = "card" } [connector_customer] connector_list = "gocardless,stax,stripe" @@ -337,17 +357,17 @@ discord_invite_url = "https://discord.gg/wJZ7DVW8mm" payout_eligibility = true [mandates.supported_payment_methods] -bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } -bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } -bank_debit.bacs = { connector_list = "stripe,gocardless" } -bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal" -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal" -pay_later.klarna.connector_list = "adyen" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet" +bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } +bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } +bank_debit.bacs = { connector_list = "stripe,gocardless" } +bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal" +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal" +pay_later.klarna.connector_list = "adyen" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet" -wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal" +wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet" +wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" wallet.go_pay.connector_list = "adyen" @@ -356,13 +376,13 @@ wallet.dana.connector_list = "adyen" wallet.twint.connector_list = "adyen" wallet.vipps.connector_list = "adyen" -bank_redirect.ideal.connector_list = "stripe,adyen,globalpay,multisafepay,nexinets" -bank_redirect.sofort.connector_list = "stripe,globalpay" -bank_redirect.giropay.connector_list = "globalpay,multisafepay,nexinets" -bank_redirect.bancontact_card.connector_list="adyen,stripe" -bank_redirect.trustly.connector_list="adyen" -bank_redirect.open_banking_uk.connector_list="adyen" -bank_redirect.eps.connector_list="globalpay,nexinets" +bank_redirect.ideal.connector_list = "stripe,adyen,globalpay,multisafepay,nexinets" +bank_redirect.sofort.connector_list = "stripe,globalpay" +bank_redirect.giropay.connector_list = "globalpay,multisafepay,nexinets" +bank_redirect.bancontact_card.connector_list = "adyen,stripe" +bank_redirect.trustly.connector_list = "adyen" +bank_redirect.open_banking_uk.connector_list = "adyen" +bank_redirect.eps.connector_list = "globalpay,nexinets" [cors] @@ -372,8 +392,8 @@ allowed_methods = "GET,POST,PUT,DELETE" wildcard_origin = false [mandates.update_mandate_supported] -card.credit ={connector_list ="cybersource"} -card.debit = {connector_list ="cybersource"} +card.credit = { connector_list = "cybersource" } +card.debit = { connector_list = "cybersource" } [network_transaction_id_supported_connectors] connector_list = "adyen,cybersource,novalnet,stripe,worldpay" @@ -409,14 +429,14 @@ enabled = false global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "" } [multitenancy.tenants.public] -base_url = "http://localhost:8080" -schema = "public" -accounts_schema = "public" +base_url = "http://localhost:8080" +schema = "public" +accounts_schema = "public" redis_key_prefix = "" clickhouse_database = "default" [multitenancy.tenants.public.user] -control_center_url = "http://localhost:9000" +control_center_url = "http://localhost:9000" [email] sender_email = "[email protected]"
2025-02-21T09:22:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> this pr introduces feature_matrix api to 4 more connectors and in addition to that, pm filters also have been updated. have written many scripts to verify the pm_filters and are attached in the issue ### 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). --> With this PR, we'll be increasing the `feature_matrix` coverage for connectors by implementing `ConnectorSpecifications` just so that it will be the single source of truth for getting information about the payment methods and payment method types that the connector supports. ## 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 by making a request to the feature matrix endpoint: request: ```curl curl --location 'http://Localhost:8080/feature_matrix' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' ``` response: ```json { "connector_count": 7, "connectors": [ { "name": "BAMBORA", "display_name": "Bambora", "description": "Bambora is a leading online payment provider in Canada and United States.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "Discover", "JCB", "DinersClub" ], "supported_countries": [ "US", "CA" ], "supported_currencies": [ "USD" ] } ], "supported_webhook_flows": [] }, { "name": "COINBASE", "display_name": "Coinbase is a place for people and businesses to buy, sell, and manage crypto.", "description": "Square is the largest business technology platform serving all kinds of businesses.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "crypto", "payment_method_type": "crypto_currency", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "VN", "US", "DE", "BR", "SG", "FR", "ZA", "ES", "GB", "CA", "IT", "TR", "NL", "PT", "AU" ], "supported_currencies": null } ], "supported_webhook_flows": [ "payments", "refunds" ] }, { "name": "DEUTSCHEBANK", "display_name": "Deutsche Bank", "description": "Deutsche Bank is a German multinational investment bank and financial services company ", "category": "bank_acquirer", "supported_payment_methods": [ { "payment_method": "bank_debit", "payment_method_type": "sepa", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": null, "supported_currencies": null }, { "payment_method": "card", "payment_method_type": "debit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "not_supported", "supported_card_networks": [ "Visa", "Mastercard" ], "supported_countries": null, "supported_currencies": null }, { "payment_method": "card", "payment_method_type": "credit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "not_supported", "supported_card_networks": [ "Visa", "Mastercard" ], "supported_countries": null, "supported_currencies": null } ], "supported_webhook_flows": [] }, { "name": "IATAPAY", "display_name": "Iatapay", "description": "IATA Pay is a payment method for travellers to pay for air tickets purchased online by directly debiting their bank account.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "bank_redirect", "payment_method_type": "local_bank_redirect", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic" ], "supported_countries": [ "GB", "SG", "LV", "ES", "TH", "AU", "LT", "IE", "MX", "PT", "GH", "FI", "DE", "VN", "FR", "PH", "IN", "JO", "MY", "EE", "HK", "IT", "NL", "CO", "BE", "BR", "LU", "AT" ], "supported_currencies": [ "GBP", "INR", "AUD", "SGD", "EUR", "MXN", "VND", "PHP", "BRL", "MYR", "THB", "HKD", "COP", "JOD", "GHS" ] }, { "payment_method": "bank_redirect", "payment_method_type": "ideal", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic" ], "supported_countries": [ "NL" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "real_time_payment", "payment_method_type": "fps", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic" ], "supported_countries": [ "GB" ], "supported_currencies": [ "GBP" ] }, { "payment_method": "real_time_payment", "payment_method_type": "viet_qr", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic" ], "supported_countries": [ "VN" ], "supported_currencies": [ "VND" ] }, { "payment_method": "real_time_payment", "payment_method_type": "duit_now", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic" ], "supported_countries": [ "MY" ], "supported_currencies": [ "MYR" ] }, { "payment_method": "real_time_payment", "payment_method_type": "prompt_pay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic" ], "supported_countries": [ "TH" ], "supported_currencies": [ "THB" ] }, { "payment_method": "upi", "payment_method_type": "upi_intent", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic" ], "supported_countries": [ "IN" ], "supported_currencies": [ "INR" ] }, { "payment_method": "upi", "payment_method_type": "upi_collect", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic" ], "supported_countries": [ "IN" ], "supported_currencies": [ "INR" ] } ], "supported_webhook_flows": [ "payments", "refunds" ] }, { "name": "NEXIXPAY", "display_name": "Nexixpay", "description": "Nexixpay is an Italian bank that specialises in payment systems such as Nexi Payments (formerly known as CartaSi).", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "debit", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "JCB" ], "supported_countries": [ "BA", "HR", "GB", "DK", "PL", "US", "GI", "HU", "MK", "CZ", "CH", "RS", "SE", "BG", "RO", "UA", "IS" ], "supported_currencies": [ "BGN", "CHF", "HUF", "HRK", "CZK", "RSD", "UAH", "SEK", "GIP", "RON", "ISK", "USD", "PLN", "GBP", "MKD", "DKK", "BAM" ] }, { "payment_method": "card", "payment_method_type": "credit", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "JCB" ], "supported_countries": [ "RO", "PL", "CH", "UA", "MK", "BA", "CZ", "HU", "SE", "US", "HR", "RS", "DK", "GB", "IS", "BG", "GI" ], "supported_currencies": [ "MKD", "CHF", "HUF", "BGN", "CZK", "ISK", "RSD", "GIP", "SEK", "BAM", "GBP", "USD", "HRK", "RON", "PLN", "DKK", "UAH" ] } ], "supported_webhook_flows": [] }, { "name": "SQUARE", "display_name": "Square", "description": "Square is the largest business technology platform serving all kinds of businesses.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "debit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "Discover", "UnionPay", "Interac", "JCB" ], "supported_countries": [ "GB", "ES", "US", "AU", "CA", "FR", "JP", "IE" ], "supported_currencies": [ "MWK", "GIP", "MOP", "AWG", "KMF", "NGN", "TMT", "LKR", "CRC", "HNL", "MXN", "QAR", "BMD", "SYP", "NOK", "AMD", "GYD", "UZS", "XCD", "SLE", "BZD", "GBP", "EUR", "SZL", "TTD", "KYD", "MNT", "KPW", "WST", "RON", "HKD", "GHS", "MUR", "USD", "HRK", "INR", "PYG", "UGX", "LAK", "OMR", "SSP", "HUF", "FJD", "GTQ", "BBD", "MMK", "SRD", "MKD", "CZK", "AUD", "TJS", "ZAR", "RSD", "GEL", "LRD", "AOA", "GNF", "ISK", "NAD", "BGN", "IRR", "BND", "THB", "KRW", "BHD", "TOP", "PHP", "MYR", "UYU", "BSD", "DOP", "SBD", "SVC", "MVR", "EGP", "TRY", "SDG", "KHR", "MAD", "MGA", "SLL", "CDF", "NZD", "TND", "TZS", "VUV", "BAM", "ANG", "NPR", "XOF", "BWP", "XPF", "MDL", "BTN", "DZD", "ETB", "LYD", "IDR", "IQD", "BIF", "CHF", "JPY", "SAR", "KGS", "JOD", "KWD", "PKR", "UAH", "KES", "MZN", "GMD", "LBP", "PAB", "SCR", "YER", "JMD", "ERN", "CNY", "XAF", "BOB", "BDT", "ARS", "PEN", "RUB", "AZN", "KZT", "CAD", "SHP", "CVE", "NIO", "DJF", "HTG", "AED", "BRL", "COP", "DKK", "PLN", "SOS", "SGD", "LSL", "ALL", "ZMW", "PGK", "CLP", "FKP", "AFN", "ILS", "VND", "RWF", "CUP", "SEK", "TWD" ] }, { "payment_method": "card", "payment_method_type": "credit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "Discover", "UnionPay", "Interac", "JCB" ], "supported_countries": [ "JP", "ES", "IE", "AU", "CA", "GB", "FR", "US" ], "supported_currencies": [ "SRD", "SCR", "CLP", "SLL", "VUV", "NIO", "ANG", "DOP", "OMR", "TZS", "IQD", "BIF", "CDF", "ILS", "PAB", "CNY", "ETB", "BDT", "BGN", "SHP", "KHR", "SVC", "AUD", "JOD", "RSD", "IDR", "KGS", "EGP", "SSP", "TND", "XPF", "BND", "ISK", "GHS", "KYD", "GIP", "MGA", "TOP", "TRY", "USD", "RWF", "COP", "BHD", "BBD", "MWK", "WST", "BWP", "XOF", "AMD", "MOP", "QAR", "AFN", "NAD", "PHP", "ALL", "XCD", "AWG", "CZK", "HKD", "GBP", "GNF", "GMD", "NOK", "ERN", "RUB", "PEN", "SBD", "AED", "DJF", "ZMW", "DZD", "UAH", "AOA", "NPR", "HUF", "PKR", "LBP", "DKK", "HNL", "KES", "CHF", "NGN", "SEK", "TWD", "MAD", "FJD", "PYG", "BOB", "JPY", "JMD", "BTN", "LRD", "MNT", "SLE", "SOS", "TTD", "ZAR", "KWD", "UGX", "BAM", "RON", "TJS", "GYD", "NZD", "CAD", "TMT", "MMK", "BRL", "SGD", "UYU", "SZL", "FKP", "SAR", "ARS", "GEL", "LAK", "MZN", "VND", "BSD", "LYD", "UZS", "XAF", "MVR", "PLN", "LKR", "SYP", "HRK", "BZD", "KPW", "PGK", "EUR", "MYR", "GTQ", "YER", "MUR", "CRC", "CUP", "IRR", "KRW", "MXN", "AZN", "BMD", "HTG", "KMF", "INR", "KZT", "LSL", "MDL", "SDG", "THB", "CVE", "MKD" ] } ], "supported_webhook_flows": [ "payments", "refunds" ] }, { "name": "ZSL", "display_name": "ZSL", "description": "Zsl is a payment gateway operating in China, specializing in facilitating local bank transfers", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "bank_transfer", "payment_method_type": "local_bank_transfer", "mandates": "not_supported", "refunds": "not_supported", "supported_capture_methods": [ "automatic" ], "supported_countries": [ "CN" ], "supported_currencies": [ "CNY" ] } ], "supported_webhook_flows": [] } ] } ``` Iatapay does support refunds. They have mentioned it in general that refunds are supported. And upon testing (intent creation, sync and refund), all working fine. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy --all-features --all-targets -- -D warnings` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.112.0
9f334c1ebcf0e8ee15ae2af608fb8f27fab2a6b2
9f334c1ebcf0e8ee15ae2af608fb8f27fab2a6b2
juspay/hyperswitch
juspay__hyperswitch-7321
Bug: add support to collect customer address details form Samsung Pay based on business profile config and connector required fields add support to collect customer address details form Samsung Pay based on business profile config and connector required fields
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index c91810a9902..5616da620bd 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -19766,7 +19766,9 @@ "merchant", "amount", "protocol", - "allowed_brands" + "allowed_brands", + "billing_address_required", + "shipping_address_required" ], "properties": { "version": { @@ -19796,6 +19798,14 @@ "type": "string" }, "description": "List of supported card brands" + }, + "billing_address_required": { + "type": "boolean", + "description": "Is billing address required to be collected from wallet" + }, + "shipping_address_required": { + "type": "boolean", + "description": "Is shipping address required to be collected from wallet" } } }, diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 587cba45e6a..49aa61763b7 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -24849,7 +24849,9 @@ "merchant", "amount", "protocol", - "allowed_brands" + "allowed_brands", + "billing_address_required", + "shipping_address_required" ], "properties": { "version": { @@ -24879,6 +24881,14 @@ "type": "string" }, "description": "List of supported card brands" + }, + "billing_address_required": { + "type": "boolean", + "description": "Is billing address required to be collected from wallet" + }, + "shipping_address_required": { + "type": "boolean", + "description": "Is shipping address required to be collected from wallet" } } }, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 7b1ba943ee7..b107c2d6b96 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -6570,6 +6570,10 @@ pub struct SamsungPaySessionTokenResponse { pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, + /// Is billing address required to be collected from wallet + pub billing_address_required: bool, + /// Is shipping address required to be collected from wallet + pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index f6e5d1e7f05..662453c4a3e 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -610,8 +610,11 @@ fn create_paze_session_token( } fn create_samsung_pay_session_token( + state: &routes::SessionState, router_data: &types::PaymentsSessionRouterData, header_payload: hyperswitch_domain_models::payments::HeaderPayload, + connector: &api::ConnectorData, + business_profile: &domain::Profile, ) -> RouterResult<types::PaymentsSessionRouterData> { let samsung_pay_session_token_data = router_data .connector_wallets_details @@ -657,6 +660,20 @@ fn create_samsung_pay_session_token( let formatted_payment_id = router_data.payment_id.replace("_", "-"); + let billing_address_required = is_billing_address_required_to_be_collected_from_wallet( + state, + connector, + business_profile, + enums::PaymentMethodType::SamsungPay, + ); + + let shipping_address_required = is_shipping_address_required_to_be_collected_form_wallet( + state, + connector, + business_profile, + enums::PaymentMethodType::SamsungPay, + ); + Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::SamsungPay(Box::new( @@ -677,6 +694,8 @@ fn create_samsung_pay_session_token( }, protocol: payment_types::SamsungPayProtocolType::Protocol3ds, allowed_brands: samsung_pay_wallet_details.allowed_brands, + billing_address_required, + shipping_address_required, }, )), }), @@ -684,6 +703,86 @@ fn create_samsung_pay_session_token( }) } +/// Function to determine whether the billing address is required to be collected from the wallet, +/// based on business profile settings, the payment method type, and the connector's required fields +/// for the specific payment method. +/// +/// If `always_collect_billing_details_from_wallet_connector` is enabled, it indicates that the +/// billing address is always required to be collected from the wallet. +/// +/// If only `collect_billing_details_from_wallet_connector` is enabled, the billing address will be +/// collected only if the connector required fields for the specific payment method type contain +/// the billing fields. +fn is_billing_address_required_to_be_collected_from_wallet( + state: &routes::SessionState, + connector: &api::ConnectorData, + business_profile: &domain::Profile, + payment_method_type: enums::PaymentMethodType, +) -> bool { + let always_collect_billing_details_from_wallet_connector = business_profile + .always_collect_billing_details_from_wallet_connector + .unwrap_or(false); + + if always_collect_billing_details_from_wallet_connector { + always_collect_billing_details_from_wallet_connector + } else if business_profile + .collect_billing_details_from_wallet_connector + .unwrap_or(false) + { + let billing_variants = enums::FieldType::get_billing_variants(); + + is_dynamic_fields_required( + &state.conf.required_fields, + enums::PaymentMethod::Wallet, + payment_method_type, + connector.connector_name, + billing_variants, + ) + } else { + false + } +} + +/// Function to determine whether the shipping address is required to be collected from the wallet, +/// based on business profile settings, the payment method type, and the connector required fields +/// for the specific payment method type. +/// +/// If `always_collect_shipping_details_from_wallet_connector` is enabled, it indicates that the +/// shipping address is always required to be collected from the wallet. +/// +/// If only `collect_shipping_details_from_wallet_connector` is enabled, the shipping address will be +/// collected only if the connector required fields for the specific payment method type contain +/// the shipping fields. +fn is_shipping_address_required_to_be_collected_form_wallet( + state: &routes::SessionState, + connector: &api::ConnectorData, + business_profile: &domain::Profile, + payment_method_type: enums::PaymentMethodType, +) -> bool { + let always_collect_shipping_details_from_wallet_connector = business_profile + .always_collect_shipping_details_from_wallet_connector + .unwrap_or(false); + + if always_collect_shipping_details_from_wallet_connector { + always_collect_shipping_details_from_wallet_connector + } else if business_profile + .collect_shipping_details_from_wallet_connector + .unwrap_or(false) + { + let shipping_variants = enums::FieldType::get_shipping_variants(); + + is_dynamic_fields_required( + &state.conf.required_fields, + enums::PaymentMethod::Wallet, + payment_method_type, + connector.connector_name, + shipping_variants, + ) + } else { + false + } +} + fn get_session_request_for_simplified_apple_pay( apple_pay_merchant_identifier: String, session_token_data: payment_types::SessionTokenForSimplifiedApplePay, @@ -865,27 +964,12 @@ fn create_gpay_session_token( ..router_data.clone() }) } else { - let always_collect_billing_details_from_wallet_connector = business_profile - .always_collect_billing_details_from_wallet_connector - .unwrap_or(false); - - let is_billing_details_required = if always_collect_billing_details_from_wallet_connector { - always_collect_billing_details_from_wallet_connector - } else if business_profile - .collect_billing_details_from_wallet_connector - .unwrap_or(false) - { - let billing_variants = enums::FieldType::get_billing_variants(); - is_dynamic_fields_required( - &state.conf.required_fields, - enums::PaymentMethod::Wallet, - enums::PaymentMethodType::GooglePay, - connector.connector_name, - billing_variants, - ) - } else { - false - }; + let is_billing_details_required = is_billing_address_required_to_be_collected_from_wallet( + state, + connector, + business_profile, + enums::PaymentMethodType::GooglePay, + ); let required_amount_type = StringMajorUnitForConnector; let google_pay_amount = required_amount_type @@ -904,29 +988,13 @@ fn create_gpay_session_token( total_price: google_pay_amount, }; - let always_collect_shipping_details_from_wallet_connector = business_profile - .always_collect_shipping_details_from_wallet_connector - .unwrap_or(false); - let required_shipping_contact_fields = - if always_collect_shipping_details_from_wallet_connector { - true - } else if business_profile - .collect_shipping_details_from_wallet_connector - .unwrap_or(false) - { - let shipping_variants = enums::FieldType::get_shipping_variants(); - - is_dynamic_fields_required( - &state.conf.required_fields, - enums::PaymentMethod::Wallet, - enums::PaymentMethodType::GooglePay, - connector.connector_name, - shipping_variants, - ) - } else { - false - }; + is_shipping_address_required_to_be_collected_form_wallet( + state, + connector, + business_profile, + enums::PaymentMethodType::GooglePay, + ); if connector_wallets_details.google_pay.is_some() { let gpay_data = router_data @@ -1199,9 +1267,13 @@ impl RouterDataSession for types::PaymentsSessionRouterData { api::GetToken::GpayMetadata => { create_gpay_session_token(state, self, connector, business_profile) } - api::GetToken::SamsungPayMetadata => { - create_samsung_pay_session_token(self, header_payload) - } + api::GetToken::SamsungPayMetadata => create_samsung_pay_session_token( + state, + self, + header_payload, + connector, + business_profile, + ), api::GetToken::ApplePayMetadata => { create_applepay_session_token( state,
2025-02-19T13:28:35Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pull request includes changes to enhance the handling of billing and shipping address requirements for Samsung Pay and Google Pay session tokens. The most important changes include adding new fields to the `SamsungPaySessionTokenResponse` struct, updating the `create_samsung_pay_session_token` function to include these new fields, and refactoring the code to use helper functions for determining address requirements. Enhancements to session token handling: * Added `billing_address_required` and `shipping_address_required` fields to the `SamsungPaySessionTokenResponse` struct. * Updated the `create_samsung_pay_session_token` function to include the new address requirement fields and refactored the logic to use helper functions for determining if billing and shipping addresses are required. Refactoring for address requirement determination: * Introduced the `is_billing_address_required_to_be_collected_from_wallet` and `is_shipping_address_required_to_be_collected_form_wallet` functions to encapsulate the logic for determining address requirements based on business profile settings and connector fields. * Refactored the `create_gpay_session_token` function to use the new helper functions for determining billing and shipping address requirements. ### 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). --> Collect the customer's address details from Samsung Pay during payment to enhance the customer experience ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a merchant connector account with the samsung pay enabled for it -> Create a payment with confirm false ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api-key' \ --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": "[email protected]", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "customer_id": "1739970997", "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_id": "pay_2B9WMNGYhzpVoUHGxvpS", "merchant_id": "merchant_1739965434", "status": "requires_payment_method", "amount": 6100, "net_amount": 6100, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_2B9WMNGYhzpVoUHGxvpS_secret_vQZZ2vDYnZJOUi8JDVdL", "created": "2025-02-19T13:16:04.153Z", "currency": "USD", "customer_id": "1739970964", "customer": { "id": "1739970964", "name": "Joseph Doe", "email": "[email protected]", "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": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": 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": "[email protected]", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": null, "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "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": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "1739970964", "created_at": 1739970964, "expires": 1739974564, "secret": "epk_40529c632d7946338b7ad09430a613e6" }, "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_2STAgRa16ISVgMLO11F2", "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": "2025-02-19T13:31:04.153Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-02-19T13:16:04.173Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null } ``` -> Set the below profile configuration ``` curl --location 'http://localhost:8080/account/merchant_1739965434/business_profile/pro_2STAgRa16ISVgMLO11F2' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api-key' \ --data '{ "collect_billing_details_from_wallet_connector": false, "collect_shipping_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": true, "always_collect_billing_details_from_wallet_connector": true, }' ``` ``` { "merchant_id": "merchant_1739965434", "profile_id": "pro_2STAgRa16ISVgMLO11F2", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "0txdls9EorK9Gzx1OYRGV0X9xS87pn5sUxfFHFlfq9endVIs7S1iqV5TnCsZUYD7", "redirect_to_merchant_with_http_post": false, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": null, "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "metadata": null, "routing_algorithm": null, "intent_fulfillment_time": 900, "frm_routing_algorithm": null, "payout_routing_algorithm": null, "applepay_verified_domains": null, "session_expiry": 900, "payment_link_config": null, "authentication_connector_details": null, "use_billing_as_payment_method_billing": true, "extended_card_info_config": null, "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": true, "always_collect_billing_details_from_wallet_connector": true, "is_connector_agnostic_mit_enabled": true, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false, "is_auto_retries_enabled": false, "max_auto_retries_enabled": null, "always_request_extended_authorization": null, "is_click_to_pay_enabled": false, "authentication_product_ids": null } ``` -> For this profile configuration the `shipping_address_required` and `billing_address_required` be true in the session resposne ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: api-key' \ --data '{ "payment_id": "pay_2B9WMNGYhzpVoUHGxvpS", "wallets": [], "client_secret": "pay_2B9WMNGYhzpVoUHGxvpS_secret_vQZZ2vDYnZJOUi8JDVdL" }' ``` ``` { "payment_id": "pay_2B9WMNGYhzpVoUHGxvpS", "client_secret": "pay_2B9WMNGYhzpVoUHGxvpS_secret_vQZZ2vDYnZJOUi8JDVdL", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": true, "email_required": true, "shipping_address_parameters": { "phone_number_required": true }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": true, "billing_address_parameters": { "phone_number_required": true, "format": "FULL" } }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "61.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "samsung_pay", "version": "2", "service_id": "49400558c67f4a97b3925f", "order_number": "pay-2B9WMNGYhzpVoUHGxvpS", "merchant": { "name": "Hyperswitch", "url": null, "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "61.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ], "billing_address_required": true, "shipping_address_required": true }, { "wallet_name": "apple_pay", "session_token_data": {}, "payment_request_data": { "country_code": "AU", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "61.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.sandbox.hyperswitch", "required_billing_contact_fields": [ "postalAddress" ], "required_shipping_contact_fields": [ "postalAddress", "phone", "email" ] }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ``` -> Set the below profile configuration ``` curl --location 'http://localhost:8080/account/merchant_1739965434/business_profile/pro_2STAgRa16ISVgMLO11F2' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api-key' \ --data '{ "collect_billing_details_from_wallet_connector": true, "collect_shipping_details_from_wallet_connector": true, "always_collect_shipping_details_from_wallet_connector": false, "always_collect_billing_details_from_wallet_connector": false, "is_connector_agnostic_mit_enabled": true }' ``` ``` { "merchant_id": "merchant_1739965434", "profile_id": "pro_2STAgRa16ISVgMLO11F2", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "0txdls9EorK9Gzx1OYRGV0X9xS87pn5sUxfFHFlfq9endVIs7S1iqV5TnCsZUYD7", "redirect_to_merchant_with_http_post": false, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": null, "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "metadata": null, "routing_algorithm": null, "intent_fulfillment_time": 900, "frm_routing_algorithm": null, "payout_routing_algorithm": null, "applepay_verified_domains": null, "session_expiry": 900, "payment_link_config": null, "authentication_connector_details": null, "use_billing_as_payment_method_billing": true, "extended_card_info_config": null, "collect_shipping_details_from_wallet_connector": true, "collect_billing_details_from_wallet_connector": true, "always_collect_shipping_details_from_wallet_connector": false, "always_collect_billing_details_from_wallet_connector": false, "is_connector_agnostic_mit_enabled": true, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false, "is_auto_retries_enabled": false, "max_auto_retries_enabled": null, "always_request_extended_authorization": null, "is_click_to_pay_enabled": false, "authentication_product_ids": null } ``` -> As per the above profile configuration the the `billing_address_required` will be `true` as the cybersource requires billing derails to be passed and `shipping_address_required` will be `false` as shipping details are not required by cybserourec. ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: api-key' \ --data '{ "payment_id": "pay_2B9WMNGYhzpVoUHGxvpS", "wallets": [], "client_secret": "pay_2B9WMNGYhzpVoUHGxvpS_secret_vQZZ2vDYnZJOUi8JDVdL" }' ``` ``` { "payment_id": "pay_2B9WMNGYhzpVoUHGxvpS", "client_secret": "pay_2B9WMNGYhzpVoUHGxvpS_secret_vQZZ2vDYnZJOUi8JDVdL", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": true, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": true, "billing_address_parameters": { "phone_number_required": true, "format": "FULL" } }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "61.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "samsung_pay", "version": "2", "service_id": "49400558c67f4a97b3925f", "order_number": "pay-2B9WMNGYhzpVoUHGxvpS", "merchant": { "name": "Hyperswitch", "url": null, "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "61.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ], "billing_address_required": true, "shipping_address_required": false }, { "wallet_name": "apple_pay", "session_token_data": {}, "payment_request_data": { "country_code": "AU", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "61.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.sandbox.hyperswitch", "required_billing_contact_fields": [ "postalAddress" ], "required_shipping_contact_fields": [ "phone", "email" ] }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.112.0
f3ca2009c1902094a72b8bf43e89b406e44ecfd4
f3ca2009c1902094a72b8bf43e89b406e44ecfd4
juspay/hyperswitch
juspay__hyperswitch-7328
Bug: [BUG] [DATATRANS] Add new payment status ### Bug Description For connector Datatrans new payment status need to be added: ChallengeOngoing and ChallengeRequired ### Expected Behavior ChallengeOngoing and ChallengeRequired status should be handled ### Actual Behavior ChallengeOngoing and ChallengeRequired not being handled ### 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 For connector Datatrans new payment status need to be added: ChallengeOngoing and ChallengeRequired ### 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/hyperswitch_connectors/src/connectors/datatrans/transformers.rs b/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs index 68daa3743bf..9297f783d3e 100644 --- a/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs @@ -129,7 +129,7 @@ pub struct SyncResponse { #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct SyncCardDetails { - pub alias: String, + pub alias: Option<String>, } #[derive(Serialize, Deserialize, Clone, Debug)] @@ -787,9 +787,12 @@ impl TryFrom<PaymentsSyncResponseRouterData<DatatransSyncResponse>> connector_transaction_id: None, }) } else { - let mandate_reference = - sync_response.card.as_ref().map(|card| MandateReference { - connector_mandate_id: Some(card.alias.clone()), + let mandate_reference = sync_response + .card + .as_ref() + .and_then(|card| card.alias.as_ref()) + .map(|alias| MandateReference { + connector_mandate_id: Some(alias.clone()), payment_method_id: None, mandate_metadata: None, connector_mandate_request_reference_id: None,
2025-02-20T15:27:59Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> For connector Datatrans add new payment status: ChallengeOngoing and ChallengeRequired Fix Deseralization Issue on Force Sync Flow ### 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/7328 ## 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 Create: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_pzCQPy1Bguc8j2kV8DQeqQJHIqJQJCjF5kLyDVep1qhmsjAPfl6GUbb10RId0cr8' \ --data-raw '{ "amount": 1000, "currency": "GBP", "amount_to_capture": 1000, "confirm": true, "capture_method": "manual", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_type": "credit", "email": "[email protected]", "payment_method_data": { "card": { "card_number": "5404000000000001", "card_exp_month": "06", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" }, "billing": { "email": "[email protected]" } } }' ``` Response: ``` { "payment_id": "pay_o5DC6PfvFD102tR0jAkC", "merchant_id": "merchant_1740052235", "status": "requires_capture", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "datatrans", "client_secret": "pay_o5DC6PfvFD102tR0jAkC_secret_aIwxbFdYcRA5QEzSwRH0", "created": "2025-02-20T12:54:31.835Z", "currency": "GBP", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "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": "0001", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "540400", "card_extended_bin": null, "card_exp_month": "06", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": { "address": null, "phone": null, "email": "[email protected]" } }, "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": "250220135432771618", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_u7haQkBn6S4w6TXz8EJH", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_2NXjPxtjXhySNn9Ui8bD", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-02-20T13:09:31.834Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-02-20T12:54:33.029Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual" } ``` Payments Intent: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_pzCQPy1Bguc8j2kV8DQeqQJHIqJQJCjF5kLyDVep1qhmsjAPfl6GUbb10RId0cr8' \ --data '{ "amount": 0, "currency": "GBP", "confirm": false, "setup_future_usage": "off_session", "customer_id": "tester1799" }' ``` Response: ``` { "payment_id": "pay_mLh13MuvuHd60YDrzoRJ", "merchant_id": "merchant_1740052235", "status": "requires_payment_method", "amount": 0, "net_amount": 0, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_mLh13MuvuHd60YDrzoRJ_secret_vG7S4ysL0mc0jQunux4v", "created": "2025-02-20T12:55:01.990Z", "currency": "GBP", "customer_id": "tester1799", "customer": { "id": "tester1799", "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": 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": "tester1799", "created_at": 1740056101, "expires": 1740059701, "secret": "epk_5f5f55938a5e4d4aa926cf0ebdfaac0a" }, "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_u7haQkBn6S4w6TXz8EJH", "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": "2025-02-20T13:10:01.990Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-02-20T12:55:02.018Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null } ``` Payments Confirm(Creating Mandate): Request: ``` curl --location 'http://localhost:8080/payments/pay_FW8L70XM5ECVgz0V0M4U/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_pzCQPy1Bguc8j2kV8DQeqQJHIqJQJCjF5kLyDVep1qhmsjAPfl6GUbb10RId0cr8' \ --data-raw '{ "payment_method": "card", "payment_method_type": "credit", "customer_acceptance": { "acceptance_type": "offline" }, "capture_method": "automatic", "authentication_type": "no_three_ds", "payment_method_data": { "card": { "card_number": "5404000000000001", "card_exp_month": "06", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" }, "billing": { "email": "[email protected]" } } }' ``` Response: ``` { "payment_id": "pay_mLh13MuvuHd60YDrzoRJ", "merchant_id": "merchant_1740052235", "status": "requires_customer_action", "amount": 0, "net_amount": 0, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "datatrans", "client_secret": "pay_mLh13MuvuHd60YDrzoRJ_secret_vG7S4ysL0mc0jQunux4v", "created": "2025-02-20T12:55:01.990Z", "currency": "GBP", "customer_id": "tester1799", "customer": { "id": "tester1799", "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": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0001", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "540400", "card_extended_bin": null, "card_exp_month": "06", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": { "address": null, "phone": null, "email": "[email protected]" } }, "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": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_mLh13MuvuHd60YDrzoRJ/merchant_1740052235/pay_mLh13MuvuHd60YDrzoRJ_1" }, "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": "250220135517601774", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_u7haQkBn6S4w6TXz8EJH", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_2NXjPxtjXhySNn9Ui8bD", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-02-20T13:10:01.990Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": "pm_wnpldY3cjI1hNd9eCdvV", "payment_method_status": "inactive", "updated": "2025-02-20T12:55:17.804Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual" } ``` Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_GSXcUmpO1O7kDsua577iUQXDZWOCT4dIMglCcbXzVpPrvujyDkm59ourkW6oOXbS' \ --data-raw '{ "amount": 1000, "currency": "GBP", "amount_to_capture": 1000, "confirm": true, "capture_method": "manual", "customer_id":"blajsh", "authentication_type": "no_three_ds", "setup_future_usage":"on_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "payment_method": "card", "payment_method_type": "credit", "email": "[email protected]", "payment_method_data": { "card": { "card_number": "5404000000000001", "card_exp_month": "06", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" }, "billing":{ "email":"[email protected]" } } }' ``` Response ``` { "payment_id": "pay_guOgcn7GmWiPeGXkZucP", "merchant_id": "postman_merchant_GHAction_ab9fae91-aff0-4a08-baae-194e61092bf6", "status": "requires_capture", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "datatrans", "client_secret": "pay_guOgcn7GmWiPeGXkZucP_secret_PUdAYdnPcNUscVt1NYqt", "created": "2025-02-20T15:12:52.832Z", "currency": "GBP", "customer_id": "blajsh", "customer": { "id": "blajsh", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "0001", "card_type": "DEBIT", "card_network": "Visa", "card_issuer": "MASTERCARD INTERNATIONAL", "card_issuing_country": "UNITEDSTATES", "card_isin": "540400", "card_extended_bin": null, "card_exp_month": "06", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": { "address": null, "phone": null, "email": "[email protected]" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "[email protected]", "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": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "blajsh", "created_at": 1740064372, "expires": 1740067972, "secret": "epk_dd3a6c0d4ead4f78bdec9a0b2b9ec12e" }, "manual_retry_allowed": false, "connector_transaction_id": "250220161253992987", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_HKMwd5SucLDtv5qWMf47", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_EZEmKXkvmX9nowH9gsty", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-02-20T15:27:52.832Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-02-20T15:12:54.206Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual" } ``` Force Sync (Request) ``` curl --location 'http://localhost:8080/payments/pay_guOgcn7GmWiPeGXkZucP?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_GSXcUmpO1O7kDsua577iUQXDZWOCT4dIMglCcbXzVpPrvujyDkm59ourkW6oOXbS' \ --data '' ``` Force Sync Response ``` { "payment_id": "pay_guOgcn7GmWiPeGXkZucP", "merchant_id": "postman_merchant_GHAction_ab9fae91-aff0-4a08-baae-194e61092bf6", "status": "requires_capture", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "datatrans", "client_secret": "pay_guOgcn7GmWiPeGXkZucP_secret_PUdAYdnPcNUscVt1NYqt", "created": "2025-02-20T15:12:52.832Z", "currency": "GBP", "customer_id": "blajsh", "customer": { "id": "blajsh", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "0001", "card_type": "DEBIT", "card_network": "Visa", "card_issuer": "MASTERCARD INTERNATIONAL", "card_issuing_country": "UNITEDSTATES", "card_isin": "540400", "card_extended_bin": null, "card_exp_month": "06", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": { "address": null, "phone": null, "email": "[email protected]" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "[email protected]", "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": "debit", "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": "250220161253992987", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_HKMwd5SucLDtv5qWMf47", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_EZEmKXkvmX9nowH9gsty", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-02-20T15:27:52.832Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_T4qWIKfShRUpJp0J6n3o", "payment_method_status": "active", "updated": "2025-02-20T15:14:43.581Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual" } ``` Note: Non-3DS transaction will redirect if we pass off_session https://docs.datatrans.ch/docs/tokenization ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.112.0
de865bd13440f965c0d3ffbe44a71925978212dd
de865bd13440f965c0d3ffbe44a71925978212dd
juspay/hyperswitch
juspay__hyperswitch-7323
Bug: docs: API-ref revamp for better user experience API-ref revamp for better user experience
diff --git a/api-reference/api-reference/payments/Introduction--to--payments.mdx b/api-reference/api-reference/payments/Introduction--to--payments.mdx new file mode 100644 index 00000000000..4cccc9cde2c --- /dev/null +++ b/api-reference/api-reference/payments/Introduction--to--payments.mdx @@ -0,0 +1,60 @@ +--- +tags: [Payments] +sidebarTitle: "Getting Started with Payments" +icon: "circle-play" +iconType: "solid" +color: "Green" +--- + +The **Hyperswitch Payments API** enables businesses to **accept, process, and manage payments seamlessly**. It supports the entire **payment lifecycle**—from creation to capture, refunds, and disputes—allowing smooth integration of **various payment methods** into any application with minimal complexity. + +### How to try your first payment through hyperswitch? +You have two options to use the Payments API: + +1. **Sandbox API Key (Dashboard)** – Quick testing without setup. +2. **Self-Deploy** – Create merchants and API keys through Rest API. + +Each option has specific nuances, we have mentioned the differences in the below step by step guide +<Tip>We recommend using our [Dashboard](https://app.hyperswitch.io/dashboard/login) to generate API Key and setting up Connectors (Step 4)</Tip> for faster trial and simple setup +<Steps> + <Step title="Create a Merchant Account"> + This account is representative of you or your organization that would like to accept payments from different <Tooltip tip="Can be a payment method or payment service provider">payment connectors</Tooltip> + <Steps> + <Step title="Hyperswitch Dashboard flow" icon= "box-open"> + Access the <Tooltip tip="Control Center is a frontend interface for the API to track and test payments">[Dashboard](https://app.hyperswitch.io/dashboard/login)</Tooltip> and sign up -> **Sign up here is equivalent to creating a Merchant Account** + </Step> + <Step title="Self-Deploy flow" icon="map-pin"> + Use the admin api key and the [Merchant Account - Create](api-reference/merchant-account/merchant-account--create) endpoint to create your Merchant Account + </Step> +</Steps> + </Step> + <Step title="Create API Key"> + You can now generate an API key that will be the secret key used to authenticate your payment request + <Steps> + <Step title="Hyperswitch Dashboard flow" icon= "box-open"> + In Dashboard go to Developer-> API Keys -> +Create New Api Key. This key can be used in your API requests for authentication. + </Step> + <Step title="Self-Deploy flow" icon="map-pin"> + Use the admin api key and the [Merchant Account - Create](api-reference/merchant-account/merchant-account--create) endpoint to create your Merchant Account + </Step> +</Steps> + </Step> + <Step title="Set up Connectors"> + Connect the payment [connectors](api-reference/merchant-connector-account/merchant-connector--create) and payment methods that your organization will accept. Connectors could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting + <Steps> + <Step title="Hyperswitch Dashboard flow" icon= "box-open"> + In Dashboard go to Connectors -> <Tooltip tip="Adding other connectors (eg. Adyen) will require you to go through their respective documentation">+Connect a Dummy Processor</Tooltip>. Choose the payments methods to enable and complete setup. + </Step> + <Step title="Self-Deploy flow" icon="map-pin"> + Use the admin api key and the [Connector Account](api-reference/merchant-connector-account/merchant-connector--create) endpoints to set up a connector + </Step> +</Steps> + </Step> + <Step title="Try your first payment"> + You are all set! Go ahead and try the [Payments API](api-reference/payments/payments--create), be sure to try the different use cases provided + </Step> + <Step title="We are here to help" icon="circle-info"> + Test the use cases you are interested in and in case of difficulty, feel free to contact us on our [slack channel](https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw) + </Step> +</Steps> +--- diff --git a/api-reference/api-reference/payments/payments--create.mdx b/api-reference/api-reference/payments/payments--create.mdx index 0b7038a4ea6..af436038731 100644 --- a/api-reference/api-reference/payments/payments--create.mdx +++ b/api-reference/api-reference/payments/payments--create.mdx @@ -1,3 +1,4 @@ --- openapi: openapi_spec post /payments ---- \ No newline at end of file +--- +<Tip> Use the dropdown on the top right corner of the code snippet to try out different payment scenarios. </Tip> \ No newline at end of file diff --git a/api-reference/introduction.mdx b/api-reference/introduction.mdx index 5f92f11fda2..2549b6c43a8 100644 --- a/api-reference/introduction.mdx +++ b/api-reference/introduction.mdx @@ -1,15 +1,32 @@ --- tags: [Getting Started] +title: "👋 Welcome to Hyperswitch API Reference" +sidebarTitle: "Introduction" stoplight-id: 3lmsk7ocvq21v +icon: "rectangle-code" +iconType: "solid" --- -# 👋 Welcome to Hyperswitch API Reference - Hyperswitch 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. You can consume the APIs directly using your favorite HTTP/REST library. +<CardGroup horizontal cols={2} row={3}> + <Card horizontal title="Try a Payment" href="api-reference/payments/Introduction--to--payments" icon="money-bill"> + Explore the versatile payments endpoint, through multiple test scenarios + </Card> + <Card horizontal title="Refund" href="api-reference/refunds/refunds--create" icon="receipt"> + Process refunds for completed payments using our API + </Card> + <Card horizontal title="Save a payment method" href="api-reference/payment-methods/paymentmethods--create" icon="vault"> + Save customer payment methods securely for future transactions + </Card> + <Card horizontal title="Self Hosted?" href="api-reference/organization/organization--create" icon="circle-down"> + Host Hyperswitch on-premise? Utilize our full API suite. + </Card> +</CardGroup> + ## Environment -We have a testing environment referred to "sandbox," which you can set up to test API calls without affecting production data. You can sign up on our Dashboard to get API keys to access Hyperswitch API. +We have a testing environment referred to <Tooltip tip="Testing environment!">"sandbox</Tooltip>," which you can set up to test API calls without affecting production data. You can sign up on our Dashboard to get API keys to access Hyperswitch API. Use the following base URLs when making requests to the APIs: diff --git a/api-reference/mint.json b/api-reference/mint.json index a134b3c5b2b..e74a8f1386a 100644 --- a/api-reference/mint.json +++ b/api-reference/mint.json @@ -5,6 +5,17 @@ "dark": "/logo/dark.svg", "light": "/logo/light.svg" }, + "topbarLinks": [ + { + "name": "Contact Us", + "url": "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw" + } + ], + "topbarCtaButton": { + "type": "link", + "url": "https://docs.hyperswitch.io/hyperswitch-open-source/overview", + "name": "Self-Deploy" + }, "favicon": "/favicon.png", "colors": { "primary": "#006DF9", @@ -14,6 +25,9 @@ "dark": "#242F48" } }, + "sidebar": { + "items": "card" + }, "tabs": [ { "name": "Locker API Reference", @@ -39,6 +53,7 @@ { "group": "Payments", "pages": [ + "api-reference/payments/Introduction--to--payments", "api-reference/payments/payments--create", "api-reference/payments/payments--update", "api-reference/payments/payments--confirm", @@ -101,54 +116,6 @@ "api-reference/disputes/disputes--list" ] }, - { - "group": "Organization", - "pages": [ - "api-reference/organization/organization--create", - "api-reference/organization/organization--retrieve", - "api-reference/organization/organization--update" - ] - }, - { - "group": "Merchant Account", - "pages": [ - "api-reference/merchant-account/merchant-account--create", - "api-reference/merchant-account/merchant-account--retrieve", - "api-reference/merchant-account/merchant-account--update", - "api-reference/merchant-account/merchant-account--delete", - "api-reference/merchant-account/merchant-account--kv-status" - ] - }, - { - "group": "Business Profile", - "pages": [ - "api-reference/business-profile/business-profile--create", - "api-reference/business-profile/business-profile--update", - "api-reference/business-profile/business-profile--retrieve", - "api-reference/business-profile/business-profile--delete", - "api-reference/business-profile/business-profile--list" - ] - }, - { - "group": "API Key", - "pages": [ - "api-reference/api-key/api-key--create", - "api-reference/api-key/api-key--retrieve", - "api-reference/api-key/api-key--update", - "api-reference/api-key/api-key--revoke", - "api-reference/api-key/api-key--list" - ] - }, - { - "group": "Merchant Connector Account", - "pages": [ - "api-reference/merchant-connector-account/merchant-connector--create", - "api-reference/merchant-connector-account/merchant-connector--retrieve", - "api-reference/merchant-connector-account/merchant-connector--update", - "api-reference/merchant-connector-account/merchant-connector--delete", - "api-reference/merchant-connector-account/merchant-connector--list" - ] - }, { "group": "Payouts", "pages": [ @@ -171,15 +138,6 @@ "api-reference/event/events--manual-retry" ] }, - { - "group": "GSM (Global Status Mapping)", - "pages": [ - "api-reference/gsm/gsm--create", - "api-reference/gsm/gsm--get", - "api-reference/gsm/gsm--update", - "api-reference/gsm/gsm--delete" - ] - }, { "group": "Poll", "pages": ["api-reference/poll/poll--retrieve-poll-status"] @@ -221,6 +179,76 @@ } ] }, + { + "group": "Admin API based", + "pages": [ + { + "group": "Organization", + "pages": [ + "api-reference/organization/organization--create", + "api-reference/organization/organization--retrieve", + "api-reference/organization/organization--update" + ] + }, + { + "group": "Merchant Account", + "pages": [ + "api-reference/merchant-account/merchant-account--create", + "api-reference/merchant-account/merchant-account--retrieve", + "api-reference/merchant-account/merchant-account--update", + "api-reference/merchant-account/merchant-account--delete", + "api-reference/merchant-account/merchant-account--kv-status" + ] + }, + { + "group": "Business Profile", + "pages": [ + "api-reference/business-profile/business-profile--create", + "api-reference/business-profile/business-profile--update", + "api-reference/business-profile/business-profile--retrieve", + "api-reference/business-profile/business-profile--delete", + "api-reference/business-profile/business-profile--list" + ] + }, + { + "group": "API Key", + "pages": [ + "api-reference/api-key/api-key--create", + "api-reference/api-key/api-key--retrieve", + "api-reference/api-key/api-key--update", + "api-reference/api-key/api-key--revoke", + "api-reference/api-key/api-key--list" + ] + }, + { + "group": "Merchant Connector Account", + "pages": [ + "api-reference/merchant-connector-account/merchant-connector--create", + "api-reference/merchant-connector-account/merchant-connector--retrieve", + "api-reference/merchant-connector-account/merchant-connector--update", + "api-reference/merchant-connector-account/merchant-connector--delete", + "api-reference/merchant-connector-account/merchant-connector--list" + ] + }, + { + "group": "GSM (Global Status Mapping)", + "pages": [ + "api-reference/gsm/gsm--create", + "api-reference/gsm/gsm--get", + "api-reference/gsm/gsm--update", + "api-reference/gsm/gsm--delete" + ] + }, + { + "group": "Event", + "pages": [ + "api-reference/event/events--list", + "api-reference/event/events--delivery-attempt-list", + "api-reference/event/events--manual-retry" + ] + } + ] + }, { "group": "Hyperswitch Card Vault", "pages": ["locker-api-reference/overview"] @@ -263,11 +291,9 @@ "analytics": { "gtm": { "tagId": "GTM-PLBNKQFQ" - } - }, - "analytics": { + }, "mixpanel": { "projectToken": "b00355f29d9548d1333608df71d5d53d" } } -} +} \ No newline at end of file
2025-02-20T09:28:47Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [X] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> We have changes the Intro page of the API-ref to make it more informative and navigable. Also, The API sidebar is now re-organised basis of different use-cases to improve the dev experience. Added an introduction page to payments API explaining all the scenarios an user can explore payment API. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #7323 ## 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="1140" alt="Screenshot 2025-02-20 at 5 55 09 PM" src="https://github.com/user-attachments/assets/9e979280-e081-48a0-b60e-33135d2461ec" /> <img width="1153" alt="Screenshot 2025-02-20 at 5 56 20 PM" src="https://github.com/user-attachments/assets/52f6adb1-3d5d-4ba7-99c9-3fdbadb2d4d4" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.112.0
74bbf4bf271d45e61e594857707250c95a86f43f
74bbf4bf271d45e61e594857707250c95a86f43f
juspay/hyperswitch
juspay__hyperswitch-7315
Bug: Implement the PaymentAuthorize, PaymentSync, Refund and RefundSync flows for Paystack Follow the steps outlined in the `add_connector.md` file. Implement the PaymentAuthorize, PaymentSync, Refund, RefundSync, and Webhooks flows for Paystack connector. Connector doc (Paystack): https://paystack.com/docs/payments/payment-channels/ - **Payment Authorize:** Authorize call to be made via Electronic Fund Transfer (payment method). Implement `impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paystack` to make Payment Authorize call. - **Payment Sync:** Implement `impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Paystack` in `paystack.rs` to make Payment Sync call. - **Refund:** Implement `impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paystack` in `paystack.rs` to make Refund call. - **RefundSync:** Implement `impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Paystack` in `paystack.rs` to make Refund Sync call. - **Webhooks:** There are two types of webhooks Payment, and Refund which to be implemented in `impl webhooks::IncomingWebhook for Paystack` in `paystack.rs` to receive the incoming webhooks sent by the connector. Modify the `get_headers()` and `get_url()` according to the connector documentation. Implement the Request and Response types and proper status mapping(Payment and Refund) in the `transformers.rs` file. Webhooks - Paystack sends a webhook with payment and refund status, we have to catch those and update in the db as well. Run the following commands before raising the PR - `cargo clippy` `cargo +nightly fmt --all` Ref PR: https://github.com/juspay/hyperswitch/pull/7286
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index b63c4eea2a1..1faac62d6c6 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -2846,6 +2846,14 @@ client_id="Client ID" api_key="Client Secret" key1="Client ID" +[paystack] +[[paystack.bank_redirect]] + payment_method_type = "eft" +[paystack.connector_auth.HeaderKey] +api_key="API Key" +[paystack.connector_webhook_details] +merchant_secret="API Key" + [payu] [[payu.credit]] payment_method_type = "Mastercard" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index a2e01c524e8..5123c66ea7e 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -2123,6 +2123,14 @@ merchant_secret="Source verification key" [paypal.metadata.paypal_sdk] client_id="Client ID" +[paystack] +[[paystack.bank_redirect]] + payment_method_type = "eft" +[paystack.connector_auth.HeaderKey] +api_key="API Key" +[paystack.connector_webhook_details] +merchant_secret="API Key" + [payu] [[payu.credit]] payment_method_type = "Mastercard" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 8084bd00b00..a036e6c4fbd 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -3955,6 +3955,14 @@ api_key="Api Key" [paypal_test.connector_auth.HeaderKey] api_key="Api Key" +[paystack] +[[paystack.bank_redirect]] + payment_method_type = "eft" +[paystack.connector_auth.HeaderKey] +api_key="API Key" +[paystack.connector_webhook_details] +merchant_secret="API Key" + [stripe_test] [[stripe_test.credit]] payment_method_type = "Mastercard" diff --git a/crates/hyperswitch_connectors/src/connectors/paystack.rs b/crates/hyperswitch_connectors/src/connectors/paystack.rs index a88b60cc210..6d6ce2ff83a 100644 --- a/crates/hyperswitch_connectors/src/connectors/paystack.rs +++ b/crates/hyperswitch_connectors/src/connectors/paystack.rs @@ -1,12 +1,13 @@ pub mod transformers; use common_utils::{ + crypto, errors::CustomResult, - ext_traits::BytesExt, + ext_traits::{ByteSliceExt, BytesExt}, request::{Method, Request, RequestBuilder, RequestContent}, - types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, + types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; -use error_stack::{report, ResultExt}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ @@ -43,13 +44,13 @@ use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Clone)] pub struct Paystack { - amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Paystack { pub fn new() -> &'static Self { &Self { - amount_converter: &StringMinorUnitForConnector, + amount_converter: &MinorUnitForConnector, } } } @@ -117,7 +118,7 @@ impl ConnectorCommon for Paystack { .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), - auth.api_key.expose().into_masked(), + format!("Bearer {}", auth.api_key.expose()).into_masked(), )]) } @@ -133,12 +134,13 @@ impl ConnectorCommon for Paystack { event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + let error_message = paystack::get_error_message(response.clone()); Ok(ErrorResponse { status_code: res.status_code, code: response.code, - message: response.message, - reason: response.reason, + message: error_message, + reason: Some(response.message), attempt_status: None, connector_transaction_id: None, }) @@ -176,9 +178,9 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData fn get_url( &self, _req: &PaymentsAuthorizeRouterData, - _connectors: &Connectors, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!("{}/charge", self.base_url(connectors))) } fn get_request_body( @@ -262,10 +264,20 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Pay fn get_url( &self, - _req: &PaymentsSyncRouterData, - _connectors: &Connectors, + req: &PaymentsSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let connector_payment_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + Ok(format!( + "{}{}{}", + self.base_url(connectors), + "/transaction/verify/", + connector_payment_id, + )) } fn build_request( @@ -289,7 +301,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Pay event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { - let response: paystack::PaystackPaymentsResponse = res + let response: paystack::PaystackPSyncResponse = res .response .parse_struct("paystack PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -406,9 +418,9 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paystac fn get_url( &self, _req: &RefundsRouterData<Execute>, - _connectors: &Connectors, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!("{}/refund", self.base_url(connectors))) } fn get_request_body( @@ -452,7 +464,7 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paystac event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { - let response: paystack::RefundResponse = res + let response: paystack::PaystackRefundsResponse = res .response .parse_struct("paystack RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -489,10 +501,20 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Paystack fn get_url( &self, - _req: &RefundSyncRouterData, - _connectors: &Connectors, + req: &RefundSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let connector_refund_id = req + .request + .connector_refund_id + .clone() + .ok_or(errors::ConnectorError::MissingConnectorRefundID)?; + Ok(format!( + "{}{}{}", + self.base_url(connectors), + "/refund/", + connector_refund_id, + )) } fn build_request( @@ -519,7 +541,7 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Paystack event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { - let response: paystack::RefundResponse = res + let response: paystack::PaystackRefundsResponse = res .response .parse_struct("paystack RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -543,25 +565,87 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Paystack #[async_trait::async_trait] impl webhooks::IncomingWebhook for Paystack { - fn get_webhook_object_reference_id( + fn get_webhook_source_verification_algorithm( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + Ok(Box::new(crypto::HmacSha512)) + } + + fn get_webhook_source_verification_signature( + &self, + request: &webhooks::IncomingWebhookRequestDetails<'_>, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let signature = utils::get_header_key_value("x-paystack-signature", request.headers) + .change_context(errors::ConnectorError::WebhookSignatureNotFound)?; + + hex::decode(signature) + .change_context(errors::ConnectorError::WebhookVerificationSecretInvalid) + } + + fn get_webhook_source_verification_message( + &self, + request: &webhooks::IncomingWebhookRequestDetails<'_>, + _merchant_id: &common_utils::id_type::MerchantId, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let message = std::str::from_utf8(request.body) + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + Ok(message.to_string().into_bytes()) + } + + fn get_webhook_object_reference_id( + &self, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let webhook_body = request + .body + .parse_struct::<paystack::PaystackWebhookData>("PaystackWebhookData") + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + match webhook_body.data { + paystack::PaystackWebhookEventData::Payment(data) => { + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId(data.reference), + )) + } + paystack::PaystackWebhookEventData::Refund(data) => { + Ok(api_models::webhooks::ObjectReferenceId::RefundId( + api_models::webhooks::RefundIdType::ConnectorRefundId(data.id), + )) + } + } } fn get_webhook_event_type( &self, - _request: &webhooks::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let webhook_body = request + .body + .parse_struct::<paystack::PaystackWebhookData>("PaystackWebhookData") + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + Ok(api_models::webhooks::IncomingWebhookEvent::from( + webhook_body.data, + )) } fn get_webhook_resource_object( &self, - _request: &webhooks::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let webhook_body = request + .body + .parse_struct::<paystack::PaystackWebhookData>("PaystackWebhookData") + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + Ok(match webhook_body.data { + paystack::PaystackWebhookEventData::Payment(payment_webhook_data) => { + Box::new(payment_webhook_data) + } + paystack::PaystackWebhookEventData::Refund(refund_webhook_data) => { + Box::new(refund_webhook_data) + } + }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs index 8a07997fbdc..2ced7d44d54 100644 --- a/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs @@ -1,30 +1,31 @@ -use common_enums::enums; -use common_utils::types::StringMinorUnit; +use common_enums::{enums, Currency}; +use common_utils::{pii::Email, request::Method, types::MinorUnit}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ - payment_method_data::PaymentMethodData, - router_data::{ConnectorAuthType, RouterData}, + payment_method_data::{BankRedirectData, PaymentMethodData}, + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; +use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::PaymentsAuthorizeRequestData, }; -//TODO: Fill the struct with respective fields pub struct PaystackRouterData<T> { - pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub amount: MinorUnit, pub router_data: T, } -impl<T> From<(StringMinorUnit, T)> for PaystackRouterData<T> { - fn from((amount, item): (StringMinorUnit, T)) -> Self { +impl<T> From<(MinorUnit, T)> for PaystackRouterData<T> { + fn from((amount, item): (MinorUnit, T)) -> Self { //Todo : use utils to convert the amount to the type of amount that a connector accepts Self { amount, @@ -33,20 +34,17 @@ impl<T> From<(StringMinorUnit, T)> for PaystackRouterData<T> { } } -//TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, PartialEq)] -pub struct PaystackPaymentsRequest { - amount: StringMinorUnit, - card: PaystackCard, +pub struct PaystackEftProvider { + provider: String, } -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct PaystackCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, +#[derive(Default, Debug, Serialize, PartialEq)] +pub struct PaystackPaymentsRequest { + amount: MinorUnit, + currency: Currency, + email: Email, + eft: PaystackEftProvider, } impl TryFrom<&PaystackRouterData<&PaymentsAuthorizeRouterData>> for PaystackPaymentsRequest { @@ -55,17 +53,14 @@ impl TryFrom<&PaystackRouterData<&PaymentsAuthorizeRouterData>> for PaystackPaym item: &PaystackRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(req_card) => { - let card = PaystackCard { - 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()?, - }; + PaymentMethodData::BankRedirect(BankRedirectData::Eft { provider }) => { + let email = item.router_data.request.get_email()?; + let eft = PaystackEftProvider { provider }; Ok(Self { - amount: item.amount.clone(), - card, + amount: item.amount, + currency: item.router_data.request.currency, + email, + eft, }) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), @@ -73,8 +68,6 @@ impl TryFrom<&PaystackRouterData<&PaymentsAuthorizeRouterData>> for PaystackPaym } } -//TODO: Fill the struct with respective fields -// Auth Struct pub struct PaystackAuthType { pub(super) api_key: Secret<String>, } @@ -90,139 +83,383 @@ impl TryFrom<&ConnectorAuthType> for PaystackAuthType { } } } -// PaymentsResponse -//TODO: Append the remaining status flags -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PaystackEftRedirect { + reference: String, + status: String, + url: String, +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PaystackPaymentsResponseData { + status: bool, + message: String, + data: PaystackEftRedirect, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(untagged)] +pub enum PaystackPaymentsResponse { + PaystackPaymentsData(PaystackPaymentsResponseData), + PaystackPaymentsError(PaystackErrorResponse), +} + +impl<F, T> TryFrom<ResponseRouterData<F, PaystackPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, PaystackPaymentsResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let (status, response) = match item.response { + PaystackPaymentsResponse::PaystackPaymentsData(resp) => { + let redirection_url = Url::parse(resp.data.url.as_str()) + .change_context(errors::ConnectorError::ParsingFailed)?; + let redirection_data = RedirectForm::from((redirection_url, Method::Get)); + ( + common_enums::AttemptStatus::AuthenticationPending, + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + resp.data.reference.clone(), + ), + redirection_data: Box::new(Some(redirection_data)), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charges: None, + }), + ) + } + PaystackPaymentsResponse::PaystackPaymentsError(err) => { + let err_msg = get_error_message(err.clone()); + ( + common_enums::AttemptStatus::Failure, + Err(ErrorResponse { + code: err.code, + message: err_msg.clone(), + reason: Some(err_msg.clone()), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, + }), + ) + } + }; + Ok(Self { + status, + response, + ..item.data + }) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] -pub enum PaystackPaymentStatus { - Succeeded, +pub enum PaystackPSyncStatus { + Abandoned, Failed, - #[default] + Ongoing, + Pending, Processing, + Queued, + Reversed, + Success, } -impl From<PaystackPaymentStatus> for common_enums::AttemptStatus { - fn from(item: PaystackPaymentStatus) -> Self { +impl From<PaystackPSyncStatus> for common_enums::AttemptStatus { + fn from(item: PaystackPSyncStatus) -> Self { match item { - PaystackPaymentStatus::Succeeded => Self::Charged, - PaystackPaymentStatus::Failed => Self::Failure, - PaystackPaymentStatus::Processing => Self::Authorizing, + PaystackPSyncStatus::Success => Self::Charged, + PaystackPSyncStatus::Abandoned => Self::AuthenticationPending, + PaystackPSyncStatus::Ongoing + | PaystackPSyncStatus::Pending + | PaystackPSyncStatus::Processing + | PaystackPSyncStatus::Queued => Self::Pending, + PaystackPSyncStatus::Failed => Self::Failure, + PaystackPSyncStatus::Reversed => Self::Voided, } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct PaystackPaymentsResponse { - status: PaystackPaymentStatus, - id: String, +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PaystackPSyncData { + status: PaystackPSyncStatus, + reference: String, } -impl<F, T> TryFrom<ResponseRouterData<F, PaystackPaymentsResponse, T, PaymentsResponseData>> +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PaystackPSyncResponseData { + status: bool, + message: String, + data: PaystackPSyncData, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(untagged)] +pub enum PaystackPSyncResponse { + PaystackPSyncData(PaystackPSyncResponseData), + PaystackPSyncWebhook(PaystackPaymentWebhookData), + PaystackPSyncError(PaystackErrorResponse), +} + +impl<F, T> TryFrom<ResponseRouterData<F, PaystackPSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: ResponseRouterData<F, PaystackPaymentsResponse, T, PaymentsResponseData>, + item: ResponseRouterData<F, PaystackPSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { - Ok(Self { - status: common_enums::AttemptStatus::from(item.response.status), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId(item.response.id), - redirection_data: Box::new(None), - mandate_reference: Box::new(None), - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: None, - incremental_authorization_allowed: None, - charges: None, + match item.response { + PaystackPSyncResponse::PaystackPSyncData(resp) => Ok(Self { + status: common_enums::AttemptStatus::from(resp.data.status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(resp.data.reference.clone()), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data }), - ..item.data - }) + PaystackPSyncResponse::PaystackPSyncWebhook(resp) => Ok(Self { + status: common_enums::AttemptStatus::from(resp.status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(resp.reference.clone()), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }), + PaystackPSyncResponse::PaystackPSyncError(err) => { + let err_msg = get_error_message(err.clone()); + Ok(Self { + response: Err(ErrorResponse { + code: err.code, + message: err_msg.clone(), + reason: Some(err_msg.clone()), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, + }), + ..item.data + }) + } + } } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct PaystackRefundRequest { - pub amount: StringMinorUnit, + pub transaction: String, + pub amount: MinorUnit, } impl<F> TryFrom<&PaystackRouterData<&RefundsRouterData<F>>> for PaystackRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &PaystackRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { + transaction: item.router_data.request.connector_transaction_id.clone(), amount: item.amount.to_owned(), }) } } -// Type definition for Refund Response - -#[allow(dead_code)] -#[derive(Debug, Serialize, Default, Deserialize, Clone)] -pub enum RefundStatus { - Succeeded, +#[derive(Debug, Serialize, Default, Deserialize, Clone, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum PaystackRefundStatus { + Processed, Failed, #[default] Processing, + Pending, } -impl From<RefundStatus> for enums::RefundStatus { - fn from(item: RefundStatus) -> Self { +impl From<PaystackRefundStatus> for enums::RefundStatus { + fn from(item: PaystackRefundStatus) -> Self { match item { - RefundStatus::Succeeded => Self::Success, - RefundStatus::Failed => Self::Failure, - RefundStatus::Processing => Self::Pending, - //TODO: Review mapping + PaystackRefundStatus::Processed => Self::Success, + PaystackRefundStatus::Failed => Self::Failure, + PaystackRefundStatus::Processing | PaystackRefundStatus::Pending => Self::Pending, } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize)] -pub struct RefundResponse { - id: String, - status: RefundStatus, +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PaystackRefundsData { + status: PaystackRefundStatus, + id: i64, +} + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PaystackRefundsResponseData { + status: bool, + message: String, + data: PaystackRefundsData, } -impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(untagged)] +pub enum PaystackRefundsResponse { + PaystackRefundsData(PaystackRefundsResponseData), + PaystackRSyncWebhook(PaystackRefundWebhookData), + PaystackRefundsError(PaystackErrorResponse), +} + +impl TryFrom<RefundsResponseRouterData<Execute, PaystackRefundsResponse>> + for RefundsRouterData<Execute> +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: RefundsResponseRouterData<Execute, RefundResponse>, + item: RefundsResponseRouterData<Execute, PaystackRefundsResponse>, ) -> Result<Self, Self::Error> { - Ok(Self { - response: Ok(RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + match item.response { + PaystackRefundsResponse::PaystackRefundsData(resp) => Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: resp.data.id.to_string(), + refund_status: enums::RefundStatus::from(resp.data.status), + }), + ..item.data }), - ..item.data - }) + PaystackRefundsResponse::PaystackRSyncWebhook(resp) => Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: resp.id, + refund_status: enums::RefundStatus::from(resp.status), + }), + ..item.data + }), + PaystackRefundsResponse::PaystackRefundsError(err) => { + let err_msg = get_error_message(err.clone()); + Ok(Self { + response: Err(ErrorResponse { + code: err.code, + message: err_msg.clone(), + reason: Some(err_msg.clone()), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, + }), + ..item.data + }) + } + } } } -impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { +impl TryFrom<RefundsResponseRouterData<RSync, PaystackRefundsResponse>> + for RefundsRouterData<RSync> +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: RefundsResponseRouterData<RSync, RefundResponse>, + item: RefundsResponseRouterData<RSync, PaystackRefundsResponse>, ) -> Result<Self, Self::Error> { - Ok(Self { - response: Ok(RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + match item.response { + PaystackRefundsResponse::PaystackRefundsData(resp) => Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: resp.data.id.to_string(), + refund_status: enums::RefundStatus::from(resp.data.status), + }), + ..item.data }), - ..item.data - }) + PaystackRefundsResponse::PaystackRSyncWebhook(resp) => Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: resp.id, + refund_status: enums::RefundStatus::from(resp.status), + }), + ..item.data + }), + PaystackRefundsResponse::PaystackRefundsError(err) => { + let err_msg = get_error_message(err.clone()); + Ok(Self { + response: Err(ErrorResponse { + code: err.code, + message: err_msg.clone(), + reason: Some(err_msg.clone()), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, + }), + ..item.data + }) + } + } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct PaystackErrorResponse { - pub status_code: u16, - pub code: String, + pub status: bool, pub message: String, - pub reason: Option<String>, + pub data: Option<serde_json::Value>, + pub meta: serde_json::Value, + pub code: String, +} + +pub fn get_error_message(response: PaystackErrorResponse) -> String { + if let Some(serde_json::Value::Object(err_map)) = response.data { + err_map.get("message").map(|msg| msg.clone().to_string()) + } else { + None + } + .unwrap_or(response.message) +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +pub struct PaystackPaymentWebhookData { + pub status: PaystackPSyncStatus, + pub reference: String, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +pub struct PaystackRefundWebhookData { + pub status: PaystackRefundStatus, + pub id: String, + pub transaction_reference: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(untagged)] +pub enum PaystackWebhookEventData { + Payment(PaystackPaymentWebhookData), + Refund(PaystackRefundWebhookData), +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +pub struct PaystackWebhookData { + pub event: String, + pub data: PaystackWebhookEventData, +} + +impl From<PaystackWebhookEventData> for api_models::webhooks::IncomingWebhookEvent { + fn from(item: PaystackWebhookEventData) -> Self { + match item { + PaystackWebhookEventData::Payment(payment_data) => match payment_data.status { + PaystackPSyncStatus::Success => Self::PaymentIntentSuccess, + PaystackPSyncStatus::Failed => Self::PaymentIntentFailure, + PaystackPSyncStatus::Abandoned + | PaystackPSyncStatus::Ongoing + | PaystackPSyncStatus::Pending + | PaystackPSyncStatus::Processing + | PaystackPSyncStatus::Queued => Self::PaymentIntentProcessing, + PaystackPSyncStatus::Reversed => Self::EventNotSupported, + }, + PaystackWebhookEventData::Refund(refund_data) => match refund_data.status { + PaystackRefundStatus::Processed => Self::RefundSuccess, + PaystackRefundStatus::Failed => Self::RefundFailure, + PaystackRefundStatus::Processing | PaystackRefundStatus::Pending => { + Self::EventNotSupported + } + }, + } + } }
2025-03-06T08:07:22Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Paystack EFT flow (Payments, PSync, Refunds, RSync, Webhooks). ### 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. Merchant Account Create: ``` 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_1739960795", "locker_id": "m0010", "merchant_name": "NewAge Retailer", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "[email protected]", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "[email protected]", "secondary_phone": "cillum do dolor id", "website": "https://www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "food" } ] }' ``` 2. API Key Create: ``` curl --location 'http://localhost:8080/api_keys/merchant_1739898797' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": "API Key 1", "description": null, "expiration": "2025-09-23T01:02:03.000Z" }' ``` 3. Paystack Connector Create: ``` curl --location 'http://localhost:8080/account/merchant_1739898797/connectors?=' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "paystack", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "abc" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "eft", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false } ] } ], "connector_webhook_details": { "merchant_secret": "abc", "additional_secret": null } }' ``` 4. Payments Create: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ykM0z3Y0k65EtZIce9BsbJXPtoq7KzcAWsLZUS3SIT13cdYEOQQ4mMkb4UMB5Oyd' \ --data-raw '{ "amount": 6540, "currency": "ZAR", "confirm": true, "amount_to_capture": 6540, "customer_id": "StripbmnxeCustomer", "email": "[email protected]", "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "bank_redirect", "payment_method_type": "eft", "payment_method_data": { "bank_redirect": { "eft": { "provider": "ozow" } } } }' ``` Response: ``` { "payment_id": "pay_kQrdGr1rVMmwEKYXorLM", "merchant_id": "merchant_1739898797", "status": "requires_customer_action", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 6540, "amount_received": null, "connector": "paystack", "client_secret": "pay_kQrdGr1rVMmwEKYXorLM_secret_U7lStVK9TuKNY4l0mxmc", "created": "2025-02-19T10:32:31.775Z", "currency": "ZAR", "customer_id": "StripbmnxeCustomer", "customer": { "id": "StripbmnxeCustomer", "name": null, "email": "[email protected]", "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": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "bank_redirect", "payment_method_data": { "bank_redirect": { "type": "BankRedirectResponse", "bank_name": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "[email protected]", "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_kQrdGr1rVMmwEKYXorLM/merchant_1739898797/pay_kQrdGr1rVMmwEKYXorLM_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "eft", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripbmnxeCustomer", "created_at": 1739961151, "expires": 1739964751, "secret": "epk_09592792e8504aa3a943feff38c3e3e2" }, "manual_retry_allowed": null, "connector_transaction_id": "sug0jyf5kbbbpe5", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_z5wMP3CJUUrMDF5CBGl9", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_Ux3UO8AL0iD9BlzLSE83", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-02-19T10:47:31.774Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-02-19T10:32:32.739Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` 5. Payments Retrieve Request: ``` curl --location 'http://localhost:8080/payments/pay_kWVz157PfvGL9GyAiTnI?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_ykM0z3Y0k65EtZIce9BsbJXPtoq7KzcAWsLZUS3SIT13cdYEOQQ4mMkb4UMB5Oyd' \ --data '' ``` Response: Same as payments response> 6. Refunds Create Request: ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ykM0z3Y0k65EtZIce9BsbJXPtoq7KzcAWsLZUS3SIT13cdYEOQQ4mMkb4UMB5Oyd' \ --data '{ "payment_id": "pay_6Ww3WmcWCT8ni7O5K5gV", "amount": 1000, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response: ``` { "refund_id": "ref_XSsCj6O6bujAZypJAFJk", "payment_id": "pay_6Ww3WmcWCT8ni7O5K5gV", "amount": 1000, "currency": "ZAR", "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, "unified_code": null, "unified_message": null, "created_at": "2025-02-19T10:31:32.658Z", "updated_at": "2025-02-19T10:31:34.094Z", "connector": "paystack", "profile_id": "pro_z5wMP3CJUUrMDF5CBGl9", "merchant_connector_id": "mca_Ux3UO8AL0iD9BlzLSE83", "split_refunds": null } ``` 7. Refunds Retrieve Request: ``` curl --location 'http://localhost:8080/refunds/ref_XSsCj6O6bujAZypJAFJk' \ --header 'Accept: application/json' \ --header 'api-key: dev_ZgTXlFsnanc0o4AW2Ag32dJQsA1rAvU1prQVsIE0JbUjPv7g65ZU5pO7MyiPLL5J' ``` Response: Same as Refunds response. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
13a274909962872f1d663d082af33fc44205d419
13a274909962872f1d663d082af33fc44205d419
juspay/hyperswitch
juspay__hyperswitch-7318
Bug: [V2]: Return connector specific customer reference ID in `CustomerResponse` Required for tokenization flows in some connectors
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index d93208fb665..67725d8c644 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -8833,6 +8833,11 @@ "maxLength": 64, "minLength": 1 }, + "connector_customer_ids": { + "type": "object", + "description": "Connector specific customer reference ids", + "nullable": true + }, "name": { "type": "string", "description": "The customer's name", diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index 2b84c50bba9..f89558e6267 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -17,7 +17,7 @@ olap = [] openapi = ["common_enums/openapi", "olap", "recon", "dummy_connector", "olap"] recon = [] v1 = ["common_utils/v1"] -v2 = ["common_utils/v2", "customer_v2"] +v2 = ["common_types/v2", "common_utils/v2", "customer_v2"] customer_v2 = ["common_utils/customer_v2"] payment_methods_v2 = ["common_utils/payment_methods_v2"] dynamic_routing = [] diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs index d78564ae53a..eb61cae6e47 100644 --- a/crates/api_models/src/customers.rs +++ b/crates/api_models/src/customers.rs @@ -182,6 +182,9 @@ pub struct CustomerResponse { /// The identifier for the customer object #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_reference_id: Option<id_type::CustomerId>, + /// Connector specific customer reference ids + #[schema(value_type = Option<Object>, example = json!({"mca_hwySG2NtpzX0qr7toOy8": "cus_Rnm2pDKGyQi506"}))] + pub connector_customer_ids: Option<common_types::customers::ConnectorCustomerMap>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: crypto::OptionalEncryptableName, diff --git a/crates/common_types/src/customers.rs b/crates/common_types/src/customers.rs new file mode 100644 index 00000000000..1d53630cade --- /dev/null +++ b/crates/common_types/src/customers.rs @@ -0,0 +1,30 @@ +//! Customer related types + +/// HashMap containing MerchantConnectorAccountId and corresponding customer id +#[cfg(feature = "v2")] +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize, diesel::AsExpression)] +#[diesel(sql_type = diesel::sql_types::Jsonb)] +#[serde(transparent)] +pub struct ConnectorCustomerMap( + std::collections::HashMap<common_utils::id_type::MerchantConnectorAccountId, String>, +); + +#[cfg(feature = "v2")] +common_utils::impl_to_sql_from_sql_json!(ConnectorCustomerMap); + +#[cfg(feature = "v2")] +impl std::ops::Deref for ConnectorCustomerMap { + type Target = + std::collections::HashMap<common_utils::id_type::MerchantConnectorAccountId, String>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +#[cfg(feature = "v2")] +impl std::ops::DerefMut for ConnectorCustomerMap { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} diff --git a/crates/common_types/src/lib.rs b/crates/common_types/src/lib.rs index 6139ddff16a..8c4ee162a76 100644 --- a/crates/common_types/src/lib.rs +++ b/crates/common_types/src/lib.rs @@ -2,6 +2,7 @@ #![warn(missing_docs, missing_debug_implementations)] +pub mod customers; pub mod domain; pub mod payment_methods; pub mod payments; diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs index b0d4535ddb7..24fe34c15d9 100644 --- a/crates/diesel_models/src/customers.rs +++ b/crates/diesel_models/src/customers.rs @@ -76,7 +76,7 @@ pub struct CustomerNew { pub description: Option<Description>, pub created_at: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, - pub connector_customer: Option<ConnectorCustomerMap>, + pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>, pub modified_at: PrimitiveDateTime, pub default_payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>, pub updated_by: Option<String>, @@ -158,7 +158,7 @@ pub struct Customer { pub description: Option<Description>, pub created_at: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, - pub connector_customer: Option<ConnectorCustomerMap>, + pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>, pub modified_at: PrimitiveDateTime, pub default_payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>, pub updated_by: Option<String>, @@ -236,7 +236,7 @@ pub struct CustomerUpdateInternal { pub phone_country_code: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: PrimitiveDateTime, - pub connector_customer: Option<ConnectorCustomerMap>, + pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>, pub default_payment_method_id: Option<Option<common_utils::id_type::GlobalPaymentMethodId>>, pub updated_by: Option<String>, pub default_billing_address: Option<Encryption>, @@ -283,31 +283,3 @@ impl CustomerUpdateInternal { } } } - -#[cfg(all(feature = "v2", feature = "customer_v2"))] -#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize, diesel::AsExpression)] -#[diesel(sql_type = diesel::sql_types::Jsonb)] -#[serde(transparent)] -pub struct ConnectorCustomerMap( - std::collections::HashMap<common_utils::id_type::MerchantConnectorAccountId, String>, -); - -#[cfg(all(feature = "v2", feature = "customer_v2"))] -common_utils::impl_to_sql_from_sql_json!(ConnectorCustomerMap); - -#[cfg(all(feature = "v2", feature = "customer_v2"))] -impl std::ops::Deref for ConnectorCustomerMap { - type Target = - std::collections::HashMap<common_utils::id_type::MerchantConnectorAccountId, String>; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -#[cfg(all(feature = "v2", feature = "customer_v2"))] -impl std::ops::DerefMut for ConnectorCustomerMap { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs index 02c25d722c1..384bc5ab427 100644 --- a/crates/hyperswitch_domain_models/src/customer.rs +++ b/crates/hyperswitch_domain_models/src/customer.rs @@ -56,7 +56,7 @@ pub struct Customer { pub description: Option<Description>, pub created_at: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, - pub connector_customer: Option<diesel_models::ConnectorCustomerMap>, + pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>, pub modified_at: PrimitiveDateTime, pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>, pub updated_by: Option<String>, @@ -334,7 +334,7 @@ pub struct CustomerGeneralUpdate { pub description: Option<Description>, pub phone_country_code: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, - pub connector_customer: Box<Option<diesel_models::ConnectorCustomerMap>>, + pub connector_customer: Box<Option<common_types::customers::ConnectorCustomerMap>>, pub default_billing_address: Option<Encryption>, pub default_shipping_address: Option<Encryption>, pub default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>, @@ -346,7 +346,7 @@ pub struct CustomerGeneralUpdate { pub enum CustomerUpdate { Update(Box<CustomerGeneralUpdate>), ConnectorCustomer { - connector_customer: Option<diesel_models::ConnectorCustomerMap>, + connector_customer: Option<common_types::customers::ConnectorCustomerMap>, }, UpdateDefaultPaymentMethod { default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>, diff --git a/crates/router/src/types/api/customers.rs b/crates/router/src/types/api/customers.rs index 5b37fb2add6..63ebfe49930 100644 --- a/crates/router/src/types/api/customers.rs +++ b/crates/router/src/types/api/customers.rs @@ -50,6 +50,7 @@ impl ForeignFrom<customer::Customer> for CustomerResponse { customers::CustomerResponse { id: cust.id, merchant_reference_id: cust.merchant_reference_id, + connector_customer_ids: cust.connector_customer, name: cust.name, email: cust.email, phone: cust.phone,
2025-02-19T12:31:39Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add a field `connector_customer` to `CustomerResponse` that contains a map between `MerchantConnectorAccountId` and connector customer id ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> From #7246: > with respect to the multi-use tokens that were created with Stripe (support added in #7106), the payment methods were created on Stripe's end, but were not associated with a customer, due to which they could not be used to make transactions again, we used to receive such an error: ```text The provided PaymentMethod cannot be attached. To reuse a PaymentMethod, you must attach it to a Customer first. ``` > To address this, we have to create a customer on Stripe's end first, and then pass Stripe's customer ID when saving the payment method with Stripe. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Request: ``` curl --location 'http://localhost:8080/v2/customers/12345_cus_01951dbc16d57d03ac193a7e297d4899' \ --header 'x-profile-id: pro_Vb32qOaqvkJClXH7aNWK' \ --header 'Authorization: api-key=dev_f4mNrhkUeCtLcsqUaG1fpzHpqTCnPdJMBSPNZAP2nWwwr7FRYtbj1RUdWBPKBKZ0' \ --header 'api-key: dev_f4mNrhkUeCtLcsqUaG1fpzHpqTCnPdJMBSPNZAP2nWwwr7FRYtbj1RUdWBPKBKZ0' ``` - Response: ```json { "id": "12345_cus_01951dbc16d57d03ac193a7e297d4899", "merchant_reference_id": "customer_1739960621", "connector_customer": { "mca_hwySG2NtpzX0qr7toOy8": "cus_Rnm2pDKGyQi506" }, "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "default_billing_address": null, "default_shipping_address": null, "created_at": "2025-02-19T10:23:40.758Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
ba3ad87e06d63910d78fdb217db47064b4d926be
ba3ad87e06d63910d78fdb217db47064b4d926be
juspay/hyperswitch
juspay__hyperswitch-7316
Bug: Integrate EFT into Hyperswitch SDK ## Description EFT is a bank redirect payment method. This issue involves adding EFT as a payment method in the Hyperswitch SDK. ## Implementation Steps - **`PaymentDetails.res`** Define EFT as a payment method by specifying its type, icon, and display name. - **`PaymentMethodsRecord.res`** Add EFT to `paymentMethodsFields`. - **`PaymentModeType.res`** - Add EFT as a `payment` type. - Map the `"eft"` string to EFT in `paymentMode`. - Include EFT in `defaultOrder` to display payment options in a specific sequence. T in `paymentMode` and add EFT in `defaultOrder` to display payment options to users in a specific sequence. - **`PaymentBody.res`** Generate a JSON structure for the "EFT" payment method using a provider name. Provider name can be taken from the SDK but for now we can provide Provider name in the code itself as `ozow`. - **`PaymentUtils.res`** Add EFT as a bank payment method type. ## How to test: 1. Set up the Hyperswitch Backend locally using this [documentation](https://github.com/juspay/hyperswitch/blob/main/docs/try_local_system.md). 2. Use the cURL commands provided in this [PR](https://github.com/juspay/hyperswitch/pull/7286) in Postman to: - Set up a merchant account - Generate Hyperswitch API keys - Create a Paystack connector 3. Setup Hyperswitch SDK locally using this [documentation](https://github.com/juspay/hyperswitch-web/blob/main/README.md#%EF%B8%8F-try-it-in-local) 4. Run the application on `localhost`, initiate a payment, and manually test EFT by clicking the **Pay Now** button. **Note:** Run the `npm run re:build` command before raising the PR
diff --git a/connector-template/mod.rs b/connector-template/mod.rs index 80330a97429..75f2f02c027 100644 --- a/connector-template/mod.rs +++ b/connector-template/mod.rs @@ -1,7 +1,6 @@ mod transformers; use std::fmt::Debug; -use common_utils::errors::ReportSwitchExt; use error_stack::{ResultExt, IntoReport}; use crate::{ diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs index 985c68a99c0..7e3caf100e1 100644 --- a/connector-template/transformers.rs +++ b/connector-template/transformers.rs @@ -30,7 +30,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for {{project-name | downcase expiry_month: req_card.card_exp_month, expiry_year: req_card.card_exp_year, cvc: req_card.card_cvc, - complete: item.request.is_auto_capture(), + complete: item.request.is_auto_capture()?, }; Ok(Self { amount: item.request.amount,
2023-04-18T16:43:29Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> When `add_connector.sh` is called to generate new connector files `mod.rs` had an unused declaration, removed it. At the time of development, if needed, one can import it directly instead of pre-bloating the stuff. `Transformers.rs` straight away failed and threw an error addressing `mismatched types` as it is expecting `bool` while were providing `Result<bool, Error>`. ### Additional Changes - [ ] 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` --> connector-template/mod.rs connector-template/transformers.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 its an obvious bug or documentation fix that will have little conversation). --> With the changes made, unexpected errors and warnings at the time of generation of connector code is avoided and addressed. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
v0.5.7
9c9c52f9af74ebc7e835a5750dd05967b39a0ade
9c9c52f9af74ebc7e835a5750dd05967b39a0ade
juspay/hyperswitch
juspay__hyperswitch-7314
Bug: Generating the Template Code for Paystack using add_connector script Follow the steps outlined in the [add_connector.md](https://github.com/juspay/hyperswitch/blob/main/add_connector.md) file. Execute the script provided in the markdown file with Connector name(eg: Paystack) and Connector base url. This will add respective code to add the specific connector in `hyperswitch_connector` crate. - Do the changes according to the document in the files. Then run the following commands: - `cargo clippy` - `cargo +nightly fmt --all` Afterward, review the code and raise a pull request (PR). Ref PR: https://github.com/juspay/hyperswitch/pull/7285
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index f81eca420a0..93e95761d09 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -7433,6 +7433,7 @@ "payme", "payone", "paypal", + "paystack", "payu", "placetopay", "powertranz", @@ -20037,6 +20038,7 @@ "payme", "payone", "paypal", + "paystack", "payu", "placetopay", "powertranz", diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 56ade32524b..5810779126a 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -9623,6 +9623,7 @@ "payme", "payone", "paypal", + "paystack", "payu", "placetopay", "powertranz", @@ -24544,6 +24545,7 @@ "payme", "payone", "paypal", + "paystack", "payu", "placetopay", "powertranz", diff --git a/config/config.example.toml b/config/config.example.toml index 3457d330c9a..0ec70721cb0 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -247,6 +247,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/" payme.base_url = "https://sandbox.payme.io/" payone.base_url = "https://payment.preprod.payone.com/" paypal.base_url = "https://api-m.sandbox.paypal.com/" +paystack.base_url = "https://api.paystack.co" payu.base_url = "https://secure.snd.payu.com/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" @@ -330,6 +331,7 @@ cards = [ "mollie", "moneris", "paypal", + "paystack", "shift4", "square", "stax", diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 079134e6d03..033b19cadea 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -92,6 +92,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/" payme.base_url = "https://sandbox.payme.io/" payone.base_url = "https://payment.preprod.payone.com/" paypal.base_url = "https://api-m.sandbox.paypal.com/" +paystack.base_url = "https://api.paystack.co" payu.base_url = "https://secure.snd.payu.com/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 79ed26906ef..5b3360d64b7 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -96,6 +96,7 @@ payeezy.base_url = "https://api.payeezy.com/" payme.base_url = "https://live.payme.io/" payone.base_url = "https://payment.payone.com/" paypal.base_url = "https://api-m.paypal.com/" +paystack.base_url = "https://api.paystack.co" payu.base_url = "https://secure.payu.com/api/" placetopay.base_url = "https://checkout.placetopay.com/rest/gateway" plaid.base_url = "https://production.plaid.com" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index a92deafb20a..6203b9393ee 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -96,6 +96,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/" payme.base_url = "https://sandbox.payme.io/" payone.base_url = "https://payment.preprod.payone.com/" paypal.base_url = "https://api-m.sandbox.paypal.com/" +paystack.base_url = "https://api.paystack.co" payu.base_url = "https://secure.snd.payu.com/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" diff --git a/config/development.toml b/config/development.toml index 13ed82c81f6..ce4f24edaac 100644 --- a/config/development.toml +++ b/config/development.toml @@ -198,6 +198,7 @@ cards = [ "payme", "payone", "paypal", + "paystack", "payu", "placetopay", "plaid", @@ -317,6 +318,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/" payme.base_url = "https://sandbox.payme.io/" payone.base_url = "https://payment.preprod.payone.com/" paypal.base_url = "https://api-m.sandbox.paypal.com/" +paystack.base_url = "https://api.paystack.co" payu.base_url = "https://secure.snd.payu.com/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 0031c37f022..6d7c88a9c62 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -179,6 +179,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/" payme.base_url = "https://sandbox.payme.io/" payone.base_url = "https://payment.preprod.payone.com/" paypal.base_url = "https://api-m.sandbox.paypal.com/" +paystack.base_url = "https://api.paystack.co" payu.base_url = "https://secure.snd.payu.com/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" @@ -279,6 +280,7 @@ cards = [ "payme", "payone", "paypal", + "paystack", "payu", "placetopay", "plaid", diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index c52bb6816d7..3e13cb8a820 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -109,6 +109,7 @@ pub enum RoutableConnectors { Payme, Payone, Paypal, + Paystack, Payu, Placetopay, Powertranz, @@ -250,6 +251,7 @@ pub enum Connector { Payme, Payone, Paypal, + Paystack, Payu, Placetopay, Powertranz, @@ -397,6 +399,7 @@ impl Connector { | Self::Payme | Self::Payone | Self::Paypal + | Self::Paystack | Self::Payu | Self::Placetopay | Self::Powertranz @@ -527,6 +530,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Payme => Self::Payme, RoutableConnectors::Payone => Self::Payone, RoutableConnectors::Paypal => Self::Paypal, + RoutableConnectors::Paystack => Self::Paystack, RoutableConnectors::Payu => Self::Payu, RoutableConnectors::Placetopay => Self::Placetopay, RoutableConnectors::Powertranz => Self::Powertranz, diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 2d1d2e4ede8..7134f5c5d34 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -219,6 +219,7 @@ pub struct ConnectorConfig { pub paypal: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub paypal_payout: Option<ConnectorTomlConfig>, + pub paystack: Option<ConnectorTomlConfig>, pub payu: Option<ConnectorTomlConfig>, pub placetopay: Option<ConnectorTomlConfig>, pub plaid: Option<ConnectorTomlConfig>, @@ -382,6 +383,7 @@ impl ConnectorConfig { Connector::Payme => Ok(connector_data.payme), Connector::Payone => Err("Use get_payout_connector_config".to_string()), Connector::Paypal => Ok(connector_data.paypal), + Connector::Paystack => Ok(connector_data.paystack), Connector::Payu => Ok(connector_data.payu), Connector::Placetopay => Ok(connector_data.placetopay), Connector::Plaid => Ok(connector_data.plaid), diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 0b6042ef931..97a2bdb77bb 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -46,6 +46,7 @@ pub mod novalnet; pub mod nuvei; pub mod paybox; pub mod payeezy; +pub mod paystack; pub mod payu; pub mod placetopay; pub mod powertranz; @@ -80,10 +81,10 @@ pub use self::{ iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, jpmorgan::Jpmorgan, klarna::Klarna, mifinity::Mifinity, mollie::Mollie, moneris::Moneris, multisafepay::Multisafepay, nexinets::Nexinets, nexixpay::Nexixpay, nomupay::Nomupay, novalnet::Novalnet, nuvei::Nuvei, - paybox::Paybox, payeezy::Payeezy, payu::Payu, placetopay::Placetopay, powertranz::Powertranz, - prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, redsys::Redsys, shift4::Shift4, - square::Square, stax::Stax, taxjar::Taxjar, thunes::Thunes, tsys::Tsys, - unified_authentication_service::UnifiedAuthenticationService, volt::Volt, + paybox::Paybox, payeezy::Payeezy, paystack::Paystack, payu::Payu, placetopay::Placetopay, + powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, + redsys::Redsys, shift4::Shift4, square::Square, stax::Stax, taxjar::Taxjar, thunes::Thunes, + tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, volt::Volt, wellsfargo::Wellsfargo, worldline::Worldline, worldpay::Worldpay, xendit::Xendit, zen::Zen, zsl::Zsl, }; diff --git a/crates/hyperswitch_connectors/src/connectors/paystack.rs b/crates/hyperswitch_connectors/src/connectors/paystack.rs new file mode 100644 index 00000000000..a88b60cc210 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/paystack.rs @@ -0,0 +1,568 @@ +pub mod transformers; + +use common_utils::{ + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, +}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundSyncRouterData, RefundsRouterData, + }, +}; +use hyperswitch_interfaces::{ + api::{ + self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, + ConnectorValidation, + }, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{self, Response}, + webhooks, +}; +use masking::{ExposeInterface, Mask}; +use transformers as paystack; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Paystack { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Paystack { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Paystack {} +impl api::PaymentSession for Paystack {} +impl api::ConnectorAccessToken for Paystack {} +impl api::MandateSetup for Paystack {} +impl api::PaymentAuthorize for Paystack {} +impl api::PaymentSync for Paystack {} +impl api::PaymentCapture for Paystack {} +impl api::PaymentVoid for Paystack {} +impl api::Refund for Paystack {} +impl api::RefundExecute for Paystack {} +impl api::RefundSync for Paystack {} +impl api::PaymentToken for Paystack {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Paystack +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paystack +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + +impl ConnectorCommon for Paystack { + fn id(&self) -> &'static str { + "paystack" + } + + 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 Connectors) -> &'a str { + connectors.paystack.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = paystack::PaystackAuthType::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: paystack::PaystackErrorResponse = res + .response + .parse_struct("PaystackErrorResponse") + .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 Paystack { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Paystack { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Paystack {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Paystack +{ +} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paystack { + fn get_headers( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + + let connector_router_data = paystack::PaystackRouterData::from((amount, req)); + let connector_req = paystack::PaystackPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: paystack::PaystackPaymentsResponse = res + .response + .parse_struct("Paystack PaymentsAuthorizeResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Paystack { + fn get_headers( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { + let response: paystack::PaystackPaymentsResponse = res + .response + .parse_struct("paystack PaymentsSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Paystack { + fn get_headers( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCaptureType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { + let response: paystack::PaystackPaymentsResponse = res + .response + .parse_struct("Paystack PaymentsCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Paystack {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paystack { + fn get_headers( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let refund_amount = utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, + req.request.currency, + )?; + + let connector_router_data = paystack::PaystackRouterData::from((refund_amount, req)); + let connector_req = paystack::PaystackRefundRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .set_body(types::RefundExecuteType::get_request_body( + self, req, connectors, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &RefundsRouterData<Execute>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { + let response: paystack::RefundResponse = res + .response + .parse_struct("paystack RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Paystack { + fn get_headers( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .set_body(types::RefundSyncType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { + let response: paystack::RefundResponse = res + .response + .parse_struct("paystack RefundSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[async_trait::async_trait] +impl webhooks::IncomingWebhook for Paystack { + fn get_webhook_object_reference_id( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_event_type( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_resource_object( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } +} + +impl ConnectorSpecifications for Paystack {} diff --git a/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs new file mode 100644 index 00000000000..8a07997fbdc --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs @@ -0,0 +1,228 @@ +use common_enums::enums; +use common_utils::types::StringMinorUnit; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{ConnectorAuthType, RouterData}, + router_flow_types::refunds::{Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{PaymentsAuthorizeRouterData, RefundsRouterData}, +}; +use hyperswitch_interfaces::errors; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::PaymentsAuthorizeRequestData, +}; + +//TODO: Fill the struct with respective fields +pub struct PaystackRouterData<T> { + pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> From<(StringMinorUnit, T)> for PaystackRouterData<T> { + fn from((amount, item): (StringMinorUnit, T)) -> Self { + //Todo : use utils to convert the amount to the type of amount that a connector accepts + Self { + amount, + router_data: item, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, PartialEq)] +pub struct PaystackPaymentsRequest { + amount: StringMinorUnit, + card: PaystackCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct PaystackCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&PaystackRouterData<&PaymentsAuthorizeRouterData>> for PaystackPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &PaystackRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(req_card) => { + let card = PaystackCard { + number: req_card.card_number, + expiry_month: req_card.card_exp_month, + expiry_year: req_card.card_exp_year, + cvc: req_card.card_cvc, + complete: item.router_data.request.is_auto_capture()?, + }; + Ok(Self { + amount: item.amount.clone(), + card, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct PaystackAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for PaystackAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + api_key: api_key.to_owned(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} +// PaymentsResponse +//TODO: Append the remaining status flags +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum PaystackPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<PaystackPaymentStatus> for common_enums::AttemptStatus { + fn from(item: PaystackPaymentStatus) -> Self { + match item { + PaystackPaymentStatus::Succeeded => Self::Charged, + PaystackPaymentStatus::Failed => Self::Failure, + PaystackPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PaystackPaymentsResponse { + status: PaystackPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, PaystackPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, PaystackPaymentsResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: common_enums::AttemptStatus::from(item.response.status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct PaystackRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&PaystackRouterData<&RefundsRouterData<F>>> for PaystackRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &PaystackRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Serialize, Default, Deserialize, Clone)] +pub enum RefundStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Succeeded => Self::Success, + RefundStatus::Failed => Self::Failure, + RefundStatus::Processing => Self::Pending, + //TODO: Review mapping + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct RefundResponse { + id: String, + status: RefundStatus, +} + +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct PaystackErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index b2df2d15f71..4be5f661134 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -139,6 +139,7 @@ default_imp_for_authorize_session_token!( connectors::Nexixpay, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -228,6 +229,7 @@ default_imp_for_calculate_tax!( connectors::Novalnet, connectors::Nuvei, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -315,6 +317,7 @@ default_imp_for_session_update!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::UnifiedAuthenticationService, @@ -401,6 +404,7 @@ default_imp_for_post_session_tokens!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Fiuu, @@ -475,6 +479,7 @@ default_imp_for_complete_authorize!( connectors::Novalnet, connectors::Nexinets, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Rapyd, @@ -553,6 +558,7 @@ default_imp_for_incremental_authorization!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -642,6 +648,7 @@ default_imp_for_create_customer!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -720,6 +727,7 @@ default_imp_for_connector_redirect_response!( connectors::Nexixpay, connectors::Nomupay, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -795,6 +803,7 @@ default_imp_for_pre_processing_steps!( connectors::Nexinets, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -880,6 +889,7 @@ default_imp_for_post_processing_steps!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -967,6 +977,7 @@ default_imp_for_approve!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1054,6 +1065,7 @@ default_imp_for_reject!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1141,6 +1153,7 @@ default_imp_for_webhook_source_verification!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1229,6 +1242,7 @@ default_imp_for_accept_dispute!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1316,6 +1330,7 @@ default_imp_for_submit_evidence!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1403,6 +1418,7 @@ default_imp_for_defend_dispute!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1499,6 +1515,7 @@ default_imp_for_file_upload!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1582,6 +1599,7 @@ default_imp_for_payouts!( connectors::Novalnet, connectors::Nuvei, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1666,6 +1684,7 @@ default_imp_for_payouts_create!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1755,6 +1774,7 @@ default_imp_for_payouts_retrieve!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1844,6 +1864,7 @@ default_imp_for_payouts_eligibility!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1932,6 +1953,7 @@ default_imp_for_payouts_fulfill!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2021,6 +2043,7 @@ default_imp_for_payouts_cancel!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2110,6 +2133,7 @@ default_imp_for_payouts_quote!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2199,6 +2223,7 @@ default_imp_for_payouts_recipient!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2288,6 +2313,7 @@ default_imp_for_payouts_recipient_account!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2377,6 +2403,7 @@ default_imp_for_frm_sale!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2466,6 +2493,7 @@ default_imp_for_frm_checkout!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2555,6 +2583,7 @@ default_imp_for_frm_transaction!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2644,6 +2673,7 @@ default_imp_for_frm_fulfillment!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2733,6 +2763,7 @@ default_imp_for_frm_record_return!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2818,6 +2849,7 @@ default_imp_for_revoking_mandates!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2904,6 +2936,7 @@ default_imp_for_uas_pre_authentication!( connectors::Nexixpay, connectors::Nuvei, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Powertranz, connectors::Prophetpay, @@ -2989,6 +3022,7 @@ default_imp_for_uas_post_authentication!( connectors::Nexixpay, connectors::Nuvei, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Powertranz, connectors::Prophetpay, @@ -3074,6 +3108,7 @@ default_imp_for_uas_authentication!( connectors::Nexixpay, connectors::Nuvei, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Powertranz, connectors::Prophetpay, @@ -3160,6 +3195,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Nexixpay, connectors::Nuvei, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Powertranz, connectors::Prophetpay, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index d0ffd3a230c..003c3cc46d1 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -248,6 +248,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -336,6 +337,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -419,6 +421,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -507,6 +510,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -594,6 +598,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -682,6 +687,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -780,6 +786,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -870,6 +877,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -960,6 +968,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1050,6 +1059,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1140,6 +1150,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1230,6 +1241,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1320,6 +1332,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1410,6 +1423,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1500,6 +1514,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1588,6 +1603,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1678,6 +1694,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1768,6 +1785,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1858,6 +1876,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1948,6 +1967,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2038,6 +2058,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2125,6 +2146,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Powertranz, diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs index d5656f3a477..4c4801801f0 100644 --- a/crates/hyperswitch_interfaces/src/configs.rs +++ b/crates/hyperswitch_interfaces/src/configs.rs @@ -73,6 +73,7 @@ pub struct Connectors { pub payme: ConnectorParams, pub payone: ConnectorParams, pub paypal: ConnectorParams, + pub paystack: ConnectorParams, pub payu: ConnectorParams, pub placetopay: ConnectorParams, pub plaid: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 4bf57cb16f0..de9d86fdd79 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -41,11 +41,11 @@ pub use hyperswitch_connectors::connectors::{ klarna::Klarna, mifinity, mifinity::Mifinity, mollie, mollie::Mollie, moneris, moneris::Moneris, multisafepay, multisafepay::Multisafepay, nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nomupay, nomupay::Nomupay, novalnet, novalnet::Novalnet, nuvei, - nuvei::Nuvei, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payu, payu::Payu, placetopay, - placetopay::Placetopay, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, - rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, redsys, redsys::Redsys, shift4, - shift4::Shift4, square, square::Square, stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, - thunes::Thunes, tsys, tsys::Tsys, unified_authentication_service, + nuvei::Nuvei, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, paystack, paystack::Paystack, + payu, payu::Payu, placetopay, placetopay::Placetopay, powertranz, powertranz::Powertranz, + prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, redsys, + redsys::Redsys, shift4, shift4::Shift4, square, square::Square, stax, stax::Stax, taxjar, + taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index bc93b9c53eb..cc753e12895 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1490,6 +1490,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { payone::transformers::PayoneAuthType::try_from(self.auth_type)?; Ok(()) } + api_enums::Connector::Paystack => { + paystack::transformers::PaystackAuthType::try_from(self.auth_type)?; + Ok(()) + } api_enums::Connector::Payu => { payu::transformers::PayuAuthType::try_from(self.auth_type)?; Ok(()) diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs index 1219363b212..997a40c9393 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -1030,6 +1030,7 @@ default_imp_for_new_connector_integration_payouts!( connector::Payme, connector::Payone, connector::Paypal, + connector::Paystack, connector::Payu, connector::Powertranz, connector::Rapyd, @@ -1496,6 +1497,7 @@ default_imp_for_new_connector_integration_frm!( connector::Payme, connector::Payone, connector::Paypal, + connector::Paystack, connector::Payu, connector::Powertranz, connector::Rapyd, @@ -1873,6 +1875,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connector::Payme, connector::Payone, connector::Paypal, + connector::Paystack, connector::Payu, connector::Placetopay, connector::Powertranz, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index f55c1f58f60..e9e3ea10cd6 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -452,6 +452,7 @@ default_imp_for_connector_request_id!( connector::Payme, connector::Payone, connector::Paypal, + connector::Paystack, connector::Payu, connector::Placetopay, connector::Plaid, @@ -1413,6 +1414,7 @@ default_imp_for_fraud_check!( connector::Payme, connector::Payone, connector::Paypal, + connector::Paystack, connector::Payu, connector::Placetopay, connector::Plaid, @@ -1948,6 +1950,7 @@ default_imp_for_connector_authentication!( connector::Payme, connector::Payone, connector::Paypal, + connector::Paystack, connector::Payu, connector::Placetopay, connector::Plaid, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 43556eb581a..14a5730d4f1 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -543,6 +543,9 @@ impl ConnectorData { enums::Connector::Paypal => { Ok(ConnectorEnum::Old(Box::new(connector::Paypal::new()))) } + enums::Connector::Paystack => { + Ok(ConnectorEnum::Old(Box::new(connector::Paystack::new()))) + } // enums::Connector::Thunes => Ok(ConnectorEnum::Old(Box::new(connector::Thunes))), enums::Connector::Trustpay => { Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new()))) diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index a05020856b9..957d8279b36 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -282,6 +282,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Payme => Self::Payme, api_enums::Connector::Payone => Self::Payone, api_enums::Connector::Paypal => Self::Paypal, + api_enums::Connector::Paystack => Self::Paystack, api_enums::Connector::Payu => Self::Payu, api_models::enums::Connector::Placetopay => Self::Placetopay, api_enums::Connector::Plaid => Self::Plaid, diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index f2fdfddfd63..d0eb96efcc8 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -69,6 +69,7 @@ mod payeezy; mod payme; mod payone; mod paypal; +mod paystack; mod payu; mod placetopay; mod plaid; diff --git a/crates/router/tests/connectors/paystack.rs b/crates/router/tests/connectors/paystack.rs new file mode 100644 index 00000000000..2aaac95b208 --- /dev/null +++ b/crates/router/tests/connectors/paystack.rs @@ -0,0 +1,421 @@ +use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; +use masking::Secret; +use router::types::{self, api, storage::enums}; +use test_utils::connector_auth; + +use crate::utils::{self, ConnectorActions}; + +#[derive(Clone, Copy)] +struct PaystackTest; +impl ConnectorActions for PaystackTest {} +impl utils::Connector for PaystackTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Paystack; + utils::construct_connector_data_old( + Box::new(Paystack::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .paystack + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "paystack".to_string() + } +} + +static CONNECTOR: PaystackTest = PaystackTest {}; + +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + None +} + +fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { + None +} + +// Cards Positive Tests +// Creates a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +// Captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Partially captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + payment_method_details(), + Some(types::PaymentsCaptureData { + amount_to_capture: 50, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +// Voids a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment( + payment_method_details(), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("Void payment response"); + assert_eq!(response.status, enums::AttemptStatus::Voided); +} + +// Refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Synchronizes a refund using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_manually_captured_refund() { + let refund_response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_make_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_auto_captured_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + capture_method: Some(enums::CaptureMethod::Automatic), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Charged,); +} + +// Refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_auto_captured_payment() { + let response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let refund_response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + CONNECTOR + .make_payment_and_multiple_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await; +} + +// Synchronizes a refund using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_refund() { + let refund_response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Cards Negative scenarios +// Creates a payment with incorrect CVC. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's security code is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry month. +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration month is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry year. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_expiry_year() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration year is invalid.".to_string(), + ); +} + +// Voids a payment using automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_fail_void_payment_for_auto_capture() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let void_response = CONNECTOR + .void_payment(txn_id.unwrap(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + void_response.response.unwrap_err().message, + "You cannot cancel this PaymentIntent because it has a status of succeeded." + ); +} + +// Captures a payment using invalid connector payment id. +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let capture_response = CONNECTOR + .capture_payment("123456789".to_string(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("No such payment_intent: '123456789'") + ); +} + +// Refunds a payment with refund amount higher than payment amount. +#[actix_web::test] +async fn should_fail_for_refund_amount_higher_than_payment_amount() { + let response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Refund amount (₹1.50) is greater than charge amount (₹1.00)", + ); +} + +// Connector dependent test cases goes here + +// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 4677417104c..6314b7fd322 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -313,4 +313,7 @@ api_key="API Key" api_key= "API Key" [moneris] -api_key= "API Key" \ No newline at end of file +api_key= "API Key" + +[paystack] +api_key = "API Key" \ No newline at end of file diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 7a5b48f03a6..6036dc2a20f 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -74,6 +74,7 @@ pub struct ConnectorAuthentication { pub payme: Option<BodyKey>, pub payone: Option<HeaderKey>, pub paypal: Option<BodyKey>, + pub paystack: Option<HeaderKey>, pub payu: Option<BodyKey>, pub placetopay: Option<BodyKey>, pub plaid: Option<BodyKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 6766d7cb7e6..22d2ccf7d98 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -145,6 +145,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/" payme.base_url = "https://sandbox.payme.io/" payone.base_url = "https://payment.preprod.payone.com/" paypal.base_url = "https://api-m.sandbox.paypal.com/" +paystack.base_url = "https://api.paystack.co" payu.base_url = "https://secure.snd.payu.com/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" @@ -245,6 +246,7 @@ cards = [ "payme", "payone", "paypal", + "paystack", "payu", "placetopay", "plaid", diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 021854ab3f1..f2c55f54adc 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 amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte getnet globalpay globepay gocardless gpayments helcim iatapay inespay itaubank jpmorgan klarna mifinity mollie moneris multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay redsys shift4 square stax stripe taxjar threedsecureio thunes trustpay tsys unified_authentication_service volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1") + connectors=(aci adyen adyenplatform airwallex amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte getnet globalpay globepay gocardless gpayments helcim iatapay inespay itaubank jpmorgan klarna mifinity mollie moneris multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal paystack payu placetopay plaid powertranz prophetpay rapyd razorpay redsys shift4 square stax stripe taxjar threedsecureio thunes trustpay tsys unified_authentication_service volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res="$(echo ${sorted[@]})" sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
2025-02-17T11:23:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Paystack template PR. Follow the steps outlined in the add_connector.md file. Execute the script provided in the markdown file, then run the following commands: cargo clippy cargo +nightly fmt --all ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.112.0
5e7e0d829a7deeed6b50af9633f6d2307b51c4bd
5e7e0d829a7deeed6b50af9633f6d2307b51c4bd
juspay/hyperswitch
juspay__hyperswitch-7313
Bug: Integrate EFT as a Payment Method in Hyperswitch Electronic Fund Transfer is a redirection flow, that falls under Bank Redirect in Hyperswitch. We have to add EFT as a payment method. - Add EFT under `BankRedirectData` enum in `crates/api_models/src/payments.rs` which has a structure: ``` Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, } ``` - Everywhere the enum `BankRedirectData` is used we have to put EFT there. - In the transformers.rs file of every connector, if the connector supports EFT we have to add implementations there otherwise we'll this as `NotSupported` or `NotImplemented` elsewhere. Ref PR: https://github.com/juspay/hyperswitch/pull/7304
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index bef1bcdeb55..4f801c2dd0c 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -5578,6 +5578,27 @@ "type": "object" } } + }, + { + "type": "object", + "required": [ + "eft" + ], + "properties": { + "eft": { + "type": "object", + "required": [ + "provider" + ], + "properties": { + "provider": { + "type": "string", + "description": "The preferred eft provider", + "example": "ozow" + } + } + } + } } ] }, @@ -15433,6 +15454,7 @@ "debit", "duit_now", "efecty", + "eft", "eps", "fps", "evoucher", diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 59791cc7504..eda1c43800f 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -7733,6 +7733,27 @@ "type": "object" } } + }, + { + "type": "object", + "required": [ + "eft" + ], + "properties": { + "eft": { + "type": "object", + "required": [ + "provider" + ], + "properties": { + "provider": { + "type": "string", + "description": "The preferred eft provider", + "example": "ozow" + } + } + } + } } ] }, @@ -17767,6 +17788,7 @@ "debit", "duit_now", "efecty", + "eft", "eps", "fps", "evoucher", diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 15d6e68f14e..2d2679f646c 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -2639,6 +2639,7 @@ impl GetPaymentMethodType for BankRedirectData { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, + Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, @@ -3015,6 +3016,11 @@ pub enum BankRedirectData { issuer: common_enums::BankNames, }, LocalBankRedirect {}, + Eft { + /// The preferred eft provider + #[schema(example = "ozow")] + provider: String, + }, } impl GetAddressFromPaymentMethodData for BankRedirectData { @@ -3130,7 +3136,8 @@ impl GetAddressFromPaymentMethodData for BankRedirectData { | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } - | Self::Blik { .. } => None, + | Self::Blik { .. } + | Self::Eft { .. } => None, } } } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 26b56be1f07..208fb7dedb5 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1587,6 +1587,7 @@ pub enum PaymentMethodType { Debit, DuitNow, Efecty, + Eft, Eps, Fps, Evoucher, diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index d351f5c927e..6fcc33a97f0 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1821,6 +1821,7 @@ impl From<PaymentMethodType> for PaymentMethod { PaymentMethodType::Debit => Self::Card, PaymentMethodType::Fps => Self::RealTimePayment, PaymentMethodType::DuitNow => Self::RealTimePayment, + PaymentMethodType::Eft => Self::BankRedirect, PaymentMethodType::Eps => Self::BankRedirect, PaymentMethodType::Evoucher => Self::Reward, PaymentMethodType::Giropay => Self::BankRedirect, diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index 6fb302641db..58e9f6fca31 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -147,6 +147,7 @@ pub enum BankRedirectType { Giropay, Ideal, Sofort, + Eft, Eps, BancontactCard, Blik, diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs index 04a029bd109..c5cb54378b0 100644 --- a/crates/euclid/src/frontend/dir/lowering.rs +++ b/crates/euclid/src/frontend/dir/lowering.rs @@ -160,6 +160,7 @@ impl From<enums::BankRedirectType> for global_enums::PaymentMethodType { enums::BankRedirectType::Giropay => Self::Giropay, enums::BankRedirectType::Ideal => Self::Ideal, enums::BankRedirectType::Sofort => Self::Sofort, + enums::BankRedirectType::Eft => Self::Eft, enums::BankRedirectType::Eps => Self::Eps, enums::BankRedirectType::BancontactCard => Self::BancontactCard, enums::BankRedirectType::Blik => Self::Blik, diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs index 1a3bb52e0fa..762f3a857b2 100644 --- a/crates/euclid/src/frontend/dir/transformers.rs +++ b/crates/euclid/src/frontend/dir/transformers.rs @@ -196,6 +196,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet global_enums::PaymentMethodType::DirectCarrierBilling => { Ok(dirval!(MobilePaymentType = DirectCarrierBilling)) } + global_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)), } } } diff --git a/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs b/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs index 9fe45cef21e..3e4ac8d80a8 100644 --- a/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs @@ -174,6 +174,17 @@ impl merchant_transaction_id: None, customer_email: None, })), + BankRedirectData::Eft { .. } => Self::BankRedirect(Box::new(BankRedirectionPMData { + payment_brand: PaymentBrand::Eft, + bank_account_country: Some(item.router_data.get_billing_country()?), + bank_account_bank_name: None, + bank_account_bic: None, + bank_account_iban: None, + billing_country: None, + merchant_customer_id: None, + merchant_transaction_id: None, + customer_email: None, + })), BankRedirectData::Giropay { bank_account_bic, bank_account_iban, @@ -326,6 +337,7 @@ pub struct WalletPMData { #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PaymentBrand { Eps, + Eft, Ideal, Giropay, Sofortueberweisung, diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index 5c38a55dc0f..8b1296a0159 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -465,6 +465,7 @@ impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentReque BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Giropay { .. } | BankRedirectData::Ideal { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs index 6450839fac3..e41057fb8e6 100644 --- a/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/iatapay/transformers.rs @@ -164,6 +164,7 @@ impl BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Giropay { .. } | BankRedirectData::Interac { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/klarna.rs b/crates/hyperswitch_connectors/src/connectors/klarna.rs index dd0110d9593..86ad19d7dc2 100644 --- a/crates/hyperswitch_connectors/src/connectors/klarna.rs +++ b/crates/hyperswitch_connectors/src/connectors/klarna.rs @@ -581,6 +581,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData | common_enums::PaymentMethodType::Debit | common_enums::PaymentMethodType::DirectCarrierBilling | common_enums::PaymentMethodType::Efecty + | common_enums::PaymentMethodType::Eft | common_enums::PaymentMethodType::Eps | common_enums::PaymentMethodType::Evoucher | common_enums::PaymentMethodType::Giropay @@ -698,6 +699,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData | common_enums::PaymentMethodType::Debit | common_enums::PaymentMethodType::DirectCarrierBilling | common_enums::PaymentMethodType::Efecty + | common_enums::PaymentMethodType::Eft | common_enums::PaymentMethodType::Eps | common_enums::PaymentMethodType::Evoucher | common_enums::PaymentMethodType::Giropay diff --git a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs index 61732e5c751..3e632e048a2 100644 --- a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs @@ -525,6 +525,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum { .. } | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } @@ -590,6 +591,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum { .. } | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } @@ -777,6 +779,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum { .. } | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Giropay { .. } | BankRedirectData::Interac { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs index 88cea9c8edf..8e4b9995040 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs @@ -593,6 +593,7 @@ fn get_payment_details_and_product( BankRedirectData::BancontactCard { .. } | BankRedirectData::Blik { .. } | BankRedirectData::Bizum { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 3bc06aa6e19..0bfd3af7e99 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -977,6 +977,7 @@ where BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs b/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs index b2fd0ed0b49..cfa5c28e7ba 100644 --- a/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs @@ -505,6 +505,7 @@ impl TryFrom<&BankRedirectData> for PaymentMethodType { BankRedirectData::Sofort { .. } => Ok(Self::Sofort), BankRedirectData::BancontactCard { .. } | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Trustly { .. } | BankRedirectData::Przelewy24 { .. } | BankRedirectData::Bizum {} diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs index 52181738579..e8da94fae34 100644 --- a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs @@ -238,6 +238,7 @@ impl TryFrom<&BankRedirectData> for TrustpayPaymentMethod { BankRedirectData::Blik { .. } => Ok(Self::Blik), BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} + | BankRedirectData::Eft { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } | BankRedirectData::OnlineBankingFinland { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs index 86816195276..3841b7e33b4 100644 --- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs @@ -113,6 +113,7 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Giropay { .. } | BankRedirectData::Ideal { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs index f9d7da5d1ec..d716bfd088f 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs @@ -390,6 +390,7 @@ fn make_bank_redirect_request( BankRedirectData::BancontactCard { .. } | BankRedirectData::Bizum {} | BankRedirectData::Blik { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Interac { .. } | BankRedirectData::OnlineBankingCzechRepublic { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs index abe528eff29..305c8518c8e 100644 --- a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs @@ -724,6 +724,7 @@ impl TryFrom<&BankRedirectData> for ZenPaymentsRequest { | BankRedirectData::BancontactCard { .. } | BankRedirectData::Blik { .. } | BankRedirectData::Trustly { .. } + | BankRedirectData::Eft { .. } | BankRedirectData::Eps { .. } | BankRedirectData::Giropay { .. } | BankRedirectData::Przelewy24 { .. } diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index ac5a7714b54..ce40e373462 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -5199,6 +5199,7 @@ pub enum PaymentMethodDataType { BancontactCard, Bizum, Blik, + Eft, Eps, Giropay, Ideal, @@ -5330,6 +5331,7 @@ impl From<PaymentMethodData> for PaymentMethodDataType { } payment_method_data::BankRedirectData::Bizum {} => Self::Bizum, payment_method_data::BankRedirectData::Blik { .. } => Self::Blik, + payment_method_data::BankRedirectData::Eft { .. } => Self::Eft, payment_method_data::BankRedirectData::Eps { .. } => Self::Eps, payment_method_data::BankRedirectData::Giropay { .. } => Self::Giropay, payment_method_data::BankRedirectData::Ideal { .. } => Self::Ideal, diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 78b2144f3ed..9b73fe45f65 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -437,6 +437,9 @@ pub enum BankRedirectData { issuer: common_enums::BankNames, }, LocalBankRedirect {}, + Eft { + provider: String, + }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] @@ -1029,6 +1032,7 @@ impl From<api_models::payments::BankRedirectData> for BankRedirectData { api_models::payments::BankRedirectData::LocalBankRedirect { .. } => { Self::LocalBankRedirect {} } + api_models::payments::BankRedirectData::Eft { provider } => Self::Eft { provider }, } } } @@ -1613,6 +1617,7 @@ impl GetPaymentMethodType for BankRedirectData { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, + Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index e224078493f..88c32a48187 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -28,6 +28,7 @@ fn get_dir_value_payment_method( 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::Eft => Ok(dirval!(BankRedirectType = Eft)), api_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)), api_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)), api_enums::PaymentMethodType::AfterpayClearpay => { diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index adfe5820866..0479753d8d0 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -136,6 +136,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { 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::Eft => Ok(dirval!(BankRedirectType = Eft)), api_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)), api_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)), api_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)), diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 7067592771f..7cefdda657e 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -222,6 +222,7 @@ impl ConnectorValidation for Adyen { | PaymentMethodType::Multibanco | PaymentMethodType::Przelewy24 | PaymentMethodType::Becs + | PaymentMethodType::Eft | PaymentMethodType::ClassicReward | PaymentMethodType::Pse | PaymentMethodType::LocalBankTransfer diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 93a43f25b8a..0920887962a 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2404,6 +2404,7 @@ impl ), domain::BankRedirectData::Trustly { .. } => Ok(AdyenPaymentMethod::Trustly), domain::BankRedirectData::Giropay { .. } + | domain::BankRedirectData::Eft { .. } | domain::BankRedirectData::Interac { .. } | domain::BankRedirectData::LocalBankRedirect {} | domain::BankRedirectData::Przelewy24 { .. } diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 5989706bf5b..80a702512c0 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -762,6 +762,7 @@ fn get_payment_source( .into()) } domain::BankRedirectData::Bizum {} + | domain::BankRedirectData::Eft { .. } | domain::BankRedirectData::Interac { .. } | domain::BankRedirectData::OnlineBankingCzechRepublic { .. } | domain::BankRedirectData::OnlineBankingFinland { .. } @@ -1158,6 +1159,7 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP | enums::PaymentMethodType::DirectCarrierBilling | enums::PaymentMethodType::DuitNow | enums::PaymentMethodType::Efecty + | enums::PaymentMethodType::Eft | enums::PaymentMethodType::Eps | enums::PaymentMethodType::Fps | enums::PaymentMethodType::Evoucher diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index cdcf7b4c7b2..41fb23e7e9e 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -711,6 +711,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { | enums::PaymentMethodType::Dana | enums::PaymentMethodType::DirectCarrierBilling | enums::PaymentMethodType::Efecty + | enums::PaymentMethodType::Eft | enums::PaymentMethodType::Evoucher | enums::PaymentMethodType::GoPay | enums::PaymentMethodType::Gcash @@ -1032,6 +1033,7 @@ impl TryFrom<&domain::BankRedirectData> for StripePaymentMethodType { } domain::BankRedirectData::Bizum {} | domain::BankRedirectData::Interac { .. } + | domain::BankRedirectData::Eft { .. } | domain::BankRedirectData::OnlineBankingCzechRepublic { .. } | domain::BankRedirectData::OnlineBankingFinland { .. } | domain::BankRedirectData::OnlineBankingPoland { .. } @@ -1600,6 +1602,7 @@ impl TryFrom<(&domain::BankRedirectData, Option<StripeBillingAddress>)> .into()) } domain::BankRedirectData::Bizum {} + | domain::BankRedirectData::Eft { .. } | domain::BankRedirectData::Interac { .. } | domain::BankRedirectData::OnlineBankingCzechRepublic { .. } | domain::BankRedirectData::OnlineBankingFinland { .. } diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 2d7e3cc6d52..8a186e0291a 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -2789,6 +2789,7 @@ pub enum PaymentMethodDataType { BancontactCard, Bizum, Blik, + Eft, Eps, Giropay, Ideal, @@ -2920,6 +2921,7 @@ impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { } domain::payments::BankRedirectData::Bizum {} => Self::Bizum, domain::payments::BankRedirectData::Blik { .. } => Self::Blik, + domain::payments::BankRedirectData::Eft { .. } => Self::Eft, domain::payments::BankRedirectData::Eps { .. } => Self::Eps, domain::payments::BankRedirectData::Giropay { .. } => Self::Giropay, domain::payments::BankRedirectData::Ideal { .. } => Self::Ideal, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 05b4d592c23..cdbda13997b 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2997,6 +2997,7 @@ pub fn validate_payment_method_type_against_payment_method( api_enums::PaymentMethodType::Giropay | api_enums::PaymentMethodType::Ideal | api_enums::PaymentMethodType::Sofort + | api_enums::PaymentMethodType::Eft | api_enums::PaymentMethodType::Eps | api_enums::PaymentMethodType::BancontactCard | api_enums::PaymentMethodType::Blik @@ -4828,6 +4829,12 @@ pub async fn get_additional_payment_data( details: None, }, )), + domain::BankRedirectData::Eft { .. } => Ok(Some( + api_models::payments::AdditionalPaymentData::BankRedirect { + bank_name: None, + details: None, + }, + )), domain::BankRedirectData::Ideal { bank_name, .. } => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: bank_name.to_owned(), diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 514ddbbbb50..860d5f5f580 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -491,6 +491,7 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { api_enums::PaymentMethodType::Giropay | api_enums::PaymentMethodType::Ideal | api_enums::PaymentMethodType::Sofort + | api_enums::PaymentMethodType::Eft | api_enums::PaymentMethodType::Eps | api_enums::PaymentMethodType::BancontactCard | api_enums::PaymentMethodType::Blik
2025-02-18T19:46:27Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Active Issue: https://github.com/juspay/hyperswitch/issues/7313 ## Description <!-- Describe your changes in detail --> Added EFT as a payment method in Bank Redirect. Active Issue linked to this PR: https://github.com/juspay/hyperswitch/issues/7313 but still PR convention checks are failing ### 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)? --> EFT is a new payment payment method and there is no connector to test that. Paystack is the only connector with EFT. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
30f321bc2001264f5197172428ecae79896ad2f5
30f321bc2001264f5197172428ecae79896ad2f5
juspay/hyperswitch
juspay__hyperswitch-7299
Bug: add Samsung pay mandate support for Cybersource add Samsung pay mandate support for Cybersource
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index b7b57690474..f9b9fb1b414 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -1215,6 +1215,8 @@ merchant_secret="Source verification key" payment_method_type = "google_pay" [[cybersource.wallet]] payment_method_type = "paze" +[[cybersource.wallet]] + payment_method_type = "samsung_pay" [cybersource.connector_auth.SignatureKey] api_key="Key" key1="Merchant ID" diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource.rs b/crates/hyperswitch_connectors/src/connectors/cybersource.rs index 5a60f6d705a..812d0391dec 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource.rs @@ -312,6 +312,7 @@ impl ConnectorValidation for Cybersource { PaymentMethodDataType::Card, PaymentMethodDataType::ApplePay, PaymentMethodDataType::GooglePay, + PaymentMethodDataType::SamsungPay, ]); utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index b953fa73754..4652080397a 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -251,6 +251,11 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest { )), Some(PaymentSolution::GooglePay), ), + WalletData::SamsungPay(samsung_pay_data) => ( + (get_samsung_pay_payment_information(&samsung_pay_data) + .attach_printable("Failed to get samsung pay payment information")?), + Some(PaymentSolution::SamsungPay), + ), WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) @@ -269,7 +274,6 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest { | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) - | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) @@ -1859,25 +1863,8 @@ impl let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); - let samsung_pay_fluid_data_value = - get_samsung_pay_fluid_data_value(&samsung_pay_data.payment_credential.token_data)?; - - let samsung_pay_fluid_data_str = serde_json::to_string(&samsung_pay_fluid_data_value) - .change_context(errors::ConnectorError::RequestEncodingFailed) - .attach_printable("Failed to serialize samsung pay fluid data")?; - - let payment_information = - PaymentInformation::SamsungPay(Box::new(SamsungPayPaymentInformation { - fluid_data: FluidData { - value: Secret::new(consts::BASE64_ENGINE.encode(samsung_pay_fluid_data_str)), - descriptor: Some( - consts::BASE64_ENGINE.encode(FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY), - ), - }, - tokenized_card: SamsungPayTokenizedCard { - transaction_type: TransactionType::SamsungPay, - }, - })); + let payment_information = get_samsung_pay_payment_information(&samsung_pay_data) + .attach_printable("Failed to get samsung pay payment information")?; let processing_information = ProcessingInformation::try_from(( item, @@ -1903,6 +1890,32 @@ impl } } +fn get_samsung_pay_payment_information( + samsung_pay_data: &SamsungPayWalletData, +) -> Result<PaymentInformation, error_stack::Report<errors::ConnectorError>> { + let samsung_pay_fluid_data_value = + get_samsung_pay_fluid_data_value(&samsung_pay_data.payment_credential.token_data)?; + + let samsung_pay_fluid_data_str = serde_json::to_string(&samsung_pay_fluid_data_value) + .change_context(errors::ConnectorError::RequestEncodingFailed) + .attach_printable("Failed to serialize samsung pay fluid data")?; + + let payment_information = + PaymentInformation::SamsungPay(Box::new(SamsungPayPaymentInformation { + fluid_data: FluidData { + value: Secret::new(consts::BASE64_ENGINE.encode(samsung_pay_fluid_data_str)), + descriptor: Some( + consts::BASE64_ENGINE.encode(FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY), + ), + }, + tokenized_card: SamsungPayTokenizedCard { + transaction_type: TransactionType::SamsungPay, + }, + })); + + Ok(payment_information) +} + fn get_samsung_pay_fluid_data_value( samsung_pay_token_data: &hyperswitch_domain_models::payment_method_data::SamsungPayTokenData, ) -> Result<SamsungPayFluidDataValue, error_stack::Report<errors::ConnectorError>> { diff --git a/crates/router/src/configs/defaults/payment_connector_required_fields.rs b/crates/router/src/configs/defaults/payment_connector_required_fields.rs index 27cc485188b..3849054045c 100644 --- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs +++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs @@ -9128,7 +9128,86 @@ impl Default for settings::RequiredFields { RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), - common: HashMap::new(), + common: HashMap::from( + [ + ( + "billing.email".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::UserEmailAddress, + value: None, + } + ), + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.first_name".to_string(), + display_name: "billing_first_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + ), + ( + "billing.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.last_name".to_string(), + display_name: "billing_last_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + ), + ( + "billing.address.city".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::UserAddressCity, + value: None, + } + ), + ( + "billing.address.state".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.state".to_string(), + display_name: "state".to_string(), + field_type: enums::FieldType::UserAddressState, + value: None, + } + ), + ( + "billing.address.zip".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::UserAddressPincode, + value: None, + } + ), + ( + "billing.address.country".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserAddressCountry{ + options: vec![ + "ALL".to_string(), + ] + }, + value: None, + } + ), + ( + "billing.address.line1".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::UserAddressLine1, + value: None, + } + ) + ] + ), } ), ]),
2025-02-18T12:45:16Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pr adds Samsung pay mandate support for Cybersource and enable samsung pay for cybersource on sandbox. ### 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 Cybersource connector with Samsung pay enabled for it -> Make a samsung pay off_session payment with amount set to zero. Payment will be in failed status with `"error_message": "SERVER_ERROR"`. This is expected, we need to get off_session payments enabled for our cybersource account. ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api-key' \ --data-raw '{ "amount": 0, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "customer_id": "cu_1739882499", "setup_future_usage": "off_session", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "return_url": "https://google.com", "email": "[email protected]", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "payment_type": "setup_mandate", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "samsung_pay", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "payment_method_data": { "wallet": { "samsung_pay": { "payment_credential": { "3_d_s": { "type": "S", "version": "100", "data": "samsung-pay-token" }, "payment_card_brand": "VI", "payment_currency_type": "USD", "payment_last4_fpan": "1661", "method": "3DS", "recurring_payment": false } } } } } ' ``` ``` { "payment_id": "pay_WXbt7aYJDjO0DvyZRpsf", "merchant_id": "merchant_1739867293", "status": "failed", "amount": 0, "net_amount": 0, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "cybersource", "client_secret": "pay_WXbt7aYJDjO0DvyZRpsf_secret_qZUj82yqxmREZX3MBnTR", "created": "2025-02-18T08:29:27.643Z", "currency": "USD", "customer_id": "cu_1739867368", "customer": { "id": "cu_1739867368", "name": "Joseph Doe", "email": "[email protected]", "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": { "samsung_pay": { "last4": "1661", "card_network": "Visa", "type": null } }, "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": "[email protected]", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "next_action": null, "cancellation_reason": null, "error_code": "SERVER_ERROR", "error_message": "SERVER_ERROR", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "samsung_pay", "connector_label": "cybersource_US_default_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1739867368", "created_at": 1739867367, "expires": 1739870967, "secret": "epk_7c1492ae7ec84198a64f11a089f48508" }, "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_lUspT7TZ8NWvqh6aWiEy", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_oGt66qf0Ct6bRlh8P9BN", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-02-18T08:44:27.643Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-02-18T08:29:28.698Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.112.0
d6e13dd0c87537e6696dd6dfc02280f825d116ab
d6e13dd0c87537e6696dd6dfc02280f825d116ab
juspay/hyperswitch
juspay__hyperswitch-7306
Bug: [CYPRESS] Fiuu Connector Configuration and Payment Processing Issues The FIUU Connector is not functioning as expected. ### Expected Behavior: - The Fiuu Connector should be configurable without errors. - Test Cases should pass successfully through the Fiuu Payment Connector. ### Actual Behavior: - Errors occur during the configuration process. - Test Cases do not go through as expected.
2025-02-18T12:33:02Z
## Type of Change - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> The FIUU Connector was not functioning as expected. ## Key Changes - Added fiuu connector configs for `PaymentConfirmWithShippingCost`, `ZeroAuthMandate`, and `SaveCardConfirmAutoCaptureOffSessionWithoutBilling`. - Added `billing.email` in some places in the configs where it was a required parameter. - Mapped `error_message: "The currency not allow for the RecordType"` wherever necessary. - Mandate Payments using PMID responds with the `connector_transaction_id: null` if the payment fails. So, changed the command accordingly. - Fiuu does not support Connector Diagnostic, so updated the exclusion list to include Fiuu connector. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] 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). --> ## How did you test it? Initial Condition <img width="710" alt="image" src="https://github.com/user-attachments/assets/976bb14e-c200-4d34-a61d-a8ab46115824" /> Current Condition <img width="710" alt="image" src="https://github.com/user-attachments/assets/3f01b9c3-3de1-468a-b022-2733d1c03c0b" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
c0c08d05ef04d914e07d49f163e43bdddf5c885b
c0c08d05ef04d914e07d49f163e43bdddf5c885b
juspay/hyperswitch
juspay__hyperswitch-7289
Bug: [BUG] Fix contract updation for Contract routing ### Feature Description We need to update the contract once it is not found in the dynamic routing service. ### Possible Implementation The updation happening in the post-update tracker does not work when the payment goes through a different connector. Need to set the contract when fetch fails. ### 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/external_services/src/grpc_client/dynamic_routing.rs b/crates/external_services/src/grpc_client/dynamic_routing.rs index e34f721b30e..67069b9fe8b 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing.rs @@ -32,9 +32,12 @@ pub enum DynamicRoutingError { #[error("Error from Dynamic Routing Server while perfrming success_rate analysis : {0}")] SuccessRateBasedRoutingFailure(String), - /// Error from Dynamic Routing Server while performing contract based routing + /// Generic Error from Dynamic Routing Server while performing contract based routing #[error("Error from Dynamic Routing Server while performing contract based routing: {0}")] ContractBasedRoutingFailure(String), + /// Generic Error from Dynamic Routing Server while performing contract based routing + #[error("Contract not found in the dynamic routing service")] + ContractNotFound, /// Error from Dynamic Routing Server while perfrming elimination #[error("Error from Dynamic Routing Server while perfrming elimination : {0}")] EliminationRateRoutingFailure(String), diff --git a/crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs index b210d996bc0..ff16594ca6e 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs @@ -26,6 +26,8 @@ use crate::grpc_client::{self, GrpcHeaders}; pub mod contract_routing { tonic::include_proto!("contract_routing"); } +pub use tonic::Code; + use super::{Client, DynamicRoutingError, DynamicRoutingResult}; /// The trait ContractBasedDynamicRouting would have the functions required to support the calculation and updation window #[async_trait::async_trait] @@ -46,6 +48,7 @@ pub trait ContractBasedDynamicRouting: dyn_clone::DynClone + Send + Sync { label_info: Vec<LabelInformation>, params: String, response: Vec<RoutableConnectorChoiceWithStatus>, + incr_count: u64, headers: GrpcHeaders, ) -> DynamicRoutingResult<UpdateContractResponse>; /// To invalidates the contract scores against the id @@ -90,9 +93,10 @@ impl ContractBasedDynamicRouting for ContractScoreCalculatorClient<Client> { .clone() .fetch_contract_score(request) .await - .change_context(DynamicRoutingError::ContractBasedRoutingFailure( - "Failed to fetch the contract score".to_string(), - ))? + .map_err(|err| match err.code() { + Code::NotFound => DynamicRoutingError::ContractNotFound, + _ => DynamicRoutingError::ContractBasedRoutingFailure(err.to_string()), + })? .into_inner(); logger::info!(dynamic_routing_response=?response); @@ -106,13 +110,18 @@ impl ContractBasedDynamicRouting for ContractScoreCalculatorClient<Client> { label_info: Vec<LabelInformation>, params: String, _response: Vec<RoutableConnectorChoiceWithStatus>, + incr_count: u64, headers: GrpcHeaders, ) -> DynamicRoutingResult<UpdateContractResponse> { - let labels_information = label_info + let mut labels_information = label_info .into_iter() .map(ProtoLabelInfo::foreign_from) .collect::<Vec<_>>(); + labels_information + .iter_mut() + .for_each(|info| info.current_count += incr_count); + let request = grpc_client::create_grpc_request( UpdateContractRequest { id, @@ -183,10 +192,14 @@ impl ForeignTryFrom<ContractBasedRoutingConfigBody> for CalContractScoreConfig { impl ForeignFrom<LabelInformation> for ProtoLabelInfo { fn foreign_from(config: LabelInformation) -> Self { Self { - label: config.label, + label: format!( + "{}:{}", + config.label.clone(), + config.mca_id.get_string_repr() + ), target_count: config.target_count, target_time: config.target_time, - current_count: 1, + current_count: u64::default(), } } } diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index d06ffea581f..215f262ea8b 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -400,8 +400,10 @@ pub enum RoutingError { ContractBasedRoutingConfigError, #[error("Params not found in contract based routing config")] ContractBasedRoutingParamsNotFoundError, - #[error("Unable to calculate contract score from dynamic routing service")] - ContractScoreCalculationError, + #[error("Unable to calculate contract score from dynamic routing service: '{err}'")] + ContractScoreCalculationError { err: String }, + #[error("Unable to update contract score on dynamic routing service")] + ContractScoreUpdationError, #[error("contract routing client from dynamic routing gRPC service not initialized")] ContractRoutingClientInitializationError, #[error("Invalid contract based connector label received from dynamic routing service: '{0}'")] diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index cf5cd35fb98..e78861d4327 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -26,8 +26,9 @@ use euclid::{ }; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use external_services::grpc_client::dynamic_routing::{ - contract_routing_client::{CalContractScoreResponse, ContractBasedDynamicRouting}, + contract_routing_client::ContractBasedDynamicRouting, success_rate_client::{CalSuccessRateResponse, SuccessBasedDynamicRouting}, + DynamicRoutingError, }; use hyperswitch_domain_models::address::Address; use kgraph_utils::{ @@ -1599,19 +1600,57 @@ pub async fn perform_contract_based_routing( .change_context(errors::RoutingError::ContractBasedRoutingConfigError) .attach_printable("unable to fetch contract based dynamic routing configs")?; - let contract_based_connectors: CalContractScoreResponse = client + let contract_based_connectors_result = client .calculate_contract_score( profile_id.get_string_repr().into(), - contract_based_routing_configs, + contract_based_routing_configs.clone(), "".to_string(), routable_connectors, state.get_grpc_headers(), ) .await - .change_context(errors::RoutingError::ContractScoreCalculationError) .attach_printable( "unable to calculate/fetch contract score from dynamic routing service", - )?; + ); + + let contract_based_connectors = match contract_based_connectors_result { + Ok(resp) => resp, + Err(err) => match err.current_context() { + DynamicRoutingError::ContractNotFound => { + let label_info = contract_based_routing_configs + .label_info + .ok_or(errors::RoutingError::ContractBasedRoutingConfigError) + .attach_printable( + "Label information not found in contract routing configs", + )?; + + client + .update_contracts( + profile_id.get_string_repr().into(), + label_info, + "".to_string(), + vec![], + u64::default(), + state.get_grpc_headers(), + ) + .await + .change_context(errors::RoutingError::ContractScoreUpdationError) + .attach_printable( + "unable to update contract based routing window in dynamic routing service", + )?; + return Err((errors::RoutingError::ContractScoreCalculationError { + err: err.to_string(), + }) + .into()); + } + _ => { + return Err((errors::RoutingError::ContractScoreCalculationError { + err: err.to_string(), + }) + .into()) + } + }, + }; let mut connectors = Vec::with_capacity(contract_based_connectors.labels_with_score.len()); diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index b8a7ee5dc1c..17edc50a30d 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -1036,11 +1036,7 @@ pub async fn push_metrics_with_update_window_for_contract_based_routing( ); let request_label_info = routing_types::LabelInformation { - label: format!( - "{}:{}", - final_label_info.label.clone(), - final_label_info.mca_id.get_string_repr() - ), + label: final_label_info.label.clone(), target_count: final_label_info.target_count, target_time: final_label_info.target_time, mca_id: final_label_info.mca_id.to_owned(), @@ -1056,6 +1052,7 @@ pub async fn push_metrics_with_update_window_for_contract_based_routing( vec![request_label_info], "".to_string(), vec![], + 1, state.get_grpc_headers(), ) .await
2025-02-14T15:17:21Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Fixed the contract updation when contract is not set in dynamo. If contract is not set, we'll set in the same flow. This fixes an issue. ### 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)? --> Same as https://github.com/juspay/hyperswitch/pull/6761 New error log - ![image](https://github.com/user-attachments/assets/26b7f7c0-ac06-4d8c-9996-d08f4c5b74fb) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.112.0
0688972814cf03edbff4bf125a59c338a7e49593
0688972814cf03edbff4bf125a59c338a7e49593
juspay/hyperswitch
juspay__hyperswitch-7294
Bug: [MASKING] add peek_mut function in PeekInterface
diff --git a/crates/masking/src/abs.rs b/crates/masking/src/abs.rs index 6501f89c9db..8996db65f23 100644 --- a/crates/masking/src/abs.rs +++ b/crates/masking/src/abs.rs @@ -6,6 +6,9 @@ use crate::Secret; pub trait PeekInterface<S> { /// Only method providing access to the secret value. fn peek(&self) -> &S; + + /// Provide a mutable reference to the inner value. + fn peek_mut(&mut self) -> &mut S; } /// Interface that consumes a option secret and returns the value. diff --git a/crates/masking/src/bytes.rs b/crates/masking/src/bytes.rs index e828f8a78e0..07b8c289ad8 100644 --- a/crates/masking/src/bytes.rs +++ b/crates/masking/src/bytes.rs @@ -28,6 +28,10 @@ impl PeekInterface<BytesMut> for SecretBytesMut { fn peek(&self) -> &BytesMut { &self.0 } + + fn peek_mut(&mut self) -> &mut BytesMut { + &mut self.0 + } } impl fmt::Debug for SecretBytesMut { diff --git a/crates/masking/src/secret.rs b/crates/masking/src/secret.rs index 7f7c18094a0..ee65b1c015b 100644 --- a/crates/masking/src/secret.rs +++ b/crates/masking/src/secret.rs @@ -95,6 +95,10 @@ where fn peek(&self) -> &SecretValue { &self.inner_secret } + + fn peek_mut(&mut self) -> &mut SecretValue { + &mut self.inner_secret + } } impl<SecretValue, MaskingStrategy> From<SecretValue> for Secret<SecretValue, MaskingStrategy> diff --git a/crates/masking/src/strong_secret.rs b/crates/masking/src/strong_secret.rs index 300b5463d25..43d2c97dfb3 100644 --- a/crates/masking/src/strong_secret.rs +++ b/crates/masking/src/strong_secret.rs @@ -32,6 +32,10 @@ impl<Secret: ZeroizableSecret, MaskingStrategy> PeekInterface<Secret> fn peek(&self) -> &Secret { &self.inner_secret } + + fn peek_mut(&mut self) -> &mut Secret { + &mut self.inner_secret + } } impl<Secret: ZeroizableSecret, MaskingStrategy> From<Secret>
2025-02-17T09:29:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Enhancement ## Description <!-- Describe your changes in detail --> Add `peek_mut` function to PeekInterface to get mutable reference for the inner data. ## 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 get the mutable reference for inner data in StrongSecret. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ** THIS CANNOT BE TESTED IN ENVIRONMENTS ** ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code
v1.112.0
3607b30c26cc24341bf88f8ce9968e094fb7a60a
3607b30c26cc24341bf88f8ce9968e094fb7a60a
juspay/hyperswitch
juspay__hyperswitch-7292
Bug: South African EFT Payment Method Integration via Paystack ### Feature Description This issue tracks the implementation of EFT (Electronic Funds Transfer) as a payment method in Hyperswitch system. The feature involves generating the necessary template code, integrating EFT as a supported payment method, and completing all required payment flows for Paystack connector. Paystack's Documentation [Link](https://paystack.com/docs/api/) Add new connector documentation [Link](https://github.com/juspay/hyperswitch/blob/main/add_connector_updated.md) ### Possible Implementation - [x] #7314 - [x] #7313 - [x] #7315 - [x] #7316 - [x] #7317
diff --git a/connector-template/mod.rs b/connector-template/mod.rs index 80330a97429..75f2f02c027 100644 --- a/connector-template/mod.rs +++ b/connector-template/mod.rs @@ -1,7 +1,6 @@ mod transformers; use std::fmt::Debug; -use common_utils::errors::ReportSwitchExt; use error_stack::{ResultExt, IntoReport}; use crate::{ diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs index 985c68a99c0..7e3caf100e1 100644 --- a/connector-template/transformers.rs +++ b/connector-template/transformers.rs @@ -30,7 +30,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for {{project-name | downcase expiry_month: req_card.card_exp_month, expiry_year: req_card.card_exp_year, cvc: req_card.card_cvc, - complete: item.request.is_auto_capture(), + complete: item.request.is_auto_capture()?, }; Ok(Self { amount: item.request.amount,
2023-04-18T16:43:29Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description <!-- Describe your changes in detail --> When `add_connector.sh` is called to generate new connector files `mod.rs` had an unused declaration, removed it. At the time of development, if needed, one can import it directly instead of pre-bloating the stuff. `Transformers.rs` straight away failed and threw an error addressing `mismatched types` as it is expecting `bool` while were providing `Result<bool, Error>`. ### Additional Changes - [ ] 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` --> connector-template/mod.rs connector-template/transformers.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 its an obvious bug or documentation fix that will have little conversation). --> With the changes made, unexpected errors and warnings at the time of generation of connector code is avoided and addressed. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
v0.5.7
9c9c52f9af74ebc7e835a5750dd05967b39a0ade
9c9c52f9af74ebc7e835a5750dd05967b39a0ade
juspay/hyperswitch
juspay__hyperswitch-7283
Bug: feat(connector): add template code for recurly add a template code for recurly connector
diff --git a/config/config.example.toml b/config/config.example.toml index 9e54c7e8c88..453e1161284 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -255,6 +255,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" razorpay.base_url = "https://sandbox.juspay.in/" +recurly.base_url = "https://{{merchant_subdomain_name}}.recurly.com" redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago" riskified.base_url = "https://sandbox.riskified.com/api" shift4.base_url = "https://api.shift4.com/" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index c8eb14c9853..a6a7a09e16e 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -100,6 +100,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" razorpay.base_url = "https://sandbox.juspay.in/" +recurly.base_url = "https://{{merchant_subdomain_name}}.recurly.com" redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago" shift4.base_url = "https://api.shift4.com/" signifyd.base_url = "https://api.signifyd.com/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 90ca4ae143d..e8f2c30c696 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -104,6 +104,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" razorpay.base_url = "https://api.juspay.in" +recurly.base_url = "https://{{merchant_subdomain_name}}.recurly.com" redsys.base_url = "https://sis.redsys.es:25443/sis/realizarPago" riskified.base_url = "https://wh.riskified.com/api/" shift4.base_url = "https://api.shift4.com/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 29e60131149..302ff6f3a0c 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -104,6 +104,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" razorpay.base_url = "https://sandbox.juspay.in/" +recurly.base_url = "https://{{merchant_subdomain_name}}.recurly.com" redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago" riskified.base_url = "https://sandbox.riskified.com/api" shift4.base_url = "https://api.shift4.com/" diff --git a/config/development.toml b/config/development.toml index 7619f992aab..b81080740fd 100644 --- a/config/development.toml +++ b/config/development.toml @@ -327,6 +327,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" razorpay.base_url = "https://sandbox.juspay.in/" +recurly.base_url = "https://{{merchant_subdomain_name}}.recurly.com" redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago" riskified.base_url = "https://sandbox.riskified.com/api" shift4.base_url = "https://api.shift4.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 58cf75fb8d2..83aa883a164 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -187,6 +187,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" razorpay.base_url = "https://sandbox.juspay.in/" +recurly.base_url = "https://{{merchant_subdomain_name}}.recurly.com" redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago" riskified.base_url = "https://sandbox.riskified.com/api" shift4.base_url = "https://api.shift4.com/" diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index cadca5fad02..65fa444175e 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -116,6 +116,7 @@ pub enum RoutableConnectors { Prophetpay, Rapyd, Razorpay, + // Recurly, // Redsys, Riskified, Shift4, @@ -259,6 +260,7 @@ pub enum Connector { Prophetpay, Rapyd, Razorpay, + //Recurly, // Redsys, Shift4, Square, @@ -408,6 +410,7 @@ impl Connector { | Self::Powertranz | Self::Prophetpay | Self::Rapyd + // | Self::Recurly // | Self::Redsys | Self::Shift4 | Self::Square @@ -543,6 +546,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Prophetpay => Self::Prophetpay, RoutableConnectors::Rapyd => Self::Rapyd, RoutableConnectors::Razorpay => Self::Razorpay, + // RoutableConnectors::Recurly => Self::Recurly, RoutableConnectors::Riskified => Self::Riskified, RoutableConnectors::Shift4 => Self::Shift4, RoutableConnectors::Signifyd => Self::Signifyd, diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 6fa0d9e103e..495228de0c9 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -59,6 +59,7 @@ pub mod powertranz; pub mod prophetpay; pub mod rapyd; pub mod razorpay; +pub mod recurly; pub mod redsys; pub mod shift4; pub mod square; @@ -92,8 +93,8 @@ pub use self::{ noon::Noon, novalnet::Novalnet, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, paystack::Paystack, payu::Payu, placetopay::Placetopay, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, - redsys::Redsys, shift4::Shift4, square::Square, stax::Stax, stripebilling::Stripebilling, - taxjar::Taxjar, thunes::Thunes, trustpay::Trustpay, tsys::Tsys, + recurly::Recurly, redsys::Redsys, shift4::Shift4, square::Square, stax::Stax, + stripebilling::Stripebilling, taxjar::Taxjar, thunes::Thunes, trustpay::Trustpay, tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, volt::Volt, wellsfargo::Wellsfargo, worldline::Worldline, worldpay::Worldpay, xendit::Xendit, zen::Zen, zsl::Zsl, diff --git a/crates/hyperswitch_connectors/src/connectors/recurly.rs b/crates/hyperswitch_connectors/src/connectors/recurly.rs new file mode 100644 index 00000000000..c16810a6ab7 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/recurly.rs @@ -0,0 +1,568 @@ +pub mod transformers; + +use common_utils::{ + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, +}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundSyncRouterData, RefundsRouterData, + }, +}; +use hyperswitch_interfaces::{ + api::{ + self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, + ConnectorValidation, + }, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{self, Response}, + webhooks, +}; +use masking::{ExposeInterface, Mask}; +use transformers as recurly; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Recurly { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Recurly { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Recurly {} +impl api::PaymentSession for Recurly {} +impl api::ConnectorAccessToken for Recurly {} +impl api::MandateSetup for Recurly {} +impl api::PaymentAuthorize for Recurly {} +impl api::PaymentSync for Recurly {} +impl api::PaymentCapture for Recurly {} +impl api::PaymentVoid for Recurly {} +impl api::Refund for Recurly {} +impl api::RefundExecute for Recurly {} +impl api::RefundSync for Recurly {} +impl api::PaymentToken for Recurly {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Recurly +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Recurly +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + +impl ConnectorCommon for Recurly { + fn id(&self) -> &'static str { + "recurly" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + // TODO! Check connector documentation, on which unit they are processing the currency. + // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, + // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.recurly.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = recurly::RecurlyAuthType::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: recurly::RecurlyErrorResponse = res + .response + .parse_struct("RecurlyErrorResponse") + .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 Recurly { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Recurly { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Recurly {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Recurly {} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Recurly { + fn get_headers( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + + let connector_router_data = recurly::RecurlyRouterData::from((amount, req)); + let connector_req = recurly::RecurlyPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: recurly::RecurlyPaymentsResponse = res + .response + .parse_struct("Recurly PaymentsAuthorizeResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Recurly { + fn get_headers( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { + let response: recurly::RecurlyPaymentsResponse = res + .response + .parse_struct("recurly PaymentsSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Recurly { + fn get_headers( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCaptureType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { + let response: recurly::RecurlyPaymentsResponse = res + .response + .parse_struct("Recurly PaymentsCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Recurly {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Recurly { + fn get_headers( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let refund_amount = utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, + req.request.currency, + )?; + + let connector_router_data = recurly::RecurlyRouterData::from((refund_amount, req)); + let connector_req = recurly::RecurlyRefundRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .set_body(types::RefundExecuteType::get_request_body( + self, req, connectors, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &RefundsRouterData<Execute>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { + let response: recurly::RefundResponse = res + .response + .parse_struct("recurly RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Recurly { + fn get_headers( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .set_body(types::RefundSyncType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { + let response: recurly::RefundResponse = res + .response + .parse_struct("recurly RefundSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[async_trait::async_trait] +impl webhooks::IncomingWebhook for Recurly { + fn get_webhook_object_reference_id( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_event_type( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_resource_object( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } +} + +impl ConnectorSpecifications for Recurly {} diff --git a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs new file mode 100644 index 00000000000..bc62985edb3 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs @@ -0,0 +1,228 @@ +use common_enums::enums; +use common_utils::types::StringMinorUnit; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{ConnectorAuthType, RouterData}, + router_flow_types::refunds::{Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{PaymentsAuthorizeRouterData, RefundsRouterData}, +}; +use hyperswitch_interfaces::errors; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::PaymentsAuthorizeRequestData, +}; + +//TODO: Fill the struct with respective fields +pub struct RecurlyRouterData<T> { + pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> From<(StringMinorUnit, T)> for RecurlyRouterData<T> { + fn from((amount, item): (StringMinorUnit, T)) -> Self { + //Todo : use utils to convert the amount to the type of amount that a connector accepts + Self { + amount, + router_data: item, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, PartialEq)] +pub struct RecurlyPaymentsRequest { + amount: StringMinorUnit, + card: RecurlyCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct RecurlyCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&RecurlyRouterData<&PaymentsAuthorizeRouterData>> for RecurlyPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &RecurlyRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(req_card) => { + let card = RecurlyCard { + number: req_card.card_number, + expiry_month: req_card.card_exp_month, + expiry_year: req_card.card_exp_year, + cvc: req_card.card_cvc, + complete: item.router_data.request.is_auto_capture()?, + }; + Ok(Self { + amount: item.amount.clone(), + card, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct RecurlyAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for RecurlyAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + api_key: api_key.to_owned(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} +// PaymentsResponse +//TODO: Append the remaining status flags +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum RecurlyPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<RecurlyPaymentStatus> for common_enums::AttemptStatus { + fn from(item: RecurlyPaymentStatus) -> Self { + match item { + RecurlyPaymentStatus::Succeeded => Self::Charged, + RecurlyPaymentStatus::Failed => Self::Failure, + RecurlyPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct RecurlyPaymentsResponse { + status: RecurlyPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, RecurlyPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, RecurlyPaymentsResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: common_enums::AttemptStatus::from(item.response.status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct RecurlyRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&RecurlyRouterData<&RefundsRouterData<F>>> for RecurlyRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &RecurlyRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Serialize, Default, Deserialize, Clone)] +pub enum RefundStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Succeeded => Self::Success, + RefundStatus::Failed => Self::Failure, + RefundStatus::Processing => Self::Pending, + //TODO: Review mapping + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct RefundResponse { + id: String, + status: RefundStatus, +} + +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct RecurlyErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index f64f624187a..ad9e456c948 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -156,6 +156,7 @@ default_imp_for_authorize_session_token!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -250,6 +251,7 @@ default_imp_for_calculate_tax!( connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -319,6 +321,7 @@ default_imp_for_session_update!( connectors::Klarna, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -415,6 +418,7 @@ default_imp_for_post_session_tokens!( connectors::Klarna, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -520,6 +524,7 @@ default_imp_for_complete_authorize!( connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Stax, connectors::Square, @@ -613,6 +618,7 @@ default_imp_for_incremental_authorization!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -707,6 +713,7 @@ default_imp_for_create_customer!( connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Square, @@ -789,6 +796,7 @@ default_imp_for_connector_redirect_response!( connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -875,6 +883,7 @@ default_imp_for_pre_processing_steps!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Stax, connectors::Square, @@ -968,6 +977,7 @@ default_imp_for_post_processing_steps!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1064,6 +1074,7 @@ default_imp_for_approve!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1160,6 +1171,7 @@ default_imp_for_reject!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1256,6 +1268,7 @@ default_imp_for_webhook_source_verification!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1352,6 +1365,7 @@ default_imp_for_accept_dispute!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1447,6 +1461,7 @@ default_imp_for_submit_evidence!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1542,6 +1557,7 @@ default_imp_for_defend_dispute!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1646,6 +1662,7 @@ default_imp_for_file_upload!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1733,6 +1750,7 @@ default_imp_for_payouts!( connectors::Prophetpay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Square, @@ -1829,6 +1847,7 @@ default_imp_for_payouts_create!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1926,6 +1945,7 @@ default_imp_for_payouts_retrieve!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -2023,6 +2043,7 @@ default_imp_for_payouts_eligibility!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -2119,6 +2140,7 @@ default_imp_for_payouts_fulfill!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -2216,6 +2238,7 @@ default_imp_for_payouts_cancel!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -2313,6 +2336,7 @@ default_imp_for_payouts_quote!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -2410,6 +2434,7 @@ default_imp_for_payouts_recipient!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -2507,6 +2532,7 @@ default_imp_for_payouts_recipient_account!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -2605,6 +2631,7 @@ default_imp_for_frm_sale!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -2703,6 +2730,7 @@ default_imp_for_frm_checkout!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -2801,6 +2829,7 @@ default_imp_for_frm_transaction!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -2899,6 +2928,7 @@ default_imp_for_frm_fulfillment!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -2997,6 +3027,7 @@ default_imp_for_frm_record_return!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -3090,6 +3121,7 @@ default_imp_for_revoking_mandates!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -3186,6 +3218,7 @@ default_imp_for_uas_pre_authentication!( connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -3280,6 +3313,7 @@ default_imp_for_uas_post_authentication!( connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -3374,6 +3408,7 @@ default_imp_for_uas_authentication!( connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -3469,6 +3504,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index f333800480b..972a26adf36 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -265,6 +265,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -362,6 +363,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -454,6 +456,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -551,6 +554,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -647,6 +651,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -744,6 +749,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -851,6 +857,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -950,6 +957,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1049,6 +1057,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1148,6 +1157,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1247,6 +1257,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1346,6 +1357,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1445,6 +1457,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1544,6 +1557,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1643,6 +1657,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1740,6 +1755,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1839,6 +1855,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -1938,6 +1955,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -2037,6 +2055,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -2136,6 +2155,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -2235,6 +2255,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, @@ -2331,6 +2352,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Multisafepay, connectors::Rapyd, connectors::Razorpay, + connectors::Recurly, connectors::Redsys, connectors::Shift4, connectors::Stax, diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs index 5b46184c363..e3177856925 100644 --- a/crates/hyperswitch_interfaces/src/configs.rs +++ b/crates/hyperswitch_interfaces/src/configs.rs @@ -81,6 +81,7 @@ pub struct Connectors { pub prophetpay: ConnectorParams, pub rapyd: ConnectorParams, pub razorpay: ConnectorParamsWithKeys, + pub recurly: ConnectorParams, pub redsys: ConnectorParams, pub riskified: ConnectorParams, pub shift4: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 9f99b4c61a3..a89ae69451c 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -38,12 +38,12 @@ pub use hyperswitch_connectors::connectors::{ opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payme, payme::Payme, paystack, paystack::Paystack, payu, payu::Payu, placetopay, placetopay::Placetopay, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, - razorpay::Razorpay, redsys, redsys::Redsys, shift4, shift4::Shift4, square, square::Square, - stax, stax::Stax, stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, thunes, - thunes::Thunes, trustpay, trustpay::Trustpay, tsys, tsys::Tsys, unified_authentication_service, - unified_authentication_service::UnifiedAuthenticationService, volt, volt::Volt, wellsfargo, - wellsfargo::Wellsfargo, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, xendit, - xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, + razorpay::Razorpay, recurly::Recurly, redsys, redsys::Redsys, shift4, shift4::Shift4, square, + square::Square, stax, stax::Stax, stripebilling, stripebilling::Stripebilling, taxjar, + taxjar::Taxjar, thunes, thunes::Thunes, trustpay, trustpay::Trustpay, tsys, tsys::Tsys, + unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, + volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, worldline, worldline::Worldline, + worldpay, worldpay::Worldpay, xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, }; #[cfg(feature = "dummy_connector")] diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs index 4f963755b1b..8d38b84a001 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -985,6 +985,7 @@ default_imp_for_new_connector_integration_payouts!( connector::Powertranz, connector::Rapyd, connector::Razorpay, + connector::Recurly, connector::Redsys, connector::Riskified, connector::Signifyd, @@ -1390,6 +1391,7 @@ default_imp_for_new_connector_integration_frm!( connector::Powertranz, connector::Rapyd, connector::Razorpay, + connector::Recurly, connector::Redsys, connector::Riskified, connector::Signifyd, @@ -1729,6 +1731,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, + connector::Recurly, connector::Redsys, connector::Riskified, connector::Signifyd, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 02a4fe2386c..7e5cdfdaa37 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -439,6 +439,7 @@ default_imp_for_connector_request_id!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, + connector::Recurly, connector::Redsys, connector::Riskified, connector::Shift4, @@ -1289,6 +1290,7 @@ default_imp_for_fraud_check!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, + connector::Recurly, connector::Redsys, connector::Shift4, connector::Square, @@ -1778,6 +1780,7 @@ default_imp_for_connector_authentication!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, + connector::Recurly, connector::Redsys, connector::Riskified, connector::Shift4, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index a32e0457dfa..c4c2371abf8 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -510,6 +510,7 @@ impl ConnectorData { enums::Connector::Rapyd => { Ok(ConnectorEnum::Old(Box::new(connector::Rapyd::new()))) } + // enums::Connector::Recurly => Ok(ConnectorEnum::Old(Box::new(connector::Recurly))), // enums::Connector::Redsys => Ok(ConnectorEnum::Old(Box::new(connector::Redsys))), enums::Connector::Shift4 => { Ok(ConnectorEnum::Old(Box::new(connector::Shift4::new()))) diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 514ddbbbb50..6ab4111f4b7 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -290,6 +290,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Prophetpay => Self::Prophetpay, api_enums::Connector::Rapyd => Self::Rapyd, api_enums::Connector::Razorpay => Self::Razorpay, + // api_enums::Connector::Recurly => Self::Recurly, // api_enums::Connector::Redsys => Self::Redsys, api_enums::Connector::Shift4 => Self::Shift4, api_enums::Connector::Signifyd => { diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 09718d56181..040b2dd6317 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -78,6 +78,7 @@ mod powertranz; mod prophetpay; mod rapyd; mod razorpay; +mod recurly; mod redsys; mod shift4; mod square; diff --git a/crates/router/tests/connectors/recurly.rs b/crates/router/tests/connectors/recurly.rs new file mode 100644 index 00000000000..a38ed49d415 --- /dev/null +++ b/crates/router/tests/connectors/recurly.rs @@ -0,0 +1,421 @@ +use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; +use masking::Secret; +use router::types::{self, api, storage::enums}; +use test_utils::connector_auth; + +use crate::utils::{self, ConnectorActions}; + +#[derive(Clone, Copy)] +struct RecurlyTest; +impl ConnectorActions for RecurlyTest {} +impl utils::Connector for RecurlyTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Recurly; + utils::construct_connector_data_old( + Box::new(Recurly::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .recurly + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "Recurly".to_string() + } +} + +static CONNECTOR: RecurlyTest = RecurlyTest {}; + +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + None +} + +fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { + None +} + +// Cards Positive Tests +// Creates a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +// Captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Partially captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + payment_method_details(), + Some(types::PaymentsCaptureData { + amount_to_capture: 50, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +// Voids a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment( + payment_method_details(), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("Void payment response"); + assert_eq!(response.status, enums::AttemptStatus::Voided); +} + +// Refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Synchronizes a refund using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_manually_captured_refund() { + let refund_response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_make_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_auto_captured_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + capture_method: Some(enums::CaptureMethod::Automatic), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Charged,); +} + +// Refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_auto_captured_payment() { + let response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let refund_response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + CONNECTOR + .make_payment_and_multiple_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await; +} + +// Synchronizes a refund using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_refund() { + let refund_response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Cards Negative scenarios +// Creates a payment with incorrect CVC. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's security code is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry month. +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration month is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry year. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_expiry_year() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration year is invalid.".to_string(), + ); +} + +// Voids a payment using automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_fail_void_payment_for_auto_capture() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let void_response = CONNECTOR + .void_payment(txn_id.unwrap(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + void_response.response.unwrap_err().message, + "You cannot cancel this PaymentIntent because it has a status of succeeded." + ); +} + +// Captures a payment using invalid connector payment id. +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let capture_response = CONNECTOR + .capture_payment("123456789".to_string(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("No such payment_intent: '123456789'") + ); +} + +// Refunds a payment with refund amount higher than payment amount. +#[actix_web::test] +async fn should_fail_for_refund_amount_higher_than_payment_amount() { + let response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Refund amount (₹1.50) is greater than charge amount (₹1.00)", + ); +} + +// Connector dependent test cases goes here + +// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index d30a5008887..0650e5e6a4d 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -320,4 +320,7 @@ api_key= "API Key" api_key= "API Key" [paystack] -api_key = "API Key" \ No newline at end of file +api_key = "API Key" + +[recurly] +api_key= "API Key" \ No newline at end of file diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index bb40cc51eaa..f19d5d22e80 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -82,6 +82,7 @@ pub struct ConnectorAuthentication { pub prophetpay: Option<HeaderKey>, pub rapyd: Option<BodyKey>, pub razorpay: Option<BodyKey>, + pub recurly: Option<HeaderKey>, pub redsys: Option<HeaderKey>, pub shift4: Option<HeaderKey>, pub square: Option<BodyKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 526899b7fff..6b1afeab21e 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -153,6 +153,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" razorpay.base_url = "https://sandbox.juspay.in/" +recurly.base_url = "https://{{merchant_subdomain_name}}.recurly.com" redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago" riskified.base_url = "https://sandbox.riskified.com/api" shift4.base_url = "https://api.shift4.com/" diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 046042bfa73..022e54a943c 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 amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte getnet globalpay globepay gocardless gpayments helcim iatapay inespay itaubank jpmorgan klarna mifinity mollie moneris multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal paystack payu placetopay plaid powertranz prophetpay rapyd razorpay redsys shift4 square stax stripe stripebilling taxjar threedsecureio thunes trustpay tsys unified_authentication_service volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1") + connectors=(aci adyen adyenplatform airwallex amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte getnet globalpay globepay gocardless gpayments helcim iatapay inespay itaubank jpmorgan klarna mifinity mollie moneris multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal paystack payu placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys shift4 square stax stripe stripebilling taxjar threedsecureio thunes trustpay tsys unified_authentication_service volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res="$(echo ${sorted[@]})" sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
2025-02-17T11:09:07Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> connector integration template code for recurly. Issue: This PR closes the issue #7283 ### 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)? --> No testing required since its a template code ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
8e922d30da367bc0baf3cba64a86c385764fff39
8e922d30da367bc0baf3cba64a86c385764fff39