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-9240
Bug: [BUG] MIT for migrated wallet tokens does not go through ### Bug Description Creating MIT transactions for migrated wallets leads to unexpected behavior - <img width="1282" height="513" alt="Image" src="https://github.com/user-attachments/assets/cc889293-3916-4f0f-b2a8-8f034a373fee" /> Transaction is incorrectly marked as payment_method_type - debit leading to failed routing ### Expected Behavior Transaction should be routed as expected. ### Actual Behavior Migrated wallet MIT transaction is incorrectly marked with incorrect payment_method_type based on the card BIN. ### Steps To Reproduce 1. Migrate wallets (PSP tokens + additional card info - card expiry + last4 + card BIN) 2. Perform MIT transaction ### Context For The Bug - ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 0e343a437b6..bcd71636f05 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -662,6 +662,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> let payment_method_type = Option::<api_models::enums::PaymentMethodType>::foreign_from(( payment_method_type, additional_pm_data.as_ref(), + payment_method, )); payment_attempt.payment_method_type = payment_method_type diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 79bfbebf499..1f54b1b72a1 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -1266,6 +1266,7 @@ impl PaymentCreate { let payment_method_type = Option::<enums::PaymentMethodType>::foreign_from(( payment_method_type, additional_pm_data.as_ref(), + payment_method, )); // TODO: remove once https://github.com/juspay/hyperswitch/issues/7421 is fixed diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 66de9b4ee60..484a3ec757e 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -5961,38 +5961,67 @@ impl ForeignFrom<diesel_models::ConnectorTokenDetails> } } -impl ForeignFrom<(Self, Option<&api_models::payments::AdditionalPaymentData>)> - for Option<enums::PaymentMethodType> +impl + ForeignFrom<( + Self, + Option<&api_models::payments::AdditionalPaymentData>, + Option<enums::PaymentMethod>, + )> for Option<enums::PaymentMethodType> { - fn foreign_from(req: (Self, Option<&api_models::payments::AdditionalPaymentData>)) -> Self { - let (payment_method_type, additional_pm_data) = req; - additional_pm_data - .and_then(|pm_data| { - if let api_models::payments::AdditionalPaymentData::Card(card_info) = pm_data { - card_info.card_type.as_ref().and_then(|card_type_str| { - api_models::enums::PaymentMethodType::from_str(&card_type_str.to_lowercase()).map_err(|err| { - crate::logger::error!( - "Err - {:?}\nInvalid card_type value found in BIN DB - {:?}", - err, - card_type_str, - ); - }).ok() - }) - } else { - None - } - }) - .map_or(payment_method_type, |card_type_in_bin_store| { - if let Some(card_type_in_req) = payment_method_type { - if card_type_in_req != card_type_in_bin_store { + fn foreign_from( + req: ( + Self, + Option<&api_models::payments::AdditionalPaymentData>, + Option<enums::PaymentMethod>, + ), + ) -> Self { + let (payment_method_type, additional_pm_data, payment_method) = req; + + match (additional_pm_data, payment_method, payment_method_type) { + ( + Some(api_models::payments::AdditionalPaymentData::Card(card_info)), + Some(enums::PaymentMethod::Card), + original_type, + ) => { + let bin_card_type = card_info.card_type.as_ref().and_then(|card_type_str| { + let normalized_type = card_type_str.trim().to_lowercase(); + if normalized_type.is_empty() { + return None; + } + api_models::enums::PaymentMethodType::from_str(&normalized_type) + .map_err(|_| { + crate::logger::warn!("Invalid BIN card_type: '{}'", card_type_str); + }) + .ok() + }); + + match (original_type, bin_card_type) { + // Override when there's a mismatch + ( + Some( + original @ (enums::PaymentMethodType::Debit + | enums::PaymentMethodType::Credit), + ), + Some(bin_type), + ) if original != bin_type => { + crate::logger::info!("BIN lookup override: {} -> {}", original, bin_type); + bin_card_type + } + // Use BIN lookup if no original type exists + (None, Some(bin_type)) => { crate::logger::info!( - "Mismatch in card_type\nAPI request - {}; BIN lookup - {}\nOverriding with {}", - card_type_in_req, card_type_in_bin_store, card_type_in_bin_store, + "BIN lookup override: No original payment method type, using BIN result={}", + bin_type ); + Some(bin_type) } + // Default + _ => original_type, } - Some(card_type_in_bin_store) - }) + } + // Skip BIN lookup for non-card payments + _ => payment_method_type, + } } }
2025-09-02T09:51:17Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR updates the BIN lookup override logic in payment transformers.rs to ensure payment_method_type is overridden only for Card payment methods. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context This allows performing MIT wallet transactions for migrated wallet tokens. ## How did you test it? Locally <details> <summary>Run wallet migration</summary> cURL curl --location --request POST 'http://localhost:8080/payment_methods/migrate-batch' \ --header 'api-key: test_admin' \ --form 'merchant_id="merchant_1756795715"' \ --form 'merchant_connector_ids="mca_6wrjYYbE1zrrFSmbB0CJ"' \ --form 'file=@"wallet-migration.csv"' Response [ { "line_number": 1, "payment_method_id": "pm_edmFuErgTu8rvVwUtdTg", "payment_method": "wallet", "payment_method_type": "google_pay", "customer_id": "e4c4a19c2f92c9b61a65d1b1d31bdab9", "migration_status": "Success", "card_number_masked": "555555XXXXXX4444", "card_migrated": null, "network_token_migrated": true, "connector_mandate_details_migrated": true, "network_transaction_id_migrated": true }, { "line_number": 2, "payment_method_id": "pm_KC3l2F4HNRFiwVs8Xjaw", "payment_method": "wallet", "payment_method_type": "google_pay", "customer_id": "03ba537453a18466e42b2f9a92b70599", "migration_status": "Success", "card_number_masked": "411111XXXXXX1111", "card_migrated": null, "network_token_migrated": true, "connector_mandate_details_migrated": true, "network_transaction_id_migrated": true }, { "line_number": 3, "payment_method_id": "pm_zGxLnsiI4Eos0SPsY91Y", "payment_method": "wallet", "payment_method_type": "apple_pay", "customer_id": "c4ff0659d5e8775e9197092247355e8a", "migration_status": "Success", "card_number_masked": "520424XXXXXX7180", "card_migrated": null, "network_token_migrated": true, "connector_mandate_details_migrated": true, "network_transaction_id_migrated": true }, { "line_number": 4, "payment_method_id": "pm_6MueQrSZoca7NDcR5Ui9", "payment_method": "wallet", "payment_method_type": "apple_pay", "customer_id": "4b1f7771d465639a4856e0c246de8a50", "migration_status": "Success", "card_number_masked": "520424XXXXXX7180", "card_migrated": null, "network_token_migrated": true, "connector_mandate_details_migrated": true, "network_transaction_id_migrated": true } ] </details> <details> <summary>Perform wallet MIT using migrated token</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_3x1wBsCK5Er6sMaYvQFVxQdzpVi8wfDXgVm6stQ5yZAZfnU4MM5rGXHGjhVaZAIt' \ --data '{"amount":1000,"currency":"EUR","confirm":true,"capture_on":"2022-09-10T10:11:12Z","customer_id":"e4c4a19c2f92c9b61a65d1b1d31bdab9","profile_id":"pro_SQD3Im1aEzJIm2o6xobw","description":"Its my first payment request","return_url":"https://hyperswitch.io","off_session":true,"recurring_details":{"type":"payment_method_id","data":"pm_edmFuErgTu8rvVwUtdTg"}}' Response {"payment_id":"pay_B9cZsoExS75t62J5G5Gl","merchant_id":"merchant_1756795715","status":"succeeded","amount":1000,"net_amount":1000,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":"adyen","client_secret":"pay_B9cZsoExS75t62J5G5Gl_secret_1SKcL0XjWp8Rv0upzo7H","created":"2025-09-02T08:45:49.872Z","currency":"EUR","customer_id":"e4c4a19c2f92c9b61a65d1b1d31bdab9","customer":{"id":"e4c4a19c2f92c9b61a65d1b1d31bdab9","name":null,"email":"rsuolf2z6xlke@googlemail.com","phone":null,"phone_country_code":null},"description":"Its my first payment request","refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":true,"capture_on":null,"capture_method":null,"payment_method":"wallet","payment_method_data":{"card":{"last4":"4444","card_type":"CREDIT","card_network":"Mastercard","card_issuer":"MASTERCARD INTERNATIONAL","card_issuing_country":"BRAZIL","card_isin":"555555","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2027","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"rsuolf2z6xlke@googlemail.com","name":null,"phone":null,"return_url":"https://hyperswitch.io/","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":"UE_9000","unified_message":"Something went wrong","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":"e4c4a19c2f92c9b61a65d1b1d31bdab9","created_at":1756802749,"expires":1756806349,"secret":"epk_9c30790bc68a4fd997d53b17e9087a9f"},"manual_retry_allowed":true,"connector_transaction_id":"DZFZZDRD5HSN6KV5","frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":null,"payment_link":null,"profile_id":"pro_SQD3Im1aEzJIm2o6xobw","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_6wrjYYbE1zrrFSmbB0CJ","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-02T09:00:49.872Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":"pm_edmFuErgTu8rvVwUtdTg","network_transaction_id":null,"payment_method_status":"active","updated":"2025-09-02T08:45:51.392Z","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":"VVBV24y20uF-D20uVHTVD-12m14oZHDBZ20uRXT14oJ22w06g20u20u000232251","card_discovery":null,"force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null,"is_iframe_redirection_enabled":null,"whole_connector_response":null,"enable_partial_authorization":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 (logging enhancement - tests not applicable)
v1.116.0
10cf161d14810cc9c6320933909e9cd3bfdc41ca
10cf161d14810cc9c6320933909e9cd3bfdc41ca
juspay/hyperswitch
juspay__hyperswitch-9116
Bug: Connector changes for 3ds in v2 In v2, the `PreProcessing` and `CompleteAuthorize` flows will not be present. We will introduce new flows `PreAuthenticate`, `Authenticate` and `PostAuthenticate` to better represent the domain.
diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource.rs b/crates/hyperswitch_connectors/src/connectors/cybersource.rs index 0a1061e2c15..6b610c32912 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource.rs @@ -21,21 +21,22 @@ use hyperswitch_domain_models::{ PaymentMethodToken, Session, SetupMandate, Void, }, refunds::{Execute, RSync}, - PreProcessing, + Authenticate, PostAuthenticate, PreAuthenticate, PreProcessing, }, router_request_types::{ AccessTokenRequestData, CompleteAuthorizeData, MandateRevokeRequestData, - PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, - PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPreProcessingData, + PaymentMethodTokenizationData, PaymentsAuthenticateData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, + PaymentsPostAuthenticateData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData}, types::{ - MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, - PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, - PaymentsIncrementalAuthorizationRouterData, PaymentsPreProcessingRouterData, - PaymentsSyncRouterData, RefundExecuteRouterData, RefundSyncRouterData, - SetupMandateRouterData, + MandateRevokeRouterData, PaymentsAuthenticateRouterData, PaymentsAuthorizeRouterData, + PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, + PaymentsIncrementalAuthorizationRouterData, PaymentsPostAuthenticateRouterData, + PaymentsPreAuthenticateRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData, + RefundExecuteRouterData, RefundSyncRouterData, SetupMandateRouterData, }, }; #[cfg(feature = "payouts")] @@ -58,8 +59,9 @@ use hyperswitch_interfaces::{ errors, events::connector_api_logs::ConnectorEvent, types::{ - IncrementalAuthorizationType, MandateRevokeType, PaymentsAuthorizeType, - PaymentsCaptureType, PaymentsCompleteAuthorizeType, PaymentsPreProcessingType, + IncrementalAuthorizationType, MandateRevokeType, PaymentsAuthenticateType, + PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType, + PaymentsPostAuthenticateType, PaymentsPreAuthenticateType, PaymentsPreProcessingType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType, RefundSyncType, Response, SetupMandateType, }, @@ -393,6 +395,9 @@ where } impl api::Payment for Cybersource {} +impl api::PaymentsPreAuthenticate for Cybersource {} +impl api::PaymentsPostAuthenticate for Cybersource {} +impl api::PaymentsAuthenticate for Cybersource {} impl api::PaymentAuthorize for Cybersource {} impl api::PaymentSync for Cybersource {} impl api::PaymentVoid for Cybersource {} @@ -732,6 +737,292 @@ impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResp } } +impl ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData> + for Cybersource +{ + fn get_headers( + &self, + req: &PaymentsPreAuthenticateRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_url( + &self, + _req: &PaymentsPreAuthenticateRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}risk/v1/authentication-setups", + ConnectorCommon::base_url(self, connectors) + )) + } + fn get_request_body( + &self, + req: &PaymentsPreAuthenticateRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let minor_amount = + req.request + .minor_amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "minor_amount", + })?; + let currency = + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?; + + let amount = convert_amount(self.amount_converter, minor_amount, currency)?; + + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); + let connector_req = + cybersource::CybersourceAuthSetupRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + fn build_request( + &self, + req: &PaymentsPreAuthenticateRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsPreAuthenticateType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(PaymentsPreAuthenticateType::get_headers( + self, req, connectors, + )?) + .set_body(self.get_request_body(req, connectors)?) + .build(); + + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &PaymentsPreAuthenticateRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsPreAuthenticateRouterData, errors::ConnectorError> { + let response: cybersource::CybersourceAuthSetupResponse = res + .response + .parse_struct("Cybersource AuthSetupResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + 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<Authenticate, PaymentsAuthenticateData, PaymentsResponseData> + for Cybersource +{ + fn get_headers( + &self, + req: &PaymentsAuthenticateRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_url( + &self, + _req: &PaymentsAuthenticateRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}risk/v1/authentications", + self.base_url(connectors) + )) + } + fn get_request_body( + &self, + req: &PaymentsAuthenticateRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let minor_amount = + req.request + .minor_amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "minor_amount", + })?; + let currency = + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?; + let amount = convert_amount(self.amount_converter, minor_amount, currency)?; + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); + let connector_req = + cybersource::CybersourceAuthEnrollmentRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + fn build_request( + &self, + req: &PaymentsAuthenticateRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthenticateType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PaymentsAuthenticateType::get_headers( + self, req, connectors, + )?) + .set_body(PaymentsAuthenticateType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsAuthenticateRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsAuthenticateRouterData, errors::ConnectorError> { + let response: cybersource::CybersourceAuthenticateResponse = res + .response + .parse_struct("Cybersource AuthEnrollmentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + 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<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData> + for Cybersource +{ + fn get_headers( + &self, + req: &PaymentsPostAuthenticateRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_url( + &self, + _req: &PaymentsPostAuthenticateRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}risk/v1/authentication-results", + self.base_url(connectors) + )) + } + fn get_request_body( + &self, + req: &PaymentsPostAuthenticateRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let minor_amount = + req.request + .minor_amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "minor_amount", + })?; + let currency = + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?; + let amount = convert_amount(self.amount_converter, minor_amount, currency)?; + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); + let connector_req = + cybersource::CybersourceAuthValidateRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + fn build_request( + &self, + req: &PaymentsPostAuthenticateRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsPostAuthenticateType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(PaymentsPostAuthenticateType::get_headers( + self, req, connectors, + )?) + .set_body(PaymentsPostAuthenticateType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsPostAuthenticateRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsPostAuthenticateRouterData, errors::ConnectorError> { + let response: cybersource::CybersourceAuthenticateResponse = res + .response + .parse_struct("Cybersource AuthEnrollmentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + 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 Cybersource { fn get_headers( &self, @@ -926,6 +1217,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cyb } } +#[cfg(feature = "v1")] impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cybersource { fn get_headers( &self, @@ -1090,6 +1382,129 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData } } +#[cfg(feature = "v2")] +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cybersource { + fn get_headers( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}pts/v2/payments/", + ConnectorCommon::base_url(self, connectors) + )) + } + + fn get_request_body( + &self, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); + let connector_req = + cybersource::CybersourcePaymentsRequest::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> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(self.get_request_body(req, connectors)?) + .build(); + + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: cybersource::CybersourcePaymentsResponse = res + .response + .parse_struct("Cybersource PaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + 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) + } + + fn get_5xx_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: cybersource::CybersourceServerErrorResponse = res + .response + .parse_struct("CybersourceServerErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|event| event.set_response_body(&response)); + router_env::logger::info!(error_response=?response); + + let attempt_status = match response.reason { + Some(reason) => match reason { + transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure), + transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None, + }, + None => None, + }; + Ok(ErrorResponse { + status_code: res.status_code, + reason: response.status.clone(), + code: response + .status + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), + message: response + .message + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), + attempt_status, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + connector_metadata: None, + }) + } +} + #[cfg(feature = "payouts")] impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Cybersource { fn get_url( diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index e39bc64c3f6..0338eb44fd8 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -34,17 +34,20 @@ use hyperswitch_domain_models::{ SetupMandate, }, router_request_types::{ - authentication::MessageExtensionAttribute, CompleteAuthorizeData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSyncData, - ResponseId, SetupMandateRequestData, + authentication::MessageExtensionAttribute, CompleteAuthorizeData, PaymentsAuthenticateData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, + PaymentsPostAuthenticateData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, + PaymentsSyncData, ResponseId, SetupMandateRequestData, }, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, types::{ - PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, - PaymentsCompleteAuthorizeRouterData, PaymentsIncrementalAuthorizationRouterData, - PaymentsPreProcessingRouterData, RefundsRouterData, SetupMandateRouterData, + PaymentsAuthenticateRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, + PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, + PaymentsIncrementalAuthorizationRouterData, PaymentsPostAuthenticateRouterData, + PaymentsPreAuthenticateRouterData, PaymentsPreProcessingRouterData, RefundsRouterData, + SetupMandateRouterData, }, }; use hyperswitch_interfaces::{api, errors}; @@ -725,6 +728,16 @@ pub struct BillTo { email: pii::Email, } +impl From<&CybersourceRouterData<&PaymentsPreAuthenticateRouterData>> + for ClientReferenceInformation +{ + fn from(item: &CybersourceRouterData<&PaymentsPreAuthenticateRouterData>) -> Self { + Self { + code: Some(item.router_data.connector_request_reference_id.clone()), + } + } +} + impl From<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for ClientReferenceInformation { fn from(item: &CybersourceRouterData<&PaymentsAuthorizeRouterData>) -> Self { Self { @@ -2653,6 +2666,77 @@ impl TryFrom<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for Cybersour } } +impl TryFrom<&CybersourceRouterData<&PaymentsPreAuthenticateRouterData>> + for CybersourceAuthSetupRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &CybersourceRouterData<&PaymentsPreAuthenticateRouterData>, + ) -> Result<Self, Self::Error> { + let payment_method_data = item + .router_data + .request + .payment_method_data + .as_ref() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "payment_method_data", + })?; + + match payment_method_data.clone() { + PaymentMethodData::Card(ccard) => { + let card_type = match ccard + .card_network + .clone() + .and_then(get_cybersource_card_type) + { + Some(card_network) => Some(card_network.to_string()), + None => ccard.get_card_issuer().ok().map(String::from), + }; + + let payment_information = + PaymentInformation::Cards(Box::new(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: Some(ccard.card_cvc), + card_type, + type_selection_indicator: Some("1".to_owned()), + }, + })); + let client_reference_information = ClientReferenceInformation::from(item); + Ok(Self { + payment_information, + client_reference_information, + }) + } + PaymentMethodData::Wallet(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::MobilePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Cybersource"), + ) + .into()) + } + } + } +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourcePaymentsCaptureRequest { @@ -3416,20 +3500,45 @@ impl TryFrom<&CybersourceRouterData<&PaymentsPreProcessingRouterData>> } } -impl TryFrom<&CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>> - for CybersourcePaymentsRequest +impl TryFrom<&CybersourceRouterData<&PaymentsAuthenticateRouterData>> + for CybersourceAuthEnrollmentRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>, + item: &CybersourceRouterData<&PaymentsAuthenticateRouterData>, ) -> Result<Self, Self::Error> { + let client_reference_information = ClientReferenceInformation { + code: Some(item.router_data.connector_request_reference_id.clone()), + }; let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( - errors::ConnectorError::MissingRequiredField { + errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "payment_method_data", }, )?; - match payment_method_data { - PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), + let payment_information = match payment_method_data { + PaymentMethodData::Card(ccard) => { + let card_type = match ccard + .card_network + .clone() + .and_then(get_cybersource_card_type) + { + Some(card_network) => Some(card_network.to_string()), + None => ccard.get_card_issuer().ok().map(String::from), + }; + + Ok(PaymentInformation::Cards(Box::new( + CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: Some(ccard.card_cvc), + card_type, + type_selection_indicator: Some("1".to_owned()), + }, + }, + ))) + } PaymentMethodData::Wallet(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) @@ -3450,113 +3559,316 @@ impl TryFrom<&CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>> | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), - ) - .into()) + )) } - } - } -} - -#[derive(Debug, Deserialize, Serialize)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum CybersourceAuthEnrollmentStatus { - PendingAuthentication, - AuthenticationSuccessful, - AuthenticationFailed, -} -#[derive(Debug, Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct CybersourceConsumerAuthValidateResponse { - ucaf_collection_indicator: Option<String>, - cavv: Option<Secret<String>>, - ucaf_authentication_data: Option<Secret<String>>, - xid: Option<String>, - specification_version: Option<SemanticVersion>, - directory_server_transaction_id: Option<Secret<String>>, - indicator: Option<String>, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct CybersourceThreeDSMetadata { - three_ds_data: CybersourceConsumerAuthValidateResponse, -} + }?; -#[derive(Debug, Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct CybersourceConsumerAuthInformationEnrollmentResponse { - access_token: Option<Secret<String>>, - step_up_url: Option<String>, - //Added to segregate the three_ds_data in a separate struct - #[serde(flatten)] - validate_response: CybersourceConsumerAuthValidateResponse, -} + let redirect_response = item.router_data.request.redirect_response.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "redirect_response", + }, + )?; -#[derive(Debug, Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct ClientAuthCheckInfoResponse { - id: String, - client_reference_information: ClientReferenceInformation, - consumer_authentication_information: CybersourceConsumerAuthInformationEnrollmentResponse, - status: CybersourceAuthEnrollmentStatus, - error_information: Option<CybersourceErrorInformation>, -} + let amount_details = Amount { + total_amount: item.amount.clone(), + currency: item.router_data.request.currency.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "currency", + }, + )?, + }; -#[derive(Debug, Deserialize, Serialize)] -#[serde(untagged)] -pub enum CybersourcePreProcessingResponse { - ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>), - ErrorInformation(Box<CybersourceErrorInformationResponse>), -} + let param = redirect_response.params.ok_or( + errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "request.redirect_response.params", + }, + )?; -impl From<CybersourceAuthEnrollmentStatus> for enums::AttemptStatus { - fn from(item: CybersourceAuthEnrollmentStatus) -> Self { - match item { - CybersourceAuthEnrollmentStatus::PendingAuthentication => Self::AuthenticationPending, - CybersourceAuthEnrollmentStatus::AuthenticationSuccessful => { - Self::AuthenticationSuccessful - } - CybersourceAuthEnrollmentStatus::AuthenticationFailed => Self::AuthenticationFailed, - } + let reference_id = param + .clone() + .peek() + .split('=') + .next_back() + .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "request.redirect_response.params.reference_id", + })? + .to_string(); + let email = item.router_data.get_billing_email().or(item + .router_data + .request + .email + .clone() + .ok_or_else(utils::missing_field_err("email")))?; + let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; + let order_information = OrderInformationWithBill { + amount_details, + bill_to: Some(bill_to), + }; + Ok(Self { + payment_information, + client_reference_information, + consumer_authentication_information: CybersourceConsumerAuthInformationRequest { + return_url: item + .router_data + .request + .complete_authorize_url + .clone() + .ok_or_else(utils::missing_field_err("complete_authorize_url"))?, + reference_id, + }, + order_information, + }) } } -impl<F> - TryFrom< - ResponseRouterData< - F, - CybersourcePreProcessingResponse, - PaymentsPreProcessingData, - PaymentsResponseData, - >, - > for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData> +impl TryFrom<&CybersourceRouterData<&PaymentsPostAuthenticateRouterData>> + for CybersourceAuthValidateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: ResponseRouterData< - F, - CybersourcePreProcessingResponse, - PaymentsPreProcessingData, - PaymentsResponseData, - >, + item: &CybersourceRouterData<&PaymentsPostAuthenticateRouterData>, ) -> Result<Self, Self::Error> { - match item.response { - CybersourcePreProcessingResponse::ClientAuthCheckInfo(info_response) => { - let status = enums::AttemptStatus::from(info_response.status); - let risk_info: Option<ClientRiskInformation> = None; - if utils::is_payment_failure(status) { - let response = Err(get_error_response( - &info_response.error_information, - &None, - &risk_info, - Some(status), - item.http_code, - info_response.id.clone(), - )); + let client_reference_information = ClientReferenceInformation { + code: Some(item.router_data.connector_request_reference_id.clone()), + }; + let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( + errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "payment_method_data", + }, + )?; + let payment_information = match payment_method_data { + PaymentMethodData::Card(ccard) => { + let card_type = match ccard + .card_network + .clone() + .and_then(get_cybersource_card_type) + { + Some(card_network) => Some(card_network.to_string()), + None => ccard.get_card_issuer().ok().map(String::from), + }; - Ok(Self { - status, - response, - ..item.data + Ok(PaymentInformation::Cards(Box::new( + CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: Some(ccard.card_cvc), + card_type, + type_selection_indicator: Some("1".to_owned()), + }, + }, + ))) + } + PaymentMethodData::Wallet(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::MobilePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Cybersource"), + )) + } + }?; + + let redirect_response = item.router_data.request.redirect_response.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "redirect_response", + }, + )?; + + let amount_details = Amount { + total_amount: item.amount.clone(), + currency: item.router_data.request.currency.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "currency", + }, + )?, + }; + + let redirect_payload: CybersourceRedirectionAuthResponse = redirect_response + .payload + .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "request.redirect_response.payload", + })? + .peek() + .clone() + .parse_value("CybersourceRedirectionAuthResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let order_information = OrderInformation { amount_details }; + Ok(Self { + payment_information, + client_reference_information, + consumer_authentication_information: + CybersourceConsumerAuthInformationValidateRequest { + authentication_transaction_id: redirect_payload.transaction_id, + }, + order_information, + }) + } +} + +impl TryFrom<&CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>> + for CybersourcePaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "payment_method_data", + }, + )?; + match payment_method_data { + PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), + PaymentMethodData::Wallet(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::MobilePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Cybersource"), + ) + .into()) + } + } + } +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum CybersourceAuthEnrollmentStatus { + PendingAuthentication, + AuthenticationSuccessful, + AuthenticationFailed, +} +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceConsumerAuthValidateResponse { + ucaf_collection_indicator: Option<String>, + cavv: Option<Secret<String>>, + ucaf_authentication_data: Option<Secret<String>>, + xid: Option<String>, + specification_version: Option<SemanticVersion>, + directory_server_transaction_id: Option<Secret<String>>, + indicator: Option<String>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct CybersourceThreeDSMetadata { + three_ds_data: CybersourceConsumerAuthValidateResponse, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceConsumerAuthInformationEnrollmentResponse { + access_token: Option<Secret<String>>, + step_up_url: Option<String>, + //Added to segregate the three_ds_data in a separate struct + #[serde(flatten)] + validate_response: CybersourceConsumerAuthValidateResponse, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientAuthCheckInfoResponse { + id: String, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: CybersourceConsumerAuthInformationEnrollmentResponse, + status: CybersourceAuthEnrollmentStatus, + error_information: Option<CybersourceErrorInformation>, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum CybersourcePreProcessingResponse { + ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>), + ErrorInformation(Box<CybersourceErrorInformationResponse>), +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum CybersourceAuthenticateResponse { + ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>), + ErrorInformation(Box<CybersourceErrorInformationResponse>), +} + +impl From<CybersourceAuthEnrollmentStatus> for enums::AttemptStatus { + fn from(item: CybersourceAuthEnrollmentStatus) -> Self { + match item { + CybersourceAuthEnrollmentStatus::PendingAuthentication => Self::AuthenticationPending, + CybersourceAuthEnrollmentStatus::AuthenticationSuccessful => { + Self::AuthenticationSuccessful + } + CybersourceAuthEnrollmentStatus::AuthenticationFailed => Self::AuthenticationFailed, + } + } +} + +impl<F> + TryFrom< + ResponseRouterData< + F, + CybersourcePreProcessingResponse, + PaymentsPreProcessingData, + PaymentsResponseData, + >, + > for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + F, + CybersourcePreProcessingResponse, + PaymentsPreProcessingData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + CybersourcePreProcessingResponse::ClientAuthCheckInfo(info_response) => { + let status = enums::AttemptStatus::from(info_response.status); + let risk_info: Option<ClientRiskInformation> = None; + if utils::is_payment_failure(status) { + let response = Err(get_error_response( + &info_response.error_information, + &None, + &risk_info, + Some(status), + item.http_code, + info_response.id.clone(), + )); + + Ok(Self { + status, + response, + ..item.data }) } else { let connector_response_reference_id = Some( @@ -3924,6 +4236,362 @@ pub struct ApplicationInformation { status: Option<CybersourcePaymentStatus>, } +impl<F> + TryFrom< + ResponseRouterData< + F, + CybersourceAuthSetupResponse, + PaymentsPreAuthenticateData, + PaymentsResponseData, + >, + > for RouterData<F, PaymentsPreAuthenticateData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + F, + CybersourceAuthSetupResponse, + PaymentsPreAuthenticateData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + CybersourceAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self { + status: enums::AttemptStatus::AuthenticationPending, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::NoResponseId, + redirection_data: Box::new(Some(RedirectForm::CybersourceAuthSetup { + access_token: info_response + .consumer_authentication_information + .access_token, + ddc_url: info_response + .consumer_authentication_information + .device_data_collection_url, + reference_id: info_response + .consumer_authentication_information + .reference_id, + })), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some( + info_response + .client_reference_information + .code + .unwrap_or(info_response.id.clone()), + ), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }), + CybersourceAuthSetupResponse::ErrorInformation(error_response) => { + let detailed_error_info = + error_response + .error_information + .details + .to_owned() + .map(|details| { + details + .iter() + .map(|details| format!("{} : {}", details.field, details.reason)) + .collect::<Vec<_>>() + .join(", ") + }); + + let reason = get_error_reason( + error_response.error_information.message, + detailed_error_info, + None, + ); + let error_message = error_response.error_information.reason; + Ok(Self { + response: Err(ErrorResponse { + code: error_message + .clone() + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or( + hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string(), + ), + reason, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + connector_metadata: None, + }), + status: enums::AttemptStatus::AuthenticationFailed, + ..item.data + }) + } + } + } +} + +impl<F> + TryFrom< + ResponseRouterData< + F, + CybersourceAuthenticateResponse, + PaymentsAuthenticateData, + PaymentsResponseData, + >, + > for RouterData<F, PaymentsAuthenticateData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + F, + CybersourceAuthenticateResponse, + PaymentsAuthenticateData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + CybersourceAuthenticateResponse::ClientAuthCheckInfo(info_response) => { + let status = enums::AttemptStatus::from(info_response.status); + let risk_info: Option<ClientRiskInformation> = None; + if utils::is_payment_failure(status) { + let response = Err(get_error_response( + &info_response.error_information, + &None, + &risk_info, + Some(status), + item.http_code, + info_response.id.clone(), + )); + + Ok(Self { + status, + response, + ..item.data + }) + } else { + let connector_response_reference_id = Some( + info_response + .client_reference_information + .code + .unwrap_or(info_response.id.clone()), + ); + + let redirection_data = match ( + info_response + .consumer_authentication_information + .access_token, + info_response + .consumer_authentication_information + .step_up_url, + ) { + (Some(token), Some(step_up_url)) => { + Some(RedirectForm::CybersourceConsumerAuth { + access_token: token.expose(), + step_up_url, + }) + } + _ => None, + }; + let three_ds_data = serde_json::to_value( + info_response + .consumer_authentication_information + .validate_response, + ) + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::NoResponseId, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), + connector_metadata: Some(serde_json::json!({ + "three_ds_data": three_ds_data + })), + network_txn_id: None, + connector_response_reference_id, + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }) + } + } + CybersourceAuthenticateResponse::ErrorInformation(error_response) => { + let detailed_error_info = + error_response + .error_information + .details + .to_owned() + .map(|details| { + details + .iter() + .map(|details| format!("{} : {}", details.field, details.reason)) + .collect::<Vec<_>>() + .join(", ") + }); + + let reason = get_error_reason( + error_response.error_information.message, + detailed_error_info, + None, + ); + let error_message = error_response.error_information.reason.to_owned(); + let response = Err(ErrorResponse { + code: error_message + .clone() + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), + message: error_message + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), + reason, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + connector_metadata: None, + }); + Ok(Self { + response, + status: enums::AttemptStatus::AuthenticationFailed, + ..item.data + }) + } + } + } +} + +impl<F> + TryFrom< + ResponseRouterData< + F, + CybersourceAuthenticateResponse, + PaymentsPostAuthenticateData, + PaymentsResponseData, + >, + > for RouterData<F, PaymentsPostAuthenticateData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + F, + CybersourceAuthenticateResponse, + PaymentsPostAuthenticateData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + CybersourceAuthenticateResponse::ClientAuthCheckInfo(info_response) => { + let status = enums::AttemptStatus::from(info_response.status); + let risk_info: Option<ClientRiskInformation> = None; + if utils::is_payment_failure(status) { + let response = Err(get_error_response( + &info_response.error_information, + &None, + &risk_info, + Some(status), + item.http_code, + info_response.id.clone(), + )); + + Ok(Self { + status, + response, + ..item.data + }) + } else { + let connector_response_reference_id = Some( + info_response + .client_reference_information + .code + .unwrap_or(info_response.id.clone()), + ); + + let redirection_data = match ( + info_response + .consumer_authentication_information + .access_token, + info_response + .consumer_authentication_information + .step_up_url, + ) { + (Some(token), Some(step_up_url)) => { + Some(RedirectForm::CybersourceConsumerAuth { + access_token: token.expose(), + step_up_url, + }) + } + _ => None, + }; + let three_ds_data = serde_json::to_value( + info_response + .consumer_authentication_information + .validate_response, + ) + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::NoResponseId, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), + connector_metadata: Some(serde_json::json!({ + "three_ds_data": three_ds_data + })), + network_txn_id: None, + connector_response_reference_id, + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }) + } + } + CybersourceAuthenticateResponse::ErrorInformation(error_response) => { + let detailed_error_info = + error_response + .error_information + .details + .to_owned() + .map(|details| { + details + .iter() + .map(|details| format!("{} : {}", details.field, details.reason)) + .collect::<Vec<_>>() + .join(", ") + }); + + let reason = get_error_reason( + error_response.error_information.message, + detailed_error_info, + None, + ); + let error_message = error_response.error_information.reason.to_owned(); + let response = Err(ErrorResponse { + code: error_message + .clone() + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), + message: error_message + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), + reason, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + connector_metadata: None, + }); + Ok(Self { + response, + status: enums::AttemptStatus::AuthenticationFailed, + ..item.data + }) + } + } + } +} + impl<F> TryFrom< ResponseRouterData< diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 8b87e0c098a..c9b0f8352d9 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -55,11 +55,13 @@ use hyperswitch_domain_models::{ CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, DisputeSyncData, ExternalVaultProxyPaymentsData, FetchDisputesRequestData, MandateRevokeRequestData, PaymentsApproveData, - PaymentsCancelPostCaptureData, PaymentsIncrementalAuthorizationData, - PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, - PaymentsRejectData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, - RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SubmitEvidenceRequestData, - UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData, + PaymentsAuthenticateData, PaymentsCancelPostCaptureData, + PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, + PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, + PaymentsPreProcessingData, PaymentsRejectData, PaymentsTaxCalculationData, + PaymentsUpdateMetadataData, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, + SubmitEvidenceRequestData, UploadFileRequestData, VaultRequestData, + VerifyWebhookSourceRequestData, }, router_response_types::{ AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse, @@ -120,7 +122,8 @@ use hyperswitch_interfaces::{ ConnectorCustomer, ExternalVaultProxyPaymentsCreateV1, PaymentApprove, PaymentAuthorizeSessionToken, PaymentIncrementalAuthorization, PaymentPostCaptureVoid, PaymentPostSessionTokens, PaymentReject, PaymentSessionUpdate, PaymentUpdateMetadata, - PaymentsCompleteAuthorize, PaymentsCreateOrder, PaymentsPostProcessing, + PaymentsAuthenticate, PaymentsCompleteAuthorize, PaymentsCreateOrder, + PaymentsPostAuthenticate, PaymentsPostProcessing, PaymentsPreAuthenticate, PaymentsPreProcessing, TaxCalculation, }, revenue_recovery::RevenueRecovery, @@ -1648,6 +1651,432 @@ default_imp_for_connector_redirect_response!( connectors::CtpMastercard ); +macro_rules! default_imp_for_pre_authenticate_steps{ + ($($path:ident::$connector:ident),*)=> { + $( + impl PaymentsPreAuthenticate for $path::$connector {} + impl + ConnectorIntegration< + PreAuthenticate, + PaymentsPreAuthenticateData, + PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_pre_authenticate_steps!( + connectors::Aci, + connectors::Adyen, + connectors::Adyenplatform, + connectors::Affirm, + connectors::Airwallex, + connectors::Amazonpay, + connectors::Archipel, + connectors::Authipay, + connectors::Authorizedotnet, + connectors::Bambora, + connectors::Bamboraapac, + connectors::Bankofamerica, + connectors::Barclaycard, + connectors::Billwerk, + connectors::Bitpay, + connectors::Blackhawknetwork, + connectors::Bluecode, + connectors::Bluesnap, + connectors::Boku, + connectors::Braintree, + connectors::Breadpay, + connectors::Cashtocode, + connectors::Celero, + connectors::Chargebee, + connectors::Checkbook, + connectors::Checkout, + connectors::Coinbase, + connectors::Coingate, + connectors::Cryptopay, + connectors::CtpMastercard, + connectors::Custombilling, + connectors::Datatrans, + connectors::Deutschebank, + connectors::Digitalvirgo, + connectors::Dlocal, + connectors::Dwolla, + connectors::Ebanx, + connectors::Elavon, + connectors::Facilitapay, + connectors::Fiserv, + connectors::Fiservemea, + connectors::Fiuu, + connectors::Flexiti, + connectors::Forte, + connectors::Getnet, + connectors::Globalpay, + connectors::Globepay, + connectors::Gocardless, + connectors::Gpayments, + connectors::Helcim, + connectors::Hipay, + connectors::HyperswitchVault, + connectors::Hyperwallet, + connectors::Iatapay, + connectors::Inespay, + connectors::Itaubank, + connectors::Jpmorgan, + connectors::Juspaythreedsserver, + connectors::Katapult, + connectors::Klarna, + connectors::Mifinity, + connectors::Mollie, + connectors::Moneris, + connectors::Mpgs, + connectors::Multisafepay, + connectors::Netcetera, + connectors::Nexinets, + connectors::Nexixpay, + connectors::Nmi, + connectors::Nomupay, + connectors::Noon, + connectors::Nordea, + connectors::Novalnet, + connectors::Nuvei, + connectors::Opayo, + connectors::Opennode, + connectors::Paybox, + connectors::Payeezy, + connectors::Payload, + connectors::Payme, + connectors::Payone, + connectors::Paypal, + connectors::Paystack, + connectors::Paytm, + connectors::Payu, + connectors::Phonepe, + connectors::Placetopay, + connectors::Plaid, + connectors::Powertranz, + connectors::Prophetpay, + connectors::Rapyd, + connectors::Razorpay, + connectors::Recurly, + connectors::Redsys, + connectors::Riskified, + connectors::Santander, + connectors::Shift4, + connectors::Sift, + connectors::Signifyd, + connectors::Silverflow, + connectors::Square, + connectors::Stax, + connectors::Stripe, + connectors::Stripebilling, + connectors::Taxjar, + connectors::Threedsecureio, + connectors::Thunes, + connectors::Tokenio, + connectors::Trustpay, + connectors::Trustpayments, + connectors::Tsys, + connectors::UnifiedAuthenticationService, + connectors::Vgs, + connectors::Volt, + connectors::Wellsfargo, + connectors::Wellsfargopayout, + connectors::Wise, + connectors::Worldline, + connectors::Worldpay, + connectors::Worldpayvantiv, + connectors::Worldpayxml, + connectors::Xendit, + connectors::Zen, + connectors::Zsl +); + +macro_rules! default_imp_for_authenticate_steps{ + ($($path:ident::$connector:ident),*)=> { + $( + impl PaymentsAuthenticate for $path::$connector {} + impl + ConnectorIntegration< + Authenticate, + PaymentsAuthenticateData, + PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_authenticate_steps!( + connectors::Aci, + connectors::Adyen, + connectors::Adyenplatform, + connectors::Affirm, + connectors::Airwallex, + connectors::Amazonpay, + connectors::Archipel, + connectors::Authipay, + connectors::Authorizedotnet, + connectors::Bambora, + connectors::Bamboraapac, + connectors::Bankofamerica, + connectors::Barclaycard, + connectors::Billwerk, + connectors::Bitpay, + connectors::Blackhawknetwork, + connectors::Bluecode, + connectors::Bluesnap, + connectors::Boku, + connectors::Braintree, + connectors::Breadpay, + connectors::Cashtocode, + connectors::Celero, + connectors::Chargebee, + connectors::Checkbook, + connectors::Checkout, + connectors::Coinbase, + connectors::Coingate, + connectors::Cryptopay, + connectors::CtpMastercard, + connectors::Custombilling, + connectors::Datatrans, + connectors::Deutschebank, + connectors::Digitalvirgo, + connectors::Dlocal, + connectors::Dwolla, + connectors::Ebanx, + connectors::Elavon, + connectors::Facilitapay, + connectors::Fiserv, + connectors::Fiservemea, + connectors::Fiuu, + connectors::Flexiti, + connectors::Forte, + connectors::Getnet, + connectors::Globalpay, + connectors::Globepay, + connectors::Gocardless, + connectors::Gpayments, + connectors::Helcim, + connectors::Hipay, + connectors::HyperswitchVault, + connectors::Hyperwallet, + connectors::Iatapay, + connectors::Inespay, + connectors::Itaubank, + connectors::Jpmorgan, + connectors::Juspaythreedsserver, + connectors::Katapult, + connectors::Klarna, + connectors::Mifinity, + connectors::Mollie, + connectors::Moneris, + connectors::Mpgs, + connectors::Multisafepay, + connectors::Netcetera, + connectors::Nexinets, + connectors::Nexixpay, + connectors::Nmi, + connectors::Nomupay, + connectors::Noon, + connectors::Nordea, + connectors::Novalnet, + connectors::Nuvei, + connectors::Opayo, + connectors::Opennode, + connectors::Paybox, + connectors::Payeezy, + connectors::Payload, + connectors::Payme, + connectors::Payone, + connectors::Paypal, + connectors::Paystack, + connectors::Paytm, + connectors::Payu, + connectors::Phonepe, + connectors::Placetopay, + connectors::Plaid, + connectors::Powertranz, + connectors::Prophetpay, + connectors::Rapyd, + connectors::Razorpay, + connectors::Recurly, + connectors::Redsys, + connectors::Riskified, + connectors::Santander, + connectors::Shift4, + connectors::Sift, + connectors::Signifyd, + connectors::Silverflow, + connectors::Square, + connectors::Stax, + connectors::Stripe, + connectors::Stripebilling, + connectors::Taxjar, + connectors::Threedsecureio, + connectors::Thunes, + connectors::Tokenio, + connectors::Trustpay, + connectors::Trustpayments, + connectors::Tsys, + connectors::UnifiedAuthenticationService, + connectors::Vgs, + connectors::Volt, + connectors::Wellsfargo, + connectors::Wellsfargopayout, + connectors::Wise, + connectors::Worldline, + connectors::Worldpay, + connectors::Worldpayvantiv, + connectors::Worldpayxml, + connectors::Xendit, + connectors::Zen, + connectors::Zsl +); + +macro_rules! default_imp_for_post_authenticate_steps{ + ($($path:ident::$connector:ident),*)=> { + $( + impl PaymentsPostAuthenticate for $path::$connector {} + impl + ConnectorIntegration< + PostAuthenticate, + PaymentsPostAuthenticateData, + PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_post_authenticate_steps!( + connectors::Aci, + connectors::Adyen, + connectors::Adyenplatform, + connectors::Affirm, + connectors::Airwallex, + connectors::Amazonpay, + connectors::Archipel, + connectors::Authipay, + connectors::Authorizedotnet, + connectors::Bambora, + connectors::Bamboraapac, + connectors::Bankofamerica, + connectors::Barclaycard, + connectors::Billwerk, + connectors::Bitpay, + connectors::Blackhawknetwork, + connectors::Bluecode, + connectors::Bluesnap, + connectors::Boku, + connectors::Braintree, + connectors::Breadpay, + connectors::Cashtocode, + connectors::Celero, + connectors::Chargebee, + connectors::Checkbook, + connectors::Checkout, + connectors::Coinbase, + connectors::Coingate, + connectors::Cryptopay, + connectors::CtpMastercard, + connectors::Custombilling, + connectors::Datatrans, + connectors::Deutschebank, + connectors::Digitalvirgo, + connectors::Dlocal, + connectors::Dwolla, + connectors::Ebanx, + connectors::Elavon, + connectors::Facilitapay, + connectors::Fiserv, + connectors::Fiservemea, + connectors::Fiuu, + connectors::Flexiti, + connectors::Forte, + connectors::Getnet, + connectors::Globalpay, + connectors::Globepay, + connectors::Gocardless, + connectors::Gpayments, + connectors::Helcim, + connectors::Hipay, + connectors::HyperswitchVault, + connectors::Hyperwallet, + connectors::Iatapay, + connectors::Inespay, + connectors::Itaubank, + connectors::Jpmorgan, + connectors::Juspaythreedsserver, + connectors::Katapult, + connectors::Klarna, + connectors::Mifinity, + connectors::Mollie, + connectors::Moneris, + connectors::Mpgs, + connectors::Multisafepay, + connectors::Netcetera, + connectors::Nexinets, + connectors::Nexixpay, + connectors::Nmi, + connectors::Nomupay, + connectors::Noon, + connectors::Nordea, + connectors::Novalnet, + connectors::Nuvei, + connectors::Opayo, + connectors::Opennode, + connectors::Paybox, + connectors::Payeezy, + connectors::Payload, + connectors::Payme, + connectors::Payone, + connectors::Paypal, + connectors::Paystack, + connectors::Paytm, + connectors::Payu, + connectors::Phonepe, + connectors::Placetopay, + connectors::Plaid, + connectors::Powertranz, + connectors::Prophetpay, + connectors::Rapyd, + connectors::Razorpay, + connectors::Recurly, + connectors::Redsys, + connectors::Riskified, + connectors::Santander, + connectors::Shift4, + connectors::Sift, + connectors::Signifyd, + connectors::Silverflow, + connectors::Square, + connectors::Stax, + connectors::Stripe, + connectors::Stripebilling, + connectors::Taxjar, + connectors::Threedsecureio, + connectors::Thunes, + connectors::Tokenio, + connectors::Trustpay, + connectors::Trustpayments, + connectors::Tsys, + connectors::UnifiedAuthenticationService, + connectors::Vgs, + connectors::Volt, + connectors::Wellsfargo, + connectors::Wellsfargopayout, + connectors::Wise, + connectors::Worldline, + connectors::Worldpay, + connectors::Worldpayvantiv, + connectors::Worldpayxml, + connectors::Xendit, + connectors::Zen, + connectors::Zsl +); + macro_rules! default_imp_for_pre_processing_steps{ ($($path:ident::$connector:ident),*)=> { $( diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index a9a842dcfd5..475f9499282 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -585,6 +585,123 @@ impl TryFrom<PaymentsAuthorizeData> for PaymentsPreProcessingData { } } +#[derive(Debug, Clone)] +pub struct PaymentsPreAuthenticateData { + pub payment_method_data: Option<PaymentMethodData>, + pub amount: Option<i64>, + pub email: Option<pii::Email>, + pub currency: Option<storage_enums::Currency>, + pub payment_method_type: Option<storage_enums::PaymentMethodType>, + pub router_return_url: Option<String>, + pub complete_authorize_url: Option<String>, + pub browser_info: Option<BrowserInformation>, + pub connector_transaction_id: Option<String>, + pub enrolled_for_3ds: bool, + pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, + + // New amount for amount frame work + pub minor_amount: Option<MinorUnit>, +} + +impl TryFrom<PaymentsAuthorizeData> for PaymentsPreAuthenticateData { + type Error = error_stack::Report<ApiErrorResponse>; + + fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> { + Ok(Self { + payment_method_data: Some(data.payment_method_data), + amount: Some(data.amount), + minor_amount: Some(data.minor_amount), + email: data.email, + currency: Some(data.currency), + payment_method_type: data.payment_method_type, + router_return_url: data.router_return_url, + complete_authorize_url: data.complete_authorize_url, + browser_info: data.browser_info, + connector_transaction_id: None, + redirect_response: None, + enrolled_for_3ds: data.enrolled_for_3ds, + }) + } +} + +#[derive(Debug, Clone)] +pub struct PaymentsAuthenticateData { + pub payment_method_data: Option<PaymentMethodData>, + pub amount: Option<i64>, + pub email: Option<pii::Email>, + pub currency: Option<storage_enums::Currency>, + pub payment_method_type: Option<storage_enums::PaymentMethodType>, + pub router_return_url: Option<String>, + pub complete_authorize_url: Option<String>, + pub browser_info: Option<BrowserInformation>, + pub connector_transaction_id: Option<String>, + pub enrolled_for_3ds: bool, + pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, + + // New amount for amount frame work + pub minor_amount: Option<MinorUnit>, +} + +impl TryFrom<PaymentsAuthorizeData> for PaymentsAuthenticateData { + type Error = error_stack::Report<ApiErrorResponse>; + + fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> { + Ok(Self { + payment_method_data: Some(data.payment_method_data), + amount: Some(data.amount), + minor_amount: Some(data.minor_amount), + email: data.email, + currency: Some(data.currency), + payment_method_type: data.payment_method_type, + router_return_url: data.router_return_url, + complete_authorize_url: data.complete_authorize_url, + browser_info: data.browser_info, + connector_transaction_id: None, + redirect_response: None, + enrolled_for_3ds: data.enrolled_for_3ds, + }) + } +} + +#[derive(Debug, Clone)] +pub struct PaymentsPostAuthenticateData { + pub payment_method_data: Option<PaymentMethodData>, + pub amount: Option<i64>, + pub email: Option<pii::Email>, + pub currency: Option<storage_enums::Currency>, + pub payment_method_type: Option<storage_enums::PaymentMethodType>, + pub router_return_url: Option<String>, + pub complete_authorize_url: Option<String>, + pub browser_info: Option<BrowserInformation>, + pub connector_transaction_id: Option<String>, + pub enrolled_for_3ds: bool, + pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, + + // New amount for amount frame work + pub minor_amount: Option<MinorUnit>, +} + +impl TryFrom<PaymentsAuthorizeData> for PaymentsPostAuthenticateData { + type Error = error_stack::Report<ApiErrorResponse>; + + fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> { + Ok(Self { + payment_method_data: Some(data.payment_method_data), + amount: Some(data.amount), + minor_amount: Some(data.minor_amount), + email: data.email, + currency: Some(data.currency), + payment_method_type: data.payment_method_type, + router_return_url: data.router_return_url, + complete_authorize_url: data.complete_authorize_url, + browser_info: data.browser_info, + connector_transaction_id: None, + redirect_response: None, + enrolled_for_3ds: data.enrolled_for_3ds, + }) + } +} + impl TryFrom<CompleteAuthorizeData> for PaymentsPreProcessingData { type Error = error_stack::Report<ApiErrorResponse>; diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs index bcca0ba12a9..a134befa55f 100644 --- a/crates/hyperswitch_domain_models/src/types.rs +++ b/crates/hyperswitch_domain_models/src/types.rs @@ -25,8 +25,9 @@ use crate::{ AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, ExternalVaultProxyPaymentsData, MandateRevokeRequestData, PaymentMethodTokenizationData, - PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, - PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostSessionTokensData, + PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, + PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, + PaymentsPostAuthenticateData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, VaultRequestData, @@ -52,6 +53,12 @@ pub type PaymentsAuthorizeSessionTokenRouterData = RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>; pub type PaymentsPreProcessingRouterData = RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; +pub type PaymentsPreAuthenticateRouterData = + RouterData<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>; +pub type PaymentsAuthenticateRouterData = + RouterData<Authenticate, PaymentsAuthenticateData, PaymentsResponseData>; +pub type PaymentsPostAuthenticateRouterData = + RouterData<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>; pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>; diff --git a/crates/hyperswitch_interfaces/src/api/payments.rs b/crates/hyperswitch_interfaces/src/api/payments.rs index b901f28a197..f4aa421240b 100644 --- a/crates/hyperswitch_interfaces/src/api/payments.rs +++ b/crates/hyperswitch_interfaces/src/api/payments.rs @@ -8,15 +8,16 @@ use hyperswitch_domain_models::{ PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, - CreateOrder, ExternalVaultProxy, + Authenticate, CreateOrder, ExternalVaultProxy, PostAuthenticate, PreAuthenticate, }, router_request_types::{ AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, ExternalVaultProxyPaymentsData, PaymentMethodTokenizationData, - PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, + PaymentsApproveData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, - PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, - PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, + PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, + PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsRejectData, + PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, }, router_response_types::{PaymentsResponseData, TaxCalculationResponseData}, @@ -171,6 +172,24 @@ pub trait PaymentsPreProcessing: { } +/// trait PaymentsPreAuthenticate +pub trait PaymentsPreAuthenticate: + api::ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData> +{ +} + +/// trait PaymentsAuthenticate +pub trait PaymentsAuthenticate: + api::ConnectorIntegration<Authenticate, PaymentsAuthenticateData, PaymentsResponseData> +{ +} + +/// trait PaymentsPostAuthenticate +pub trait PaymentsPostAuthenticate: + api::ConnectorIntegration<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData> +{ +} + /// trait PaymentsPostProcessing pub trait PaymentsPostProcessing: api::ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData> diff --git a/crates/hyperswitch_interfaces/src/api/payments_v2.rs b/crates/hyperswitch_interfaces/src/api/payments_v2.rs index ea4b6428c3b..88c3e39ca40 100644 --- a/crates/hyperswitch_interfaces/src/api/payments_v2.rs +++ b/crates/hyperswitch_interfaces/src/api/payments_v2.rs @@ -2,19 +2,23 @@ use hyperswitch_domain_models::{ router_data_v2::PaymentFlowData, - router_flow_types::payments::{ - Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, - CreateConnectorCustomer, CreateOrder, ExternalVaultProxy, IncrementalAuthorization, PSync, - PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, - Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, + router_flow_types::{ + payments::{ + Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, + CreateConnectorCustomer, CreateOrder, ExternalVaultProxy, IncrementalAuthorization, + PSync, PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, + PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, + }, + Authenticate, PostAuthenticate, PreAuthenticate, }, router_request_types::{ AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, ExternalVaultProxyPaymentsData, PaymentMethodTokenizationData, - PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, + PaymentsApproveData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, - PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, - PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, + PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, + PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsRejectData, + PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, }, router_response_types::{PaymentsResponseData, TaxCalculationResponseData}, @@ -199,6 +203,39 @@ pub trait PaymentsPreProcessingV2: { } +/// trait PaymentsPreAuthenticateV2 +pub trait PaymentsPreAuthenticateV2: + ConnectorIntegrationV2< + PreAuthenticate, + PaymentFlowData, + PaymentsPreAuthenticateData, + PaymentsResponseData, +> +{ +} + +/// trait PaymentsAuthenticateV2 +pub trait PaymentsAuthenticateV2: + ConnectorIntegrationV2< + Authenticate, + PaymentFlowData, + PaymentsAuthenticateData, + PaymentsResponseData, +> +{ +} + +/// trait PaymentsPostAuthenticateV2 +pub trait PaymentsPostAuthenticateV2: + ConnectorIntegrationV2< + PostAuthenticate, + PaymentFlowData, + PaymentsPostAuthenticateData, + PaymentsResponseData, +> +{ +} + /// trait PaymentsPostProcessingV2 pub trait PaymentsPostProcessingV2: ConnectorIntegrationV2< diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs index eed89fe00ba..01c1a1c82ba 100644 --- a/crates/hyperswitch_interfaces/src/types.rs +++ b/crates/hyperswitch_interfaces/src/types.rs @@ -40,9 +40,10 @@ use hyperswitch_domain_models::{ AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, DisputeSyncData, FetchDisputesRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, - PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, - PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, - PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsSessionData, + PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, + PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, + PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, + PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, SubmitEvidenceRequestData, UploadFileRequestData, VaultRequestData, @@ -111,6 +112,19 @@ pub type CreateOrderType = /// Type alias for `ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>` pub type PaymentsPreProcessingType = dyn ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; + +/// Type alias for `ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>` +pub type PaymentsPreAuthenticateType = + dyn ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>; + +/// Type alias for `ConnectorIntegration<Authenticate, PaymentsAuthenticateData, PaymentsResponseData>` +pub type PaymentsAuthenticateType = + dyn ConnectorIntegration<Authenticate, PaymentsAuthenticateData, PaymentsResponseData>; + +/// Type alias for `ConnectorIntegration<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>` +pub type PaymentsPostAuthenticateType = + dyn ConnectorIntegration<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>; + /// Type alias for `ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>` pub type PaymentsPostProcessingType = dyn ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>;
2025-08-31T00:39:56Z
## 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 `PreAuthenticate`, `Authenticate` and `PostAuthenticate` connector integration and implement them for cybersource ### 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 #9116 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This PR only adds the code changes without actually wiring them to APIs, so it can't be tested as is. A separate PR will add new endpoints that use these flows, they will be tested there. ## 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.116.0
8ce36a2fd513034755a1bf1aacbd3210083e07c9
8ce36a2fd513034755a1bf1aacbd3210083e07c9
juspay/hyperswitch
juspay__hyperswitch-9129
Bug: [FEATURE] Checkout: Add Google Pay Predecrypt Flow ### Feature Description Add Google Pay Predecrypt Flow in Checkout ### Possible Implementation Add Google Pay Predecrypt Flow in Checkout ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index b69f959fbe3..cc3468029e4 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -475,7 +475,7 @@ force_cookies = true # Whether to use only cookies for JWT extra #tokenization configuration which describe token lifetime and payment method for specific connector [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" } +checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization",google_pay_pre_decrypt_flow = "network_tokenization" } mollie = { long_lived_token = false, payment_method = "card" } stax = { long_lived_token = true, payment_method = "card,bank_debit" } square = { long_lived_token = false, payment_method = "card" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index fdcb7891f30..2d88a1b2739 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -853,7 +853,7 @@ redsys = { payment_method = "card" } #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] braintree = { long_lived_token = false, payment_method = "card" } -checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization" } +checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization", google_pay_pre_decrypt_flow = "network_tokenization" } gocardless = { long_lived_token = true, payment_method = "bank_debit" } hipay = { long_lived_token = false, payment_method = "card" } mollie = { long_lived_token = false, payment_method = "card" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 552a6ebb0ed..d3cbd02cc20 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -862,7 +862,7 @@ redsys = { payment_method = "card" } #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] braintree = { long_lived_token = false, payment_method = "card" } -checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization" } +checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization", google_pay_pre_decrypt_flow = "network_tokenization" } gocardless = { long_lived_token = true, payment_method = "bank_debit" } hipay = { long_lived_token = false, payment_method = "card" } mollie = { long_lived_token = false, payment_method = "card" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 520883d5558..7a006dd704b 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -868,7 +868,7 @@ redsys = { payment_method = "card" } #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] braintree = { long_lived_token = false, payment_method = "card" } -checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization" } +checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization", google_pay_pre_decrypt_flow = "network_tokenization" } gocardless = { long_lived_token = true, payment_method = "bank_debit" } hipay = { long_lived_token = false, payment_method = "card" } mollie = { long_lived_token = false, payment_method = "card" } diff --git a/config/development.toml b/config/development.toml index 3bab0fc27bb..3d8aff0fc8c 100644 --- a/config/development.toml +++ b/config/development.toml @@ -996,7 +996,7 @@ apple_pay = {country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD [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" } +checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization", google_pay_pre_decrypt_flow = "network_tokenization" } stax = { long_lived_token = true, payment_method = "card,bank_debit" } mollie = { long_lived_token = false, payment_method = "card" } square = { long_lived_token = false, payment_method = "card" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index fa082b35522..75d67f4eb91 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -396,7 +396,7 @@ workers = 1 #tokenization configuration which describe token lifetime and payment method for specific connector [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" } +checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization", google_pay_pre_decrypt_flow = "network_tokenization" } mollie = { long_lived_token = false, payment_method = "card" } stax = { long_lived_token = true, payment_method = "card,bank_debit" } square = { long_lived_token = false, payment_method = "card" } diff --git a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs index 42ff1d537d9..6754778539c 100644 --- a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs @@ -231,6 +231,19 @@ pub enum PaymentSource { Wallets(WalletSource), ApplePayPredecrypt(Box<ApplePayPredecrypt>), MandatePayment(MandateSource), + GooglePayPredecrypt(Box<GooglePayPredecrypt>), +} + +#[derive(Debug, Serialize)] +pub struct GooglePayPredecrypt { + #[serde(rename = "type")] + _type: String, + token: cards::CardNumber, + token_type: String, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + eci: String, + cryptogram: Option<Secret<String>>, } #[derive(Debug, Serialize)] @@ -453,25 +466,47 @@ impl TryFrom<&CheckoutRouterData<&PaymentsAuthorizeRouterData>> for PaymentsRequ } PaymentMethodData::Wallet(wallet_data) => match wallet_data { WalletData::GooglePay(_) => { - let p_source = PaymentSource::Wallets(WalletSource { - source_type: CheckoutSourceTypes::Token, - token: match item.router_data.get_payment_method_token()? { - PaymentMethodToken::Token(token) => token, - PaymentMethodToken::ApplePayDecrypt(_) => { - Err(unimplemented_payment_method!( - "Apple Pay", - "Simplified", - "Checkout" - ))? - } - PaymentMethodToken::PazeDecrypt(_) => { - Err(unimplemented_payment_method!("Paze", "Checkout"))? - } - PaymentMethodToken::GooglePayDecrypt(_) => { - Err(unimplemented_payment_method!("Google Pay", "Checkout"))? - } - }, - }); + let p_source = match item.router_data.get_payment_method_token()? { + PaymentMethodToken::Token(token) => PaymentSource::Wallets(WalletSource { + source_type: CheckoutSourceTypes::Token, + token, + }), + PaymentMethodToken::ApplePayDecrypt(_) => Err( + unimplemented_payment_method!("Apple Pay", "Simplified", "Checkout"), + )?, + PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Checkout"))? + } + PaymentMethodToken::GooglePayDecrypt(google_pay_decrypted_data) => { + let token = google_pay_decrypted_data + .application_primary_account_number + .clone(); + + let expiry_month = google_pay_decrypted_data + .get_expiry_month() + .change_context(errors::ConnectorError::InvalidDataFormat { + field_name: "payment_method_data.card.card_exp_month", + })?; + + let expiry_year = google_pay_decrypted_data + .get_four_digit_expiry_year() + .change_context(errors::ConnectorError::InvalidDataFormat { + field_name: "payment_method_data.card.card_exp_year", + })?; + + let cryptogram = google_pay_decrypted_data.cryptogram.clone(); + + PaymentSource::GooglePayPredecrypt(Box::new(GooglePayPredecrypt { + _type: "network_token".to_string(), + token, + token_type: "googlepay".to_string(), + expiry_month, + expiry_year, + eci: "06".to_string(), + cryptogram, + })) + } + }; Ok(( p_source, None, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 1923af66b35..223b5ae4cbf 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -638,6 +638,7 @@ pub struct PaymentMethodTokenFilter { pub payment_method_type: Option<PaymentMethodTypeTokenFilter>, pub long_lived_token: bool, pub apple_pay_pre_decrypt_flow: Option<ApplePayPreDecryptFlow>, + pub google_pay_pre_decrypt_flow: Option<GooglePayPreDecryptFlow>, pub flow: Option<PaymentFlow>, } @@ -655,6 +656,14 @@ pub enum ApplePayPreDecryptFlow { NetworkTokenization, } +#[derive(Debug, Deserialize, Clone, Default)] +#[serde(deny_unknown_fields, rename_all = "snake_case")] +pub enum GooglePayPreDecryptFlow { + #[default] + ConnectorTokenization, + NetworkTokenization, +} + #[derive(Debug, Deserialize, Clone, Default)] pub struct TempLockerEnablePaymentMethodFilter { #[serde(deserialize_with = "deserialize_hashset")] diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index e04b790ab12..cf6a6852dcc 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -108,7 +108,9 @@ 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; use crate::{ - configs::settings::{ApplePayPreDecryptFlow, PaymentFlow, PaymentMethodTypeTokenFilter}, + configs::settings::{ + ApplePayPreDecryptFlow, GooglePayPreDecryptFlow, PaymentFlow, PaymentMethodTypeTokenFilter, + }, consts, core::{ errors::{self, CustomResult, RouterResponse, RouterResult}, @@ -6938,6 +6940,11 @@ fn is_payment_method_tokenization_enabled_for_connector( payment_method_token, connector_filter.apple_pay_pre_decrypt_flow.clone(), ) + && is_google_pay_pre_decrypt_type_connector_tokenization( + payment_method_type, + payment_method_token, + connector_filter.google_pay_pre_decrypt_flow.clone(), + ) && is_payment_flow_allowed_for_connector( mandate_flow_enabled, connector_filter.flow.clone(), @@ -6978,6 +6985,28 @@ fn is_apple_pay_pre_decrypt_type_connector_tokenization( } } +fn is_google_pay_pre_decrypt_type_connector_tokenization( + payment_method_type: Option<storage::enums::PaymentMethodType>, + payment_method_token: Option<&PaymentMethodToken>, + google_pay_pre_decrypt_flow_filter: Option<GooglePayPreDecryptFlow>, +) -> bool { + if let ( + Some(storage::enums::PaymentMethodType::GooglePay), + Some(PaymentMethodToken::GooglePayDecrypt(..)), + ) = (payment_method_type, payment_method_token) + { + !matches!( + google_pay_pre_decrypt_flow_filter, + Some(GooglePayPreDecryptFlow::NetworkTokenization) + ) + } else { + // Always return true for non–Google Pay pre-decrypt cases, + // because the filter is only relevant for Google Pay pre-decrypt tokenization. + // Returning true ensures that other payment methods or token types are not blocked. + true + } +} + fn decide_apple_pay_flow( state: &SessionState, payment_method_type: Option<enums::PaymentMethodType>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 5818cee9519..33b93cc2b73 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -691,7 +691,7 @@ apple_pay = {country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD #tokenization configuration which describe token lifetime and payment method for specific connector [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" } +checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization", google_pay_pre_decrypt_flow = "network_tokenization" } 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" }
2025-09-01T11:34:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/9129) ## Description <!-- Describe your changes in detail --> Added Google Pay Predecrypt 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). --> ## 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. Payments - Create Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_lCkY35u2evZqwny1tXdtyZuu7VufIiJjFTJhuI0kMJAP8RL9XmyomvPqQDBzDvo1' \ --data-raw '{ "amount": 7445, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 7445, "customer_id": "cu_1756821388", "capture_method": "automatic", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "google_pay", "billing": { "address": { "line1": "1467", "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": { "google_pay": { "type": "CARD", "description": "SuccessfulAuth: Visa ‒‒‒‒ 4242", "info": { "assurance_details": { "account_verified": true, "card_holder_authenticated": false }, "card_details": "4242", "card_network": "MASTERCARD" }, "tokenization_data": { "application_primary_account_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "cryptogram": CRYPTOGRAM } } } } }' ``` Response: ``` { "payment_id": "pay_kZOyskQtl91kB3oiAaFS", "merchant_id": "merchant_1756821155", "status": "processing", "amount": 7445, "net_amount": 7445, "shipping_cost": null, "amount_capturable": 7445, "amount_received": null, "connector": "checkout", "client_secret": "pay_kZOyskQtl91kB3oiAaFS_secret_1VaHJKidL1jl9DftOx0Z", "created": "2025-09-02T13:53:01.094Z", "currency": "USD", "customer_id": "cu_1756821181", "customer": { "id": "cu_1756821181", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "google_pay": { "last4": "4242", "card_network": "MASTERCARD", "type": "CARD" } }, "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", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "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": "google_pay", "connector_label": "checkout_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1756821181", "created_at": 1756821181, "expires": 1756824781, "secret": "epk_39573ad4636840e2a30021f811f4a9c4" }, "manual_retry_allowed": false, "connector_transaction_id": "pay_ddjiyc5cghrernmk7gqlpnua6e", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_kZOyskQtl91kB3oiAaFS_1", "payment_link": null, "profile_id": "pro_YQn8ejoAyLrvevnCJLnZ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_hkY02nmI5cs4ygBEbIUg", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-02T14:08:01.094Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-02T13:53:02.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": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` 2. Payments - Retrieve Request: ``` curl --location 'http://localhost:8080/payments/pay_kZOyskQtl91kB3oiAaFS?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_lCkY35u2evZqwny1tXdtyZuu7VufIiJjFTJhuI0kMJAP8RL9XmyomvPqQDBzDvo1' ``` Response: ``` { "payment_id": "pay_kZOyskQtl91kB3oiAaFS", "merchant_id": "merchant_1756821155", "status": "succeeded", "amount": 7445, "net_amount": 7445, "shipping_cost": null, "amount_capturable": 0, "amount_received": 7445, "connector": "checkout", "client_secret": "pay_kZOyskQtl91kB3oiAaFS_secret_1VaHJKidL1jl9DftOx0Z", "created": "2025-09-02T13:53:01.094Z", "currency": "USD", "customer_id": "cu_1756821181", "customer": { "id": "cu_1756821181", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "google_pay": { "last4": "4242", "card_network": "MASTERCARD", "type": "CARD" } }, "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", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "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": "google_pay", "connector_label": "checkout_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": "pay_ddjiyc5cghrernmk7gqlpnua6e", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_kZOyskQtl91kB3oiAaFS_1", "payment_link": null, "profile_id": "pro_YQn8ejoAyLrvevnCJLnZ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_hkY02nmI5cs4ygBEbIUg", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-02T14:08:01.094Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": "pm_LSM4mcvLDbufpOlCjb1X", "network_transaction_id": null, "payment_method_status": "inactive", "updated": "2025-09-02T13:53:11.202Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": 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.117.0
b26e845198407f3672a7f80d8eea670419858e0e
b26e845198407f3672a7f80d8eea670419858e0e
juspay/hyperswitch
juspay__hyperswitch-9103
Bug: [BUG] UCS PSync call fails for Cashtocode ### Bug Description Cashtocode does not support PSync. When a PSync call is processed via Hyperswitch, the RouterData remains unchanged (payment status is not modified). However, when the same PSync call goes via UCS, UCS returns an error response. This causes inconsistent behavior between Hyperswitch and UCS flows. ### Expected Behavior Replicate behaviour of PSync when payment was made throught Hyperswitch. ### Actual Behavior { "error": { "type": "api", "message": "Something went wrong", "code": "HE_00" } } ### Steps To Reproduce Make an evoucher payment for cashtocode connector via UCS, and do a PSync. ### Context For The Bug _No response_ ### Environment router 2025.08.29.0-3-g0194b7a-dirty-0194b7a-2025-08-29T10:00:27.000000000Z macos sequoia rustc 1.87.0 ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index 0d5eb5f4fa3..dcf5bb24fb6 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -1173,6 +1173,7 @@ url = "http://localhost:8080" # Open Router URL base_url = "http://localhost:8000" # Unified Connector Service Base URL connection_timeout = 10 # Connection Timeout Duration in Seconds ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only +ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call [grpc_client.recovery_decider_client] # Revenue recovery client base url base_url = "http://127.0.0.1:8080" #Base URL diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 77fef227921..bfba035c1f3 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -385,6 +385,7 @@ connector_names = "connector_names" # Comma-separated list of allowed connec base_url = "http://localhost:8000" # Unified Connector Service Base URL connection_timeout = 10 # Connection Timeout Duration in Seconds ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only +ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call [revenue_recovery] # monitoring threshold - 120 days diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index d5d2f821eed..6dc2d098850 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -862,3 +862,4 @@ connector_list = "worldpayvantiv" [grpc_client.unified_connector_service] ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only +ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call diff --git a/config/deployments/production.toml b/config/deployments/production.toml index cf08971a96e..311733923f2 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -871,4 +871,5 @@ click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [grpc_client.unified_connector_service] ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only +ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 5625a22eeff..822d8d7dae7 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -881,3 +881,4 @@ connector_list = "worldpayvantiv" [grpc_client.unified_connector_service] ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only +ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call diff --git a/config/development.toml b/config/development.toml index c838e2add1d..7320594bf1b 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1295,6 +1295,7 @@ enabled = "true" base_url = "http://localhost:8000" connection_timeout = 10 ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only +ucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call [revenue_recovery] monitoring_threshold_in_seconds = 60 diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs index 81bb2dc8988..904238ccf5e 100644 --- a/crates/external_services/src/grpc_client/unified_connector_service.rs +++ b/crates/external_services/src/grpc_client/unified_connector_service.rs @@ -128,6 +128,10 @@ pub struct UnifiedConnectorServiceClientConfig { /// Set of external services/connectors available for the unified connector service #[serde(default, deserialize_with = "deserialize_hashset")] pub ucs_only_connectors: HashSet<Connector>, + + /// Set of connectors for which psync is disabled in unified connector service + #[serde(default, deserialize_with = "deserialize_hashset")] + pub ucs_psync_disabled_connectors: HashSet<Connector>, } /// Contains the Connector Auth Type and related authentication data. diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index 93a2c1ecd48..9f86b6e73bf 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -1,4 +1,4 @@ -use std::collections::HashMap; +use std::{collections::HashMap, str::FromStr}; use async_trait::async_trait; use error_stack::ResultExt; @@ -226,6 +226,29 @@ impl Feature<api::PSync, types::PaymentsSyncData> merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, merchant_context: &domain::MerchantContext, ) -> RouterResult<()> { + let connector_name = self.connector.clone(); + let connector_enum = common_enums::connector_enums::Connector::from_str(&connector_name) + .change_context(ApiErrorResponse::IncorrectConnectorNameGiven)?; + + let is_ucs_psync_disabled = state + .conf + .grpc_client + .unified_connector_service + .as_ref() + .is_some_and(|config| { + config + .ucs_psync_disabled_connectors + .contains(&connector_enum) + }); + + if is_ucs_psync_disabled { + logger::info!( + "UCS PSync call disabled for connector: {}, skipping UCS call", + connector_name + ); + return Ok(()); + } + let client = state .grpc_client .unified_connector_service_client
2025-08-29T07:07:24Z
## 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 --> Cashtocode does not support PSync. When a PSync call is processed via Hyperswitch, the RouterData remains unchanged (payment status is not modified). However, when the same PSync call goes via UCS, UCS returns an error response. This causes inconsistent behavior between Hyperswitch and UCS flows. To replicate Hyperswitch behavior when authorize was done through UCS: - Introduced configuration "ucs_psync_disabled_connectors" under grpc_client.unified_connector_service. - During call_unified_connector_service, we check if the connector is listed in "ucs_psync_disabled_connectors". If the connector is present, UCS PSync call is skipped, and unmodified RouterData is returned (same as Hyperswitch behavior). ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Make a evoucher payment through UCS for Cashtocode. <details> <summary>Enable Payments via UCS</summary> ```sh curl --location 'http://localhost:8080/configs/' \ --header 'Content-Type: application/json' \ --header 'api-key: ' \ --header 'x-tenant-id: public' \ --data '{ "key": "ucs_rollout_config_merchant_1756446892_cashtocode_reward_Authorize", "value": "1" }' ``` </details> <details> <summary>Create Payment Evoucher For Cashtocode</summary> Request ```json { "amount": 1000, "currency": "USD", "confirm": true, "payment_method_data": "reward", "payment_method_type": "evoucher", "payment_method":"reward", "capture_method": "automatic", "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1.2 Safari/605.1.15", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "en-US", "color_depth": 24, "screen_height": 1117, "screen_width": 1728, "time_zone": -330, "java_enabled": true, "java_script_enabled": true }, "customer_id": "cus_5ZiQdWmdv9efuLCPWeoN", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://www.google.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" }, "phone": { "number": "1233456789", "country_code": "+1" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" }, "phone": { "number": "1233456789", "country_code": "+1" } } } ``` Response ```json { "payment_id": "pay_zBEXBJSHcgiiBihUBZd6", "merchant_id": "merchant_1756640756", "status": "requires_customer_action", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "cashtocode", "client_secret": "pay_zBEXBJSHcgiiBihUBZd6_secret_OuxmlTO7YOGOVWzXAFB2", "created": "2025-08-31T12:04:05.954Z", "currency": "USD", "customer_id": "cus_5ZiQdWmdv9efuLCPWeoN", "customer": { "id": "cus_5ZiQdWmdv9efuLCPWeoN", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "reward", "payment_method_data": "reward", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null, "origin_zip": null }, "phone": { "number": "1233456789", "country_code": "+1" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null, "origin_zip": null }, "phone": { "number": "1233456789", "country_code": "+1" }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://www.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_zBEXBJSHcgiiBihUBZd6/merchant_1756640756/pay_zBEXBJSHcgiiBihUBZd6_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "evoucher", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cus_5ZiQdWmdv9efuLCPWeoN", "created_at": 1756641845, "expires": 1756645445, "secret": "epk_47eacc344437434e97664bd6b3e2722a" }, "manual_retry_allowed": null, "connector_transaction_id": "pay_zBEXBJSHcgiiBihUBZd6_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "unified_connector_service" }, "reference_id": null, "payment_link": null, "profile_id": "pro_MrgPu8NG45h4Ea7ah7kC", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_mRMHa49InsH1tw9OQKXk", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-31T12:19:05.954Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": -330, "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1.2 Safari/605.1.15", "color_depth": 24, "java_enabled": true, "screen_width": 1728, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1117, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-31T12:04:06.829Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": "{\"payUrl\":\"https://cluster05.api-test.cashtocode.com/paytoken/redirect?token=ODJkYzNkOTAtZDk3Mi00MWQ1LThlMjItNTMyYzM3ZmQyZDYw\"}", "enable_partial_authorization": null } ``` </details> Do a PSync. <details> <summary>PSync repsponse</summary> ```json { "payment_id": "pay_zBEXBJSHcgiiBihUBZd6", "merchant_id": "merchant_1756640756", "status": "requires_customer_action", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "cashtocode", "client_secret": "pay_zBEXBJSHcgiiBihUBZd6_secret_OuxmlTO7YOGOVWzXAFB2", "created": "2025-08-31T12:04:05.954Z", "currency": "USD", "customer_id": "cus_5ZiQdWmdv9efuLCPWeoN", "customer": { "id": "cus_5ZiQdWmdv9efuLCPWeoN", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "attempts": [ { "attempt_id": "pay_zBEXBJSHcgiiBihUBZd6_1", "status": "authentication_pending", "amount": 1000, "order_tax_amount": null, "currency": "USD", "connector": "cashtocode", "error_message": null, "payment_method": "reward", "connector_transaction_id": "pay_zBEXBJSHcgiiBihUBZd6_1", "capture_method": "automatic", "authentication_type": "no_three_ds", "created_at": "2025-08-31T12:04:05.955Z", "modified_at": "2025-08-31T12:04:43.026Z", "cancellation_reason": null, "mandate_id": null, "error_code": null, "payment_token": null, "connector_metadata": null, "payment_experience": null, "payment_method_type": "evoucher", "reference_id": null, "unified_code": null, "unified_message": null, "client_source": null, "client_version": null } ], "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "reward", "payment_method_data": "reward", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null, "origin_zip": null }, "phone": { "number": "1233456789", "country_code": "+1" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null, "origin_zip": null }, "phone": { "number": "1233456789", "country_code": "+1" }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://www.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_zBEXBJSHcgiiBihUBZd6/merchant_1756640756/pay_zBEXBJSHcgiiBihUBZd6_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "evoucher", "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": "pay_zBEXBJSHcgiiBihUBZd6_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "unified_connector_service" }, "reference_id": null, "payment_link": null, "profile_id": "pro_MrgPu8NG45h4Ea7ah7kC", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_mRMHa49InsH1tw9OQKXk", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-31T12:19:05.954Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": -330, "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1.2 Safari/605.1.15", "color_depth": 24, "java_enabled": true, "screen_width": 1728, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1117, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-31T12:04:54.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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details> <img width="1203" height="51" alt="Screenshot 2025-08-31 at 5 26 20β€―PM" src="https://github.com/user-attachments/assets/62cc23de-bcf9-4b65-bb32-df7776c92556" /> ## 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.116.0
971e17e0f3f8db7ec134b55c786ee1c7429430cd
971e17e0f3f8db7ec134b55c786ee1c7429430cd
juspay/hyperswitch
juspay__hyperswitch-9107
Bug: add configs for Calculate job
diff --git a/config/config.example.toml b/config/config.example.toml index e6bbef7fddf..0d5eb5f4fa3 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -1203,7 +1203,10 @@ max_retries_per_day = 20 max_retry_count_for_thirty_day = 20 [revenue_recovery.recovery_timestamp] # Timestamp configuration for Revenue Recovery -initial_timestamp_in_hours = 1 # number of hours added to start time for Decider service of Revenue Recovery +initial_timestamp_in_seconds = 3600 # number of seconds added to start time for Decider service of Revenue Recovery +job_schedule_buffer_time_in_seconds = 3600 # buffer time in seconds to schedule the job for Revenue Recovery +reopen_workflow_buffer_time_in_seconds = 3600 # time in seconds to be added in scheduling for calculate workflow +max_random_schedule_delay_in_seconds = 300 # max random delay in seconds to schedule the payment for Revenue Recovery [clone_connector_allowlist] merchant_ids = "merchant_ids" # Comma-separated list of allowed merchant IDs diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 40868da8f3f..77fef227921 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -410,11 +410,14 @@ max_retries_per_day = 20 max_retry_count_for_thirty_day = 20 [revenue_recovery.recovery_timestamp] # Timestamp configuration for Revenue Recovery -initial_timestamp_in_hours = 1 # number of hours added to start time for Decider service of Revenue Recovery +initial_timestamp_in_seconds = 3600 # number of seconds added to start time for Decider service of Revenue Recovery +job_schedule_buffer_time_in_seconds = 3600 # time in seconds to be added in schedule time as a buffer +reopen_workflow_buffer_time_in_seconds = 3600 # time in seconds to be added in scheduling for calculate workflow +max_random_schedule_delay_in_seconds = 300 # max random delay in seconds to schedule the payment for Revenue Recovery [chat] enabled = false # Enable or disable chat features hyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow host [proxy_status_mapping] -proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response \ No newline at end of file +proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response diff --git a/config/development.toml b/config/development.toml index 7db6e74568b..4f898e07570 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1302,7 +1302,10 @@ retry_algorithm_type = "cascading" redis_ttl_in_seconds=3888000 [revenue_recovery.recovery_timestamp] -initial_timestamp_in_hours = 1 +initial_timestamp_in_seconds = 3600 +job_schedule_buffer_time_in_seconds = 3600 +reopen_workflow_buffer_time_in_seconds = 3600 +max_random_schedule_delay_in_seconds = 300 [revenue_recovery.card_config.amex] max_retries_per_day = 20 diff --git a/config/docker_compose.toml b/config/docker_compose.toml index fd5a6a9a0c8..a11475d6cb6 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -1219,6 +1219,11 @@ max_retry_count_for_thirty_day = 20 max_retries_per_day = 20 max_retry_count_for_thirty_day = 20 +[revenue_recovery.recovery_timestamp] # Timestamp configuration for Revenue Recovery +initial_timestamp_in_seconds = 3600 # number of seconds added to start time for Decider service of Revenue Recovery +job_schedule_buffer_time_in_seconds = 3600 # time in seconds to be added in schedule time as a buffer +reopen_workflow_buffer_time_in_seconds = 60 # time in seconds to be added in scheduling for calculate workflow + [clone_connector_allowlist] merchant_ids = "merchant_123, merchant_234" # Comma-separated list of allowed merchant IDs connector_names = "stripe, adyen" # Comma-separated list of allowed connector names diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs index 206c5026a63..d63cbd5f906 100644 --- a/crates/router/src/core/revenue_recovery.rs +++ b/crates/router/src/core/revenue_recovery.rs @@ -56,8 +56,9 @@ pub async fn upsert_calculate_pcr_task( // Create process tracker ID in the format: CALCULATE_WORKFLOW_{payment_intent_id} let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr()); - // Set scheduled time to 1 hour from now - let schedule_time = common_utils::date_time::now() + time::Duration::hours(1); + // Scheduled time is now because this will be the first entry in + // process tracker and we dont want to wait + let schedule_time = common_utils::date_time::now(); let payment_attempt_id = payment_attempt_id .ok_or(error_stack::report!( @@ -580,7 +581,13 @@ pub async fn perform_calculate_workflow( update_calculate_job_schedule_time( db, process, - time::Duration::minutes(15), + time::Duration::seconds( + state + .conf + .revenue_recovery + .recovery_timestamp + .job_schedule_buffer_time_in_seconds, + ), scheduled_token.scheduled_at, &connector_customer_id, ) @@ -607,7 +614,13 @@ pub async fn perform_calculate_workflow( update_calculate_job_schedule_time( db, process, - time::Duration::minutes(15), + time::Duration::seconds( + state + .conf + .revenue_recovery + .recovery_timestamp + .job_schedule_buffer_time_in_seconds, + ), Some(common_utils::date_time::now()), &connector_customer_id, ) diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index 1777f4cb22d..d2667cc63b0 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -1180,7 +1180,14 @@ pub async fn reopen_calculate_workflow_on_payment_failure( // 3. Set business status to QUEUED // 4. Schedule for immediate execution let new_retry_count = process.retry_count + 1; - let new_schedule_time = common_utils::date_time::now() + time::Duration::hours(1); + let new_schedule_time = common_utils::date_time::now() + + time::Duration::seconds( + state + .conf + .revenue_recovery + .recovery_timestamp + .reopen_workflow_buffer_time_in_seconds, + ); let pt_update = storage::ProcessTrackerUpdate::Update { name: Some(task.to_string()), diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rs index 3c3df991d4f..5a3f9f1bf7e 100644 --- a/crates/router/src/types/storage/revenue_recovery.rs +++ b/crates/router/src/types/storage/revenue_recovery.rs @@ -77,13 +77,19 @@ pub struct RevenueRecoverySettings { #[derive(Debug, serde::Deserialize, Clone)] pub struct RecoveryTimestamp { - pub initial_timestamp_in_hours: i64, + pub initial_timestamp_in_seconds: i64, + pub job_schedule_buffer_time_in_seconds: i64, + pub reopen_workflow_buffer_time_in_seconds: i64, + pub max_random_schedule_delay_in_seconds: i64, } impl Default for RecoveryTimestamp { fn default() -> Self { Self { - initial_timestamp_in_hours: 1, + initial_timestamp_in_seconds: 1, + job_schedule_buffer_time_in_seconds: 15, + reopen_workflow_buffer_time_in_seconds: 60, + max_random_schedule_delay_in_seconds: 300, } } } diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rs index 4d42be64f9a..b85ebd3ff11 100644 --- a/crates/router/src/workflows/revenue_recovery.rs +++ b/crates/router/src/workflows/revenue_recovery.rs @@ -324,9 +324,9 @@ pub(crate) async fn get_schedule_time_for_smart_retry( let start_time_primitive = payment_intent.created_at; let recovery_timestamp_config = &state.conf.revenue_recovery.recovery_timestamp; - let modified_start_time_primitive = start_time_primitive.saturating_add(time::Duration::hours( - recovery_timestamp_config.initial_timestamp_in_hours, - )); + let modified_start_time_primitive = start_time_primitive.saturating_add( + time::Duration::seconds(recovery_timestamp_config.initial_timestamp_in_seconds), + ); let start_time_proto = date_time::convert_to_prost_timestamp(modified_start_time_primitive); @@ -550,7 +550,8 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type( .change_context(errors::ProcessTrackerError::EApiErrorResponse)?; } } - let delayed_schedule_time = scheduled_time.map(add_random_delay_to_schedule_time); + let delayed_schedule_time = + scheduled_time.map(|time| add_random_delay_to_schedule_time(state, time)); Ok(delayed_schedule_time) } @@ -776,10 +777,16 @@ pub async fn check_hard_decline( #[cfg(feature = "v2")] pub fn add_random_delay_to_schedule_time( + state: &SessionState, schedule_time: time::PrimitiveDateTime, ) -> time::PrimitiveDateTime { let mut rng = rand::thread_rng(); - let random_secs = rng.gen_range(1..=3600); + let delay_limit = state + .conf + .revenue_recovery + .recovery_timestamp + .max_random_schedule_delay_in_seconds; + let random_secs = rng.gen_range(1..=delay_limit); logger::info!("Adding random delay of {random_secs} seconds to schedule time"); schedule_time + time::Duration::seconds(random_secs) }
2025-08-29T11:47:48Z
## 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 --> Add configs for calculate job ### 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` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.116.0
8cfa966d34e914c8df06f000b59fdad53d3f9902
8cfa966d34e914c8df06f000b59fdad53d3f9902
juspay/hyperswitch
juspay__hyperswitch-9109
Bug: [FEAT: CONNECTOR] [PAYLOAD] Add setup mandate support ```sh curl --location 'https://api.payload.com/transactions' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --header 'Authorization: Basic apiKey' \ --data-urlencode 'amount=0' \ --data-urlencode 'type=payment' \ --data-urlencode 'payment_method%5Btype%5D=card' \ --data-urlencode 'payment_method%5Bcard%5D%5Bcard_number%5D=4242 4242 4242 4242' \ --data-urlencode 'payment_method%5Bcard%5D%5Bexpiry%5D=12/25' \ --data-urlencode 'payment_method%5Bcard%5D%5Bcard_code%5D=123' \ --data-urlencode 'payment_method%5Bbilling_address%5D%5Bcountry_code%5D=US' \ --data-urlencode 'payment_method%5Bbilling_address%5D%5Bpostal_code%5D=11111' \ --data-urlencode 'payment_method%5Bbilling_address%5D%5Bcity%5D=Los Angeles' \ --data-urlencode 'payment_method%5Bbilling_address%5D%5Bstate_province%5D=Texas' \ --data-urlencode 'payment_method%5Bbilling_address%5D%5Bstreet_address%5D%22=Line1' \ --data-urlencode 'payment_method%5Bdefault_payment_method%5D=false' \ --data-urlencode 'payment_method%5Bkeep_active%5D=true' ``` ```json { "amount": 0, "attrs": null, "avs": "street_and_zip", "created_at": "Fri, 29 Aug 2025 12:56:29 GMT", "customer_id": null, "description": null, "funding_delay": 2, "funding_status": "pending", "funding_type": "debit", "id": "", "ledger": [], "modified_at": "Fri, 29 Aug 2025 12:56:29 GMT", "notes": null, "object": "transaction", "order_number": null, "payment_method": { "account_holder": null, "attrs": null, "bank_name": "STRIPE PAYMENTS UK, LTD.", "billing_address": { "city": "Los Angeles", "country_code": "US", "postal_code": "11111", "state_province": "Te", "street_address": "Line1", "unit_number": null }, "card": { "card_brand": "visa", "card_number": "xxxxxxxxxxxx4242", "card_type": "credit", "expiry": "2025-12-31" }, "created_at": "Fri, 29 Aug 2025 12:56:29 GMT", "customer_id": null, "default_credit_method": false, "default_deposit_method": false, "default_payment_method": false, "default_reversal_method": null, "description": "Visa x-4242", "email": null, "id": "", "keep_active": true, "modified_at": "Fri, 29 Aug 2025 12:56:29 GMT", "object": "payment_method", "phone_number": null, "status": "active", "transfer_type": "send-only", "type": "card", "verification_status": "not-verified" }, "payment_method_id": "", "processed_date": "2025-09-02", "processing_id": "", "processing_method": null, "processing_method_id": null, "reader_id": null, "ref_number": "PL-V7P-ZOI-74Y", "rejected_date": null, "risk_flag": "allowed", "risk_score": 0, "source": "api", "status": "processed", "status_code": "approved", "status_message": "Transaction approved.", "type": "payment" } ``` connector indeed supports 0 dollar mandates!
diff --git a/crates/hyperswitch_connectors/src/connectors/payload.rs b/crates/hyperswitch_connectors/src/connectors/payload.rs index 792fa493c4d..3967736fd06 100644 --- a/crates/hyperswitch_connectors/src/connectors/payload.rs +++ b/crates/hyperswitch_connectors/src/connectors/payload.rs @@ -33,7 +33,7 @@ use hyperswitch_domain_models::{ }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, - PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData, }, }; use hyperswitch_interfaces::{ @@ -44,7 +44,7 @@ use hyperswitch_interfaces::{ configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, - types::{self, PaymentsVoidType, Response}, + types::{self, PaymentsVoidType, Response, SetupMandateType}, webhooks, }; use masking::{ExposeInterface, Mask, Secret}; @@ -190,15 +190,77 @@ impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> fo impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Payload {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Payload { - fn build_request( + fn get_headers( + &self, + req: &SetupMandateRouterData, + 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: &SetupMandateRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}/transactions", self.base_url(connectors))) + } + + fn get_request_body( &self, - _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + req: &SetupMandateRouterData, _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = requests::PayloadCardsRequestData::try_from(req)?; + Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { - Err( - errors::ConnectorError::NotImplemented("Setup Mandate flow for Payload".to_string()) - .into(), - ) + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&SetupMandateType::get_url(self, req, connectors)?) + .headers(SetupMandateType::get_headers(self, req, connectors)?) + .set_body(SetupMandateType::get_request_body(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &SetupMandateRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> { + let response: responses::PayloadPaymentsResponse = res + .response + .parse_struct("PayloadPaymentsResponse") + .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) } } diff --git a/crates/hyperswitch_connectors/src/connectors/payload/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payload/transformers.rs index 778aedb89fd..90f4a650647 100644 --- a/crates/hyperswitch_connectors/src/connectors/payload/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/payload/transformers.rs @@ -5,12 +5,16 @@ use common_enums::enums; use common_utils::{ext_traits::ValueExt, types::StringMajorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::{ + address::AddressDetails, payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, - router_request_types::{PaymentsAuthorizeData, ResponseId}, + router_request_types::ResponseId, router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData}, - types::{PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, RefundsRouterData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, RefundsRouterData, + SetupMandateRouterData, + }, }; use hyperswitch_interfaces::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, @@ -23,16 +27,77 @@ use super::{requests, responses}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ - is_manual_capture, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, + get_unimplemented_payment_method_error_message, is_manual_capture, AddressDetailsData, + CardData, PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData, RouterData as OtherRouterData, }, }; type Error = error_stack::Report<errors::ConnectorError>; -//TODO: Fill the struct with respective fields +fn build_payload_cards_request_data( + payment_method_data: &PaymentMethodData, + connector_auth_type: &ConnectorAuthType, + currency: enums::Currency, + amount: StringMajorUnit, + billing_address: &AddressDetails, + capture_method: Option<enums::CaptureMethod>, + is_mandate: bool, +) -> Result<requests::PayloadCardsRequestData, Error> { + if let PaymentMethodData::Card(req_card) = payment_method_data { + let payload_auth = PayloadAuth::try_from((connector_auth_type, currency))?; + + let card = requests::PayloadCard { + number: req_card.clone().card_number, + expiry: req_card + .clone() + .get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?, + cvc: req_card.card_cvc.clone(), + }; + + let city = billing_address.get_city()?.to_owned(); + let country = billing_address.get_country()?.to_owned(); + let postal_code = billing_address.get_zip()?.to_owned(); + let state_province = billing_address.get_state()?.to_owned(); + let street_address = billing_address.get_line1()?.to_owned(); + + let billing_address = requests::BillingAddress { + city, + country, + postal_code, + state_province, + street_address, + }; + + // For manual capture, set status to "authorized" + let status = if is_manual_capture(capture_method) { + Some(responses::PayloadPaymentStatus::Authorized) + } else { + None + }; + + Ok(requests::PayloadCardsRequestData { + amount, + card, + transaction_types: requests::TransactionTypes::Payment, + payment_method_type: "card".to_string(), + status, + billing_address, + processing_id: payload_auth.processing_account_id, + keep_active: is_mandate, + }) + } else { + Err( + errors::ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( + "Payload", + )) + .into(), + ) + } +} + pub struct PayloadRouterData<T> { - pub amount: StringMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub amount: StringMajorUnit, pub router_data: T, } @@ -104,6 +169,33 @@ impl TryFrom<&ConnectorAuthType> for PayloadAuthType { } } +impl TryFrom<&SetupMandateRouterData> for requests::PayloadCardsRequestData { + type Error = Error; + fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> { + match item.request.amount { + Some(amount) if amount > 0 => Err(errors::ConnectorError::FlowNotSupported { + flow: "Setup mandate with non zero amount".to_string(), + connector: "Payload".to_string(), + } + .into()), + _ => { + let billing_address = item.get_billing_address()?; + let is_mandate = item.request.is_customer_initiated_mandate_payment(); + + build_payload_cards_request_data( + &item.request.payment_method_data, + &item.connector_auth_type, + item.request.currency, + StringMajorUnit::zero(), + billing_address, + item.request.capture_method, + is_mandate, + ) + } + } + } +} + impl TryFrom<&PayloadRouterData<&PaymentsAuthorizeRouterData>> for requests::PayloadPaymentsRequest { @@ -119,55 +211,21 @@ impl TryFrom<&PayloadRouterData<&PaymentsAuthorizeRouterData>> } match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(req_card) => { - let payload_auth = PayloadAuth::try_from(( - &item.router_data.connector_auth_type, - item.router_data.request.currency, - ))?; - let card = requests::PayloadCard { - number: req_card.clone().card_number, - expiry: req_card - .clone() - .get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?, - cvc: req_card.card_cvc, - }; + PaymentMethodData::Card(_) => { + let billing_address = item.router_data.get_billing_address()?; let is_mandate = item.router_data.request.is_mandate_payment(); - let address = item.router_data.get_billing_address()?; - - // Check for required fields and fail if they're missing - let city = address.get_city()?.to_owned(); - let country = address.get_country()?.to_owned(); - let postal_code = address.get_zip()?.to_owned(); - let state_province = address.get_state()?.to_owned(); - let street_address = address.get_line1()?.to_owned(); - - let billing_address = requests::BillingAddress { - city, - country, - postal_code, - state_province, - street_address, - }; - // For manual capture, set status to "authorized" - let status = if is_manual_capture(item.router_data.request.capture_method) { - Some(responses::PayloadPaymentStatus::Authorized) - } else { - None - }; + let cards_data = build_payload_cards_request_data( + &item.router_data.request.payment_method_data, + &item.router_data.connector_auth_type, + item.router_data.request.currency, + item.amount.clone(), + billing_address, + item.router_data.request.capture_method, + is_mandate, + )?; - Ok(Self::PayloadCardsRequest(Box::new( - requests::PayloadCardsRequestData { - amount: item.amount.clone(), - card, - transaction_types: requests::TransactionTypes::Payment, - payment_method_type: "card".to_string(), - status, - billing_address, - processing_id: payload_auth.processing_account_id, - keep_active: is_mandate, - }, - ))) + Ok(Self::PayloadCardsRequest(Box::new(cards_data))) } PaymentMethodData::MandatePayment => { // For manual capture, set status to "authorized" @@ -206,7 +264,7 @@ impl From<responses::PayloadPaymentStatus> for common_enums::AttemptStatus { } } -impl<F, T> +impl<F: 'static, T> TryFrom<ResponseRouterData<F, responses::PayloadPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> where @@ -220,10 +278,13 @@ where responses::PayloadPaymentsResponse::PayloadCardsResponse(response) => { let status = enums::AttemptStatus::from(response.status); - let request_any: &dyn std::any::Any = &item.data.request; - let is_mandate_payment = request_any - .downcast_ref::<PaymentsAuthorizeData>() - .is_some_and(|req| req.is_mandate_payment()); + let router_data: &dyn std::any::Any = &item.data; + let is_mandate_payment = router_data + .downcast_ref::<PaymentsAuthorizeRouterData>() + .is_some_and(|router_data| router_data.request.is_mandate_payment()) + || router_data + .downcast_ref::<SetupMandateRouterData>() + .is_some(); let mandate_reference = if is_mandate_payment { let connector_payment_method_id =
2025-08-29T19:23:50Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> this pr introduces 0 dollar mandate (setup mandate) for payload 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). --> feature coverage. closes https://github.com/juspay/hyperswitch/issues/9109 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Payment Method Id: <details> <summary>CIT</summary> ```sh curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_uGs7ayYh5hoENIMQ43lMkQGC2i863OXlIg5XhqxcyfaKjNYcOtUv1YRrUTYuD1WW' \ --data-raw '{ "currency": "USD", "amount": 0, "confirm": true, "customer_id": "payload_connector_test", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "return_url": "https://www.google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "card", "setup_future_usage": "off_session", "payment_type": "setup_mandate", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "billing": { "address": { "line1": "1467", "line2": "CA", "line3": "Harrison Street", "city": "San Fransico", "state": "CA", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "CA", "zip": "94122", "country": "US", "first_name": "john", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/22F76 [FBAN/FBIOS;FBAV/520.0.0.38.101;FBBV/756351453;FBDV/iPhone14,7;FBMD/iPhone;FBSN/iOS;FBSV/18.5;FBSS/3;FBID/phone;FBLC/fr_FR;FBOP/5;FBRV/760683563;IABMV/1]", "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": "109.71.40.0" }, "metadata": { "order_category": "applepay" }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 300, "account_name": "transaction_processing" } ], "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/22F76 [FBAN/FBIOS;FBAV/520.0.0.38.101;FBBV/756351453;FBDV/iPhone14,7;FBMD/iPhone;FBSN/iOS;FBSV/18.5;FBSS/3;FBID/phone;FBLC/fr_FR;FBOP/5;FBRV/760683563;IABMV/1]" } } }' ``` ```json { "payment_id": "pay_4ybWqJgD05Ur3L8rmDwd", "merchant_id": "postman_merchant_GHAction_1756491108", "status": "succeeded", "amount": 0, "net_amount": 0, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "payload", "client_secret": "pay_4ybWqJgD05Ur3L8rmDwd_secret_aRQ0QjaG7ROtanCpfQ2x", "created": "2025-08-29T19:00:35.597Z", "currency": "USD", "customer_id": "payload_connector_test", "customer": { "id": "payload_connector_test", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "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": "CA", "first_name": "john", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "CA", "line3": "Harrison Street", "zip": "94122", "state": "CA", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": [ { "sku": null, "upc": null, "brand": null, "amount": 300, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "description": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "total_amount": null, "commodity_code": null, "unit_of_measure": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null, "unit_discount_amount": null } ], "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://www.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": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "payload_connector_test", "created_at": 1756494035, "expires": 1756497635, "secret": "epk_dd8f8b864b6e40a5af4f366967aa7c81" }, "manual_retry_allowed": false, "connector_transaction_id": "txn_3euQY8b9lWzU1wQHkqM3F", "frm_message": null, "metadata": { "order_category": "applepay" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "PL-JOE-QIZ-TY7", "payment_link": null, "profile_id": "pro_JprfwhCqYDKEKZwcwHSo", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nXQ68xSyk8uShjAhLx1p", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-29T19:15:35.597Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "109.71.40.0", "user_agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/22F76 [FBAN/FBIOS;FBAV/520.0.0.38.101;FBBV/756351453;FBDV/iPhone14,7;FBMD/iPhone;FBSN/iOS;FBSV/18.5;FBSS/3;FBID/phone;FBLC/fr_FR;FBOP/5;FBRV/760683563;IABMV/1]", "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_channel": null, "payment_method_id": "pm_aNYtgqzHA7LuY38clFX6", "network_transaction_id": null, "payment_method_status": "active", "updated": "2025-08-29T19:00:37.348Z", "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": "pm_3euQY8Ztroeb9d3FizYWe", "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details> <details> <summary>DB</summary> <img width="1386" height="621" alt="image" src="https://github.com/user-attachments/assets/1018173e-5f30-4088-9e06-a1a8395a4b44" /> </details> <details> <summary>MIT</summary> ```sh curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_uGs7ayYh5hoENIMQ43lMkQGC2i863OXlIg5XhqxcyfaKjNYcOtUv1YRrUTYuD1WW' \ --data-raw '{ "amount": 499, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "payload_connector_test", "email": "guest@example.com", "off_session": true, "recurring_details": { "type": "payment_method_id", "data": "pm_aNYtgqzHA7LuY38clFX6" }, "authentication_type": "no_three_ds" }' ``` ```json { "payment_id": "pay_jLbHJLkFleJp5BKY9eP1", "merchant_id": "postman_merchant_GHAction_1756491108", "status": "succeeded", "amount": 499, "net_amount": 499, "shipping_cost": null, "amount_capturable": 0, "amount_received": 499, "connector": "payload", "client_secret": "pay_jLbHJLkFleJp5BKY9eP1_secret_H21H8T0hMFJyIOEe2cbb", "created": "2025-08-29T19:01:50.520Z", "currency": "USD", "customer_id": "payload_connector_test", "customer": { "id": "payload_connector_test", "name": "Joseph Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+65" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "Joseph 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": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "payload_connector_test", "created_at": 1756494110, "expires": 1756497710, "secret": "epk_f267def8c8e444a79293278502e04313" }, "manual_retry_allowed": false, "connector_transaction_id": "txn_3euQYQOPSgkZCsRjGp8BI", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "PL-PTQ-PL7-04C", "payment_link": null, "profile_id": "pro_JprfwhCqYDKEKZwcwHSo", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nXQ68xSyk8uShjAhLx1p", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-29T19:16:50.520Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": "pm_aNYtgqzHA7LuY38clFX6", "network_transaction_id": null, "payment_method_status": "active", "updated": "2025-08-29T19:01:51.480Z", "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": "pm_3euQY8Ztroeb9d3FizYWe", "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details> Mandate Id: <details> <summary>CIT</summary> ```sh curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_uGs7ayYh5hoENIMQ43lMkQGC2i863OXlIg5XhqxcyfaKjNYcOtUv1YRrUTYuD1WW' \ --data-raw '{ "currency": "USD", "amount": 0, "confirm": true, "customer_id": "payload_connector_test", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "return_url": "https://www.google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "card", "setup_future_usage": "off_session", "payment_type": "setup_mandate", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "billing": { "address": { "line1": "1467", "line2": "CA", "line3": "Harrison Street", "city": "San Fransico", "state": "CA", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "CA", "zip": "94122", "country": "US", "first_name": "john", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/22F76 [FBAN/FBIOS;FBAV/520.0.0.38.101;FBBV/756351453;FBDV/iPhone14,7;FBMD/iPhone;FBSN/iOS;FBSV/18.5;FBSS/3;FBID/phone;FBLC/fr_FR;FBOP/5;FBRV/760683563;IABMV/1]", "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": "109.71.40.0" }, "metadata": { "order_category": "applepay" }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 300, "account_name": "transaction_processing" } ], "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00Z", "end_date": "2023-05-21T00:00:00Z", "metadata": { "frequency": "13" } } } } }' ``` ```json { "payment_id": "pay_cb28Jbsq7T9gcQj6guLd", "merchant_id": "postman_merchant_GHAction_1756491108", "status": "succeeded", "amount": 0, "net_amount": 0, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "payload", "client_secret": "pay_cb28Jbsq7T9gcQj6guLd_secret_uPq3s4qwO4kMcC33m6jf", "created": "2025-08-29T19:03:49.113Z", "currency": "USD", "customer_id": "payload_connector_test", "customer": { "id": "payload_connector_test", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": "man_3mj9Jwv4MwbOlI5CaXlC", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00.000Z", "end_date": "2023-05-21T00:00:00.000Z", "metadata": { "frequency": "13" } } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "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": "CA", "first_name": "john", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "CA", "line3": "Harrison Street", "zip": "94122", "state": "CA", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": [ { "sku": null, "upc": null, "brand": null, "amount": 300, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "description": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "total_amount": null, "commodity_code": null, "unit_of_measure": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null, "unit_discount_amount": null } ], "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://www.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": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "payload_connector_test", "created_at": 1756494229, "expires": 1756497829, "secret": "epk_7500c29e58b2436ba3c2702b7513f04c" }, "manual_retry_allowed": false, "connector_transaction_id": "txn_3euQYszstRDRYhiNjZZu3", "frm_message": null, "metadata": { "order_category": "applepay" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "PL-IW6-K1O-C2J", "payment_link": null, "profile_id": "pro_JprfwhCqYDKEKZwcwHSo", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nXQ68xSyk8uShjAhLx1p", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-29T19:18:49.113Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "109.71.40.0", "user_agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/22F76 [FBAN/FBIOS;FBAV/520.0.0.38.101;FBBV/756351453;FBDV/iPhone14,7;FBMD/iPhone;FBSN/iOS;FBSV/18.5;FBSS/3;FBID/phone;FBLC/fr_FR;FBOP/5;FBRV/760683563;IABMV/1]", "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_channel": null, "payment_method_id": "pm_rFxrI0UIZ4dJuFNW6vrQ", "network_transaction_id": null, "payment_method_status": "active", "updated": "2025-08-29T19:03:50.744Z", "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": "pm_3euQYsyiEXTjoc3LyDvJO", "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details> <details> <summary>DB</summary> <img width="1396" height="705" alt="image" src="https://github.com/user-attachments/assets/5e7eaae8-4113-4eb4-a4df-12c86cced6b8" /> </details> <details> <summary>MIT</summary> ```sh curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_uGs7ayYh5hoENIMQ43lMkQGC2i863OXlIg5XhqxcyfaKjNYcOtUv1YRrUTYuD1WW' \ --data-raw '{ "amount": 499, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "payload_connector_test", "email": "guest@example.com", "off_session": true, "recurring_details": { "type": "mandate_id", "data": "man_3mj9Jwv4MwbOlI5CaXlC" }, "authentication_type": "no_three_ds" }' ``` ```json { "payment_id": "pay_n6Q7mVWZolxL0iEvvWCq", "merchant_id": "postman_merchant_GHAction_1756491108", "status": "succeeded", "amount": 499, "net_amount": 499, "shipping_cost": null, "amount_capturable": 0, "amount_received": 499, "connector": "payload", "client_secret": "pay_n6Q7mVWZolxL0iEvvWCq_secret_2kO6VPJ9ZB2gjKJ5FYY6", "created": "2025-08-29T19:04:16.806Z", "currency": "USD", "customer_id": "payload_connector_test", "customer": { "id": "payload_connector_test", "name": "Joseph Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+65" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "df98d618-af0e-49d7-ba36-fb618248a19c", "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "Joseph 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": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "payload_connector_test", "created_at": 1756494256, "expires": 1756497856, "secret": "epk_868f1a923aa54d42b1fb7413cdffcede" }, "manual_retry_allowed": false, "connector_transaction_id": "txn_3euQYzTsOACXwo57SzYAY", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "PL-1AQ-M6K-KC7", "payment_link": null, "profile_id": "pro_JprfwhCqYDKEKZwcwHSo", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nXQ68xSyk8uShjAhLx1p", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-29T19:19:16.806Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": "pm_rFxrI0UIZ4dJuFNW6vrQ", "network_transaction_id": null, "payment_method_status": "active", "updated": "2025-08-29T19:04:17.696Z", "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": "pm_3euQYsyiEXTjoc3LyDvJO", "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details> Cypress changes: <details> <summary>Images of Cypress CI</summary> <img width="724" height="562" alt="image" src="https://github.com/user-attachments/assets/20120708-0090-4c5b-ae4e-b54ed339498f" /> <img width="562" height="796" alt="image" src="https://github.com/user-attachments/assets/fefd2f7d-37eb-4e18-9df8-c7558cf3dcc7" /> all the 11 failures because of timeouts (even 30 seconds is not enough): <img width="418" height="468" alt="image" src="https://github.com/user-attachments/assets/30e0de84-64fc-44ff-bac1-60947e273273" /> </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 - [x] I added unit tests for my changes where possible <!-- @coderabbitai ignore -->
v1.116.0
8ce36a2fd513034755a1bf1aacbd3210083e07c9
8ce36a2fd513034755a1bf1aacbd3210083e07c9
juspay/hyperswitch
juspay__hyperswitch-9097
Bug: Subscription Create to return client secret and create payment intent automatically
diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index 3b343459e9e..7c48d626f2d 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -42,6 +42,8 @@ pub mod recon; pub mod refunds; pub mod relay; pub mod routing; +#[cfg(feature = "v1")] +pub mod subscription; pub mod surcharge_decision_configs; pub mod three_ds_decision_rule; #[cfg(feature = "tokenization_v2")] diff --git a/crates/api_models/src/subscription.rs b/crates/api_models/src/subscription.rs new file mode 100644 index 00000000000..7dff21205a2 --- /dev/null +++ b/crates/api_models/src/subscription.rs @@ -0,0 +1,109 @@ +use common_utils::events::ApiEventMetric; +use masking::Secret; +use utoipa::ToSchema; + +// use crate::{ +// customers::{CustomerRequest, CustomerResponse}, +// payments::CustomerDetailsResponse, +// }; + +/// Request payload for creating a subscription. +/// +/// This struct captures details required to create a subscription, +/// including plan, profile, merchant connector, and optional customer info. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct CreateSubscriptionRequest { + /// Merchant specific Unique identifier. + pub merchant_reference_id: Option<String>, + + /// Identifier for the subscription plan. + pub plan_id: Option<String>, + + /// Optional coupon code applied to the subscription. + pub coupon_code: Option<String>, + + /// customer ID associated with this subscription. + pub customer_id: common_utils::id_type::CustomerId, +} + +/// Response payload returned after successfully creating a subscription. +/// +/// Includes details such as subscription ID, status, plan, merchant, and customer info. +#[derive(Debug, Clone, serde::Serialize, ToSchema)] +pub struct CreateSubscriptionResponse { + /// Unique identifier for the subscription. + pub id: common_utils::id_type::SubscriptionId, + + /// Merchant specific Unique identifier. + pub merchant_reference_id: Option<String>, + + /// Current status of the subscription. + pub status: SubscriptionStatus, + + /// Identifier for the associated subscription plan. + pub plan_id: Option<String>, + + /// Associated profile ID. + pub profile_id: common_utils::id_type::ProfileId, + + /// Optional client secret used for secure client-side interactions. + pub client_secret: Option<Secret<String>>, + + /// Merchant identifier owning this subscription. + pub merchant_id: common_utils::id_type::MerchantId, + + /// Optional coupon code applied to this subscription. + pub coupon_code: Option<String>, + + /// Optional customer ID associated with this subscription. + pub customer_id: common_utils::id_type::CustomerId, +} + +/// Possible states of a subscription lifecycle. +/// +/// - `Created`: Subscription was created but not yet activated. +/// - `Active`: Subscription is currently active. +/// - `InActive`: Subscription is inactive (e.g., cancelled or expired). +#[derive(Debug, Clone, serde::Serialize, strum::EnumString, strum::Display, ToSchema)] +pub enum SubscriptionStatus { + /// Subscription is active. + Active, + /// Subscription is created but not yet active. + Created, + /// Subscription is inactive. + InActive, + /// Subscription is in pending state. + Pending, +} + +impl CreateSubscriptionResponse { + /// Creates a new [`CreateSubscriptionResponse`] with the given identifiers. + /// + /// By default, `client_secret`, `coupon_code`, and `customer` fields are `None`. + #[allow(clippy::too_many_arguments)] + pub fn new( + id: common_utils::id_type::SubscriptionId, + merchant_reference_id: Option<String>, + status: SubscriptionStatus, + plan_id: Option<String>, + profile_id: common_utils::id_type::ProfileId, + merchant_id: common_utils::id_type::MerchantId, + client_secret: Option<Secret<String>>, + customer_id: common_utils::id_type::CustomerId, + ) -> Self { + Self { + id, + merchant_reference_id, + status, + plan_id, + profile_id, + client_secret, + merchant_id, + coupon_code: None, + customer_id, + } + } +} + +impl ApiEventMetric for CreateSubscriptionResponse {} +impl ApiEventMetric for CreateSubscriptionRequest {} diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index bbb1be10b80..03ceab3f9a2 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -8412,6 +8412,7 @@ pub enum Resource { RunRecon, ReconConfig, RevenueRecovery, + Subscription, InternalConnector, Theme, } diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index 49be22fc931..dc8f6e333a4 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -85,6 +85,7 @@ pub enum ApiEventsType { payment_id: Option<id_type::GlobalPaymentId>, }, Routing, + Subscription, ResourceListAPI, #[cfg(feature = "v1")] PaymentRedirectionResponse { diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs index 6d73a90eab2..237ca661c10 100644 --- a/crates/common_utils/src/id_type.rs +++ b/crates/common_utils/src/id_type.rs @@ -17,6 +17,7 @@ mod profile_acquirer; mod refunds; mod relay; mod routing; +mod subscription; mod tenant; use std::{borrow::Cow, fmt::Debug}; @@ -55,6 +56,7 @@ pub use self::{ refunds::RefundReferenceId, relay::RelayId, routing::RoutingId, + subscription::SubscriptionId, tenant::TenantId, }; use crate::{fp_utils::when, generate_id_with_default_len}; diff --git a/crates/common_utils/src/id_type/subscription.rs b/crates/common_utils/src/id_type/subscription.rs new file mode 100644 index 00000000000..20f0c483fa1 --- /dev/null +++ b/crates/common_utils/src/id_type/subscription.rs @@ -0,0 +1,21 @@ +crate::id_type!( + SubscriptionId, + " A type for subscription_id that can be used for subscription ids" +); + +crate::impl_id_type_methods!(SubscriptionId, "subscription_id"); + +// This is to display the `SubscriptionId` as SubscriptionId(subs) +crate::impl_debug_id_type!(SubscriptionId); +crate::impl_try_from_cow_str_id_type!(SubscriptionId, "subscription_id"); + +crate::impl_generate_id_id_type!(SubscriptionId, "subscription"); +crate::impl_serializable_secret_id_type!(SubscriptionId); +crate::impl_queryable_id_type!(SubscriptionId); +crate::impl_to_sql_from_sql_id_type!(SubscriptionId); + +impl crate::events::ApiEventMetric for SubscriptionId { + fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { + Some(crate::events::ApiEventsType::Subscription) + } +} diff --git a/crates/diesel_models/src/query/subscription.rs b/crates/diesel_models/src/query/subscription.rs index e25f1617873..7a6bdd19c15 100644 --- a/crates/diesel_models/src/query/subscription.rs +++ b/crates/diesel_models/src/query/subscription.rs @@ -19,13 +19,13 @@ impl Subscription { pub async fn find_by_merchant_id_subscription_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, - subscription_id: String, + id: String, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) - .and(dsl::subscription_id.eq(subscription_id.to_owned())), + .and(dsl::id.eq(id.to_owned())), ) .await } @@ -33,7 +33,7 @@ impl Subscription { pub async fn update_subscription_entry( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, - subscription_id: String, + id: String, subscription_update: SubscriptionUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::< @@ -43,8 +43,8 @@ impl Subscription { _, >( conn, - dsl::subscription_id - .eq(subscription_id.to_owned()) + dsl::id + .eq(id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())), subscription_update, ) diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 271d2a79ba0..c02a9748f81 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1530,9 +1530,9 @@ diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; - subscription (subscription_id, merchant_id) { + subscription (id) { #[max_length = 128] - subscription_id -> Varchar, + id -> Varchar, #[max_length = 128] status -> Varchar, #[max_length = 128] @@ -1554,6 +1554,8 @@ diesel::table! { modified_at -> Timestamp, #[max_length = 64] profile_id -> Varchar, + #[max_length = 128] + merchant_reference_id -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 4195475f88d..4648eed49f7 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1465,9 +1465,9 @@ diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; - subscription (subscription_id, merchant_id) { + subscription (id) { #[max_length = 128] - subscription_id -> Varchar, + id -> Varchar, #[max_length = 128] status -> Varchar, #[max_length = 128] @@ -1489,6 +1489,8 @@ diesel::table! { modified_at -> Timestamp, #[max_length = 64] profile_id -> Varchar, + #[max_length = 128] + merchant_reference_id -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/subscription.rs b/crates/diesel_models/src/subscription.rs index b2cb6e48470..f49fef4a7be 100644 --- a/crates/diesel_models/src/subscription.rs +++ b/crates/diesel_models/src/subscription.rs @@ -1,5 +1,6 @@ -use common_utils::pii::SecretSerdeValue; +use common_utils::{generate_id_with_default_len, pii::SecretSerdeValue}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; +use masking::Secret; use serde::{Deserialize, Serialize}; use crate::schema::subscription; @@ -7,7 +8,7 @@ use crate::schema::subscription; #[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] #[diesel(table_name = subscription)] pub struct SubscriptionNew { - subscription_id: String, + id: common_utils::id_type::SubscriptionId, status: String, billing_processor: Option<String>, payment_method_id: Option<String>, @@ -20,14 +21,15 @@ pub struct SubscriptionNew { created_at: time::PrimitiveDateTime, modified_at: time::PrimitiveDateTime, profile_id: common_utils::id_type::ProfileId, + merchant_reference_id: Option<String>, } #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize, )] -#[diesel(table_name = subscription, primary_key(subscription_id, merchant_id), check_for_backend(diesel::pg::Pg))] +#[diesel(table_name = subscription, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct Subscription { - pub subscription_id: String, + pub id: common_utils::id_type::SubscriptionId, pub status: String, pub billing_processor: Option<String>, pub payment_method_id: Option<String>, @@ -40,6 +42,7 @@ pub struct Subscription { pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub profile_id: common_utils::id_type::ProfileId, + pub merchant_reference_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, AsChangeset, router_derive::DebugAsDisplay, Deserialize)] @@ -53,7 +56,7 @@ pub struct SubscriptionUpdate { impl SubscriptionNew { #[allow(clippy::too_many_arguments)] pub fn new( - subscription_id: String, + id: common_utils::id_type::SubscriptionId, status: String, billing_processor: Option<String>, payment_method_id: Option<String>, @@ -64,10 +67,11 @@ impl SubscriptionNew { customer_id: common_utils::id_type::CustomerId, metadata: Option<SecretSerdeValue>, profile_id: common_utils::id_type::ProfileId, + merchant_reference_id: Option<String>, ) -> Self { let now = common_utils::date_time::now(); Self { - subscription_id, + id, status, billing_processor, payment_method_id, @@ -80,8 +84,16 @@ impl SubscriptionNew { created_at: now, modified_at: now, profile_id, + merchant_reference_id, } } + + pub fn generate_and_set_client_secret(&mut self) -> Secret<String> { + let client_secret = + generate_id_with_default_len(&format!("{}_secret", self.id.get_string_repr())); + self.client_secret = Some(client_secret.clone()); + Secret::new(client_secret) + } } impl SubscriptionUpdate { diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index f7cb256f587..e6c13f5344f 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -51,6 +51,8 @@ pub mod refunds_v2; #[cfg(feature = "v1")] pub mod debit_routing; pub mod routing; +#[cfg(feature = "v1")] +pub mod subscription; pub mod surcharge_decision_config; pub mod three_ds_decision_rule; #[cfg(feature = "olap")] diff --git a/crates/router/src/core/subscription.rs b/crates/router/src/core/subscription.rs new file mode 100644 index 00000000000..32c6754e2fe --- /dev/null +++ b/crates/router/src/core/subscription.rs @@ -0,0 +1,65 @@ +use std::str::FromStr; + +use api_models::subscription::{ + self as subscription_types, CreateSubscriptionResponse, SubscriptionStatus, +}; +use common_utils::id_type::GenerateId; +use diesel_models::subscription::SubscriptionNew; +use error_stack::ResultExt; +use hyperswitch_domain_models::{api::ApplicationResponse, merchant_context::MerchantContext}; +use masking::Secret; + +use super::errors::{self, RouterResponse}; +use crate::routes::SessionState; + +pub async fn create_subscription( + state: SessionState, + merchant_context: MerchantContext, + profile_id: String, + request: subscription_types::CreateSubscriptionRequest, +) -> RouterResponse<CreateSubscriptionResponse> { + let store = state.store.clone(); + let db = store.as_ref(); + let id = common_utils::id_type::SubscriptionId::generate(); + let profile_id = common_utils::id_type::ProfileId::from_str(&profile_id).change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "X-Profile-Id", + }, + )?; + + let mut subscription = SubscriptionNew::new( + id, + SubscriptionStatus::Created.to_string(), + None, + None, + None, + None, + None, + merchant_context.get_merchant_account().get_id().clone(), + request.customer_id.clone(), + None, + profile_id, + request.merchant_reference_id, + ); + + subscription.generate_and_set_client_secret(); + let subscription_response = db + .insert_subscription_entry(subscription) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("subscriptions: unable to insert subscription entry to database")?; + + let response = CreateSubscriptionResponse::new( + subscription_response.id.clone(), + subscription_response.merchant_reference_id, + SubscriptionStatus::from_str(&subscription_response.status) + .unwrap_or(SubscriptionStatus::Created), + None, + subscription_response.profile_id, + subscription_response.merchant_id, + subscription_response.client_secret.map(Secret::new), + request.customer_id, + ); + + Ok(ApplicationResponse::Json(response)) +} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index d92dc311e0c..fd9c7f8a0a5 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -211,6 +211,7 @@ pub fn mk_app( .service(routes::Files::server(state.clone())) .service(routes::Disputes::server(state.clone())) .service(routes::Blocklist::server(state.clone())) + .service(routes::Subscription::server(state.clone())) .service(routes::Gsm::server(state.clone())) .service(routes::ApplePayCertificatesMigration::server(state.clone())) .service(routes::PaymentLink::server(state.clone())) diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index b8fde79e2a1..f2af4631917 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -50,6 +50,8 @@ pub mod recon; pub mod refunds; #[cfg(feature = "olap")] pub mod routing; +#[cfg(feature = "v1")] +pub mod subscription; pub mod three_ds_decision_rule; pub mod tokenization; #[cfg(feature = "olap")] @@ -96,7 +98,7 @@ pub use self::app::{ User, UserDeprecated, Webhooks, }; #[cfg(feature = "olap")] -pub use self::app::{Blocklist, Organization, Routing, Verify, WebhookEvents}; +pub use self::app::{Blocklist, Organization, Routing, Subscription, Verify, WebhookEvents}; #[cfg(feature = "payouts")] pub use self::app::{PayoutLink, Payouts}; #[cfg(all(feature = "stripe", feature = "v1"))] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index d52dc1570ce..1cdc2479364 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -65,7 +65,9 @@ use super::{ profiles, relay, user, user_role, }; #[cfg(feature = "v1")] -use super::{apple_pay_certificates_migration, blocklist, payment_link, webhook_events}; +use super::{ + apple_pay_certificates_migration, blocklist, payment_link, subscription, webhook_events, +}; #[cfg(any(feature = "olap", feature = "oltp"))] use super::{configs::*, customers, payments}; #[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v1"))] @@ -1163,6 +1165,22 @@ impl Routing { } } +#[cfg(feature = "oltp")] +pub struct Subscription; + +#[cfg(all(feature = "oltp", feature = "v1"))] +impl Subscription { + pub fn server(state: AppState) -> Scope { + web::scope("/subscription/create") + .app_data(web::Data::new(state.clone())) + .service(web::resource("").route( + web::post().to(|state, req, payload| { + subscription::create_subscription(state, req, payload) + }), + )) + } +} + pub struct Customers; #[cfg(all(feature = "v2", any(feature = "olap", feature = "oltp")))] diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 28581198d83..8bbddaedc8e 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -26,6 +26,7 @@ pub enum ApiIdentifier { ApiKeys, PaymentLink, Routing, + Subscription, Blocklist, Forex, RustLockerMigration, @@ -88,6 +89,8 @@ impl From<Flow> for ApiIdentifier { | Flow::DecisionEngineDecideGatewayCall | Flow::DecisionEngineGatewayFeedbackCall => Self::Routing, + Flow::CreateSubscription => Self::Subscription, + Flow::RetrieveForexFlow => Self::Forex, Flow::AddToBlocklist => Self::Blocklist, diff --git a/crates/router/src/routes/subscription.rs b/crates/router/src/routes/subscription.rs new file mode 100644 index 00000000000..d4b716f63c0 --- /dev/null +++ b/crates/router/src/routes/subscription.rs @@ -0,0 +1,69 @@ +//! Analysis for usage of Subscription in Payment flows +//! +//! Functions that are used to perform the api level configuration and retrieval +//! of various types under Subscriptions. + +use actix_web::{web, HttpRequest, HttpResponse, Responder}; +use api_models::subscription as subscription_types; +use hyperswitch_domain_models::errors; +use router_env::{ + tracing::{self, instrument}, + Flow, +}; + +use crate::{ + core::{api_locking, subscription}, + headers::X_PROFILE_ID, + routes::AppState, + services::{api as oss_api, authentication as auth, authorization::permissions::Permission}, + types::domain, +}; + +#[cfg(all(feature = "oltp", feature = "v1"))] +#[instrument(skip_all)] +pub async fn create_subscription( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<subscription_types::CreateSubscriptionRequest>, +) -> impl Responder { + let flow = Flow::CreateSubscription; + let profile_id = match req.headers().get(X_PROFILE_ID) { + Some(val) => val.to_str().unwrap_or_default().to_string(), + None => { + return HttpResponse::BadRequest().json( + errors::api_error_response::ApiErrorResponse::MissingRequiredField { + field_name: "x-profile-id", + }, + ); + } + }; + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + move |state, auth: auth::AuthenticationData, payload, _| { + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( + domain::Context(auth.merchant_account, auth.key_store), + )); + subscription::create_subscription( + state, + merchant_context, + profile_id.clone(), + payload.clone(), + ) + }, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }), + &auth::JWTAuth { + permission: Permission::ProfileSubscriptionWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index 3860d343b68..6fb4b09cd5d 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -43,6 +43,10 @@ generate_permissions! { scopes: [Read, Write], entities: [Profile, Merchant] }, + Subscription: { + scopes: [Read, Write], + entities: [Profile, Merchant] + }, ThreeDsDecisionManager: { scopes: [Read, Write], entities: [Merchant, Profile] @@ -123,6 +127,7 @@ pub fn get_resource_name(resource: Resource, entity_type: EntityType) -> Option< Some("Payment Processors, Payout Processors, Fraud & Risk Managers") } (Resource::Routing, _) => Some("Routing"), + (Resource::Subscription, _) => Some("Subscription"), (Resource::RevenueRecovery, _) => Some("Revenue Recovery"), (Resource::ThreeDsDecisionManager, _) => Some("3DS Decision Manager"), (Resource::SurchargeDecisionManager, _) => Some("Surcharge Decision Manager"), diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index f5359d84010..fad87204cee 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -263,6 +263,8 @@ pub enum Flow { RoutingUpdateDefaultConfig, /// Routing delete config RoutingDeleteConfig, + /// Subscription create flow, + CreateSubscription, /// Create dynamic routing CreateDynamicRoutingConfig, /// Toggle dynamic routing diff --git a/migrations/2025-09-17-165505_update_subscription_table_with_merchant_ref_id/down.sql b/migrations/2025-09-17-165505_update_subscription_table_with_merchant_ref_id/down.sql new file mode 100644 index 00000000000..cc002a5e7e6 --- /dev/null +++ b/migrations/2025-09-17-165505_update_subscription_table_with_merchant_ref_id/down.sql @@ -0,0 +1,9 @@ +ALTER TABLE subscription + DROP CONSTRAINT subscription_pkey, + DROP COLUMN merchant_reference_id; + +ALTER TABLE subscription + RENAME COLUMN id TO subscription_id; + +ALTER TABLE subscription + ADD PRIMARY KEY (subscription_id, merchant_id); diff --git a/migrations/2025-09-17-165505_update_subscription_table_with_merchant_ref_id/up.sql b/migrations/2025-09-17-165505_update_subscription_table_with_merchant_ref_id/up.sql new file mode 100644 index 00000000000..1d454442b81 --- /dev/null +++ b/migrations/2025-09-17-165505_update_subscription_table_with_merchant_ref_id/up.sql @@ -0,0 +1,9 @@ +ALTER TABLE subscription + DROP CONSTRAINT subscription_pkey, + ADD COLUMN merchant_reference_id VARCHAR(128); + +ALTER TABLE subscription + RENAME COLUMN subscription_id TO id; + +ALTER TABLE subscription + ADD PRIMARY KEY (id);
2025-08-31T23:26:42Z
## Summary Add **Subscriptions API (v1/OLAP)** entrypoint to create a _subscription intent_ and optionally create/attach a customer, returning a `client_secret` and basic subscription payload. - New route: `POST /subscription/create` (behind `olap` + `v1`) - Creates a `subscription` row (using existing table) and generates a `client_secret` - Optionally **gets or creates** a `Customer` from inline `customer` payload or `customer_id` - Persists optional `mca_id` on the subscription row (used later for connector selection) - Returns a typed `CreateSubscriptionResponse` with `subscription`, `client_secret`, `merchant_id`, `mca_id`, and optional `customer`, `invoice` (placeholder) ## Endpoints ### Create Subscription Intent `POST /subscription/create` **Auth** - API key (HeaderAuth) + JWT (`Permission::ProfileRoutingWrite`) **Request Body** ```json { "customer_id": "{{customer_id}}" } ``` **Behavior** - Generates `sub_<random>` for subscription row id - If `customer_id` provided β†’ fetch; else if `customer` has any PII fields β†’ **create customer** (encrypting PII); else β†’ `400 CustomerNotFound` - Persists subscription with: - `id` - `subscription_id` = `null` (placeholder, to be set later) - `mca_id` (if provided) - `client_secret` = generated via `SubscriptionNew::generate_client_secret()` - `merchant_id`, `customer_id` - `billing_processor`, `payment_method_id`, `metadata` = `null` (placeholders) - Returns `200` with response below **Success Response** ```json { "id": "subscription_f8Ng47rKaB296XHolKKG", "merchant_reference_id": null, "status": "Created", "plan_id": null, "profile_id": "pro_UjmcM35TVpYh9Zb3LaZV", "client_secret": "subscription_f8Ng47rKaB296XHolKKG_secret_0fz5A3aa4NTcdiQF5W7i", "merchant_id": "merchant_1758146582", "coupon_code": null, "customer_id": "cus_jtJ8WHTHnsguskpiorEt" } ``` --- ## Implementation Notes - **Core** - `crates/router/src/core/subscription.rs` – service handler - `crates/router/src/core/subscription/utils.rs` – helpers, request/response types - **Routing** - `crates/router/src/routes/subscription.rs` – web handler (`/subscription/create`) - `crates/router/src/routes/app.rs` – `Subscription::server()` scope under `/subscription` - `crates/router/src/lib.rs` – wire route - **Domain / DTO** - `hyperswitch_domain_models::router_request_types::CustomerDetails` now `Serialize`/`Deserialize` - `hyperswitch_domain_models::customer::Customer` derives `Serialize` (v1) - **Storage** - Uses existing `subscription` table and `SubscriptionNew::generate_client_secret()` - No new migrations introduced in this PR - **Customer flow** - If not found, creates via encrypted batch operation; respects merchant key store and storage scheme --- ## Testing ``` curl --location 'http://localhost:8080/subscription/create' \ --header 'Content-Type: application/json' \ --header 'X-Profile-Id: pro_UjmcM35TVpYh9Zb3LaZV' \ --header 'api-key: dev_pPBMnOEL5SJnMfxxp2bh4du87ESZoMJNtUmn3oIS8kpCNfUJAZ2a8F832n1je5zQ' \ --data '{ "customer_id": "cus_jtJ8WHTHnsguskpiorEt" }' ``` Response: ``` { "id": "subscription_f8Ng47rKaB296XHolKKG", "merchant_reference_id": null, "status": "Created", "plan_id": null, "profile_id": "pro_UjmcM35TVpYh9Zb3LaZV", "client_secret": "subscription_f8Ng47rKaB296XHolKKG_secret_0fz5A3aa4NTcdiQF5W7i", "merchant_id": "merchant_1758146582", "coupon_code": null, "customer_id": "cus_jtJ8WHTHnsguskpiorEt" } ``` ---
v1.117.0
85bc733d5b03df4cda4d2a03aa8362a4fd1b14d9
85bc733d5b03df4cda4d2a03aa8362a4fd1b14d9
juspay/hyperswitch
juspay__hyperswitch-9099
Bug: Subscription confirm API
diff --git a/crates/api_models/src/subscription.rs b/crates/api_models/src/subscription.rs index 7dff21205a2..4ed14a9c64e 100644 --- a/crates/api_models/src/subscription.rs +++ b/crates/api_models/src/subscription.rs @@ -1,7 +1,13 @@ -use common_utils::events::ApiEventMetric; +use common_types::payments::CustomerAcceptance; +use common_utils::{errors::ValidationError, events::ApiEventMetric, types::MinorUnit}; use masking::Secret; use utoipa::ToSchema; +use crate::{ + enums as api_enums, + payments::{Address, PaymentMethodDataRequest}, +}; + // use crate::{ // customers::{CustomerRequest, CustomerResponse}, // payments::CustomerDetailsResponse, @@ -63,7 +69,14 @@ pub struct CreateSubscriptionResponse { /// /// - `Created`: Subscription was created but not yet activated. /// - `Active`: Subscription is currently active. -/// - `InActive`: Subscription is inactive (e.g., cancelled or expired). +/// - `InActive`: Subscription is inactive. +/// - `Pending`: Subscription is pending activation. +/// - `Trial`: Subscription is in a trial period. +/// - `Paused`: Subscription is paused. +/// - `Unpaid`: Subscription is unpaid. +/// - `Onetime`: Subscription is a one-time payment. +/// - `Cancelled`: Subscription has been cancelled. +/// - `Failed`: Subscription has failed. #[derive(Debug, Clone, serde::Serialize, strum::EnumString, strum::Display, ToSchema)] pub enum SubscriptionStatus { /// Subscription is active. @@ -74,6 +87,18 @@ pub enum SubscriptionStatus { InActive, /// Subscription is in pending state. Pending, + /// Subscription is in trial state. + Trial, + /// Subscription is paused. + Paused, + /// Subscription is unpaid. + Unpaid, + /// Subscription is a one-time payment. + Onetime, + /// Subscription is cancelled. + Cancelled, + /// Subscription has failed. + Failed, } impl CreateSubscriptionResponse { @@ -107,3 +132,141 @@ impl CreateSubscriptionResponse { impl ApiEventMetric for CreateSubscriptionResponse {} impl ApiEventMetric for CreateSubscriptionRequest {} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct PaymentDetails { + pub payment_method: api_enums::PaymentMethod, + pub payment_method_type: Option<api_enums::PaymentMethodType>, + pub payment_method_data: PaymentMethodDataRequest, + pub setup_future_usage: Option<api_enums::FutureUsage>, + pub customer_acceptance: Option<CustomerAcceptance>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct PaymentResponseData { + pub payment_id: common_utils::id_type::PaymentId, + pub status: api_enums::IntentStatus, + pub amount: MinorUnit, + pub currency: api_enums::Currency, + pub connector: Option<String>, +} +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct ConfirmSubscriptionRequest { + /// Client secret for SDK based interaction. + pub client_secret: Option<String>, + + /// Amount to be charged for the invoice. + pub amount: MinorUnit, + + /// Currency for the amount. + pub currency: api_enums::Currency, + + /// Identifier for the associated plan_id. + pub plan_id: Option<String>, + + /// Identifier for the associated item_price_id for the subscription. + pub item_price_id: Option<String>, + + /// Idenctifier for the coupon code for the subscription. + pub coupon_code: Option<String>, + + /// Identifier for customer. + pub customer_id: common_utils::id_type::CustomerId, + + /// Billing address for the subscription. + pub billing_address: Option<Address>, + + /// Payment details for the invoice. + pub payment_details: PaymentDetails, +} + +impl ConfirmSubscriptionRequest { + pub fn get_item_price_id(&self) -> Result<String, error_stack::Report<ValidationError>> { + self.item_price_id.clone().ok_or(error_stack::report!( + ValidationError::MissingRequiredField { + field_name: "item_price_id".to_string() + } + )) + } + + pub fn get_billing_address(&self) -> Result<Address, error_stack::Report<ValidationError>> { + self.billing_address.clone().ok_or(error_stack::report!( + ValidationError::MissingRequiredField { + field_name: "billing_address".to_string() + } + )) + } +} + +impl ApiEventMetric for ConfirmSubscriptionRequest {} + +#[derive(Debug, Clone, serde::Serialize, ToSchema)] +pub struct ConfirmSubscriptionResponse { + /// Unique identifier for the subscription. + pub id: common_utils::id_type::SubscriptionId, + + /// Merchant specific Unique identifier. + pub merchant_reference_id: Option<String>, + + /// Current status of the subscription. + pub status: SubscriptionStatus, + + /// Identifier for the associated subscription plan. + pub plan_id: Option<String>, + + /// Identifier for the associated item_price_id for the subscription. + pub price_id: Option<String>, + + /// Optional coupon code applied to this subscription. + pub coupon: Option<String>, + + /// Associated profile ID. + pub profile_id: common_utils::id_type::ProfileId, + + /// Payment details for the invoice. + pub payment: Option<PaymentResponseData>, + + /// Customer ID associated with this subscription. + pub customer_id: Option<common_utils::id_type::CustomerId>, + + /// Invoice Details for the subscription. + pub invoice: Option<Invoice>, +} + +#[derive(Debug, Clone, serde::Serialize, ToSchema)] +pub struct Invoice { + /// Unique identifier for the invoice. + pub id: common_utils::id_type::InvoiceId, + + /// Unique identifier for the subscription. + pub subscription_id: common_utils::id_type::SubscriptionId, + + /// Identifier for the merchant. + pub merchant_id: common_utils::id_type::MerchantId, + + /// Identifier for the profile. + pub profile_id: common_utils::id_type::ProfileId, + + /// Identifier for the merchant connector account. + pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, + + /// Identifier for the Payment. + pub payment_intent_id: Option<common_utils::id_type::PaymentId>, + + /// Identifier for the Payment method. + pub payment_method_id: Option<String>, + + /// Identifier for the Customer. + pub customer_id: common_utils::id_type::CustomerId, + + /// Invoice amount. + pub amount: MinorUnit, + + /// Currency for the invoice payment. + pub currency: api_enums::Currency, + + /// Status of the invoice. + pub status: String, +} + +impl ApiEventMetric for ConfirmSubscriptionResponse {} diff --git a/crates/diesel_models/src/invoice.rs b/crates/diesel_models/src/invoice.rs index 57024d0730a..8ffd54c288d 100644 --- a/crates/diesel_models/src/invoice.rs +++ b/crates/diesel_models/src/invoice.rs @@ -34,21 +34,21 @@ pub struct InvoiceNew { check_for_backend(diesel::pg::Pg) )] pub struct Invoice { - id: common_utils::id_type::InvoiceId, - subscription_id: common_utils::id_type::SubscriptionId, - merchant_id: common_utils::id_type::MerchantId, - profile_id: common_utils::id_type::ProfileId, - merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, - payment_intent_id: Option<common_utils::id_type::PaymentId>, - payment_method_id: Option<String>, - customer_id: common_utils::id_type::CustomerId, - amount: MinorUnit, - currency: String, - status: String, - provider_name: Connector, - metadata: Option<SecretSerdeValue>, - created_at: time::PrimitiveDateTime, - modified_at: time::PrimitiveDateTime, + pub id: common_utils::id_type::InvoiceId, + pub subscription_id: common_utils::id_type::SubscriptionId, + pub merchant_id: common_utils::id_type::MerchantId, + pub profile_id: common_utils::id_type::ProfileId, + pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, + pub payment_intent_id: Option<common_utils::id_type::PaymentId>, + pub payment_method_id: Option<String>, + pub customer_id: common_utils::id_type::CustomerId, + pub amount: MinorUnit, + pub currency: String, + pub status: String, + pub provider_name: Connector, + pub metadata: Option<SecretSerdeValue>, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, } #[derive(Clone, Debug, Eq, PartialEq, AsChangeset, Deserialize)] diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee.rs b/crates/hyperswitch_connectors/src/connectors/chargebee.rs index b761dc9ebbf..167c2a337ba 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee.rs @@ -16,7 +16,7 @@ use error_stack::ResultExt; use hyperswitch_domain_models::{revenue_recovery, router_data_v2::RouterDataV2}; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, - router_data_v2::flow_common_types::SubscriptionCreateData, + router_data_v2::flow_common_types::{SubscriptionCreateData, SubscriptionCustomerData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, @@ -131,13 +131,28 @@ impl ConnectorIntegration<SubscriptionCreate, SubscriptionCreateRequest, Subscri ) -> CustomResult<String, errors::ConnectorError> { let metadata: chargebee::ChargebeeMetadata = utils::to_connector_meta_from_secret(req.connector_meta_data.clone())?; - let url = self - .base_url(connectors) - .to_string() - .replace("{{merchant_endpoint_prefix}}", metadata.site.peek()); + + let site = metadata.site.peek(); + + let mut base = self.base_url(connectors).to_string(); + + base = base.replace("{{merchant_endpoint_prefix}}", site); + base = base.replace("$", site); + + if base.contains("{{merchant_endpoint_prefix}}") || base.contains('$') { + return Err(errors::ConnectorError::InvalidConnectorConfig { + config: "Chargebee base_url has an unresolved placeholder (expected `$` or `{{merchant_endpoint_prefix}}`).", + } + .into()); + } + + if !base.ends_with('/') { + base.push('/'); + } + let customer_id = &req.request.customer_id.get_string_repr().to_string(); Ok(format!( - "{url}v2/customers/{customer_id}/subscription_for_items" + "{base}v2/customers/{customer_id}/subscription_for_items" )) } @@ -217,6 +232,17 @@ impl // Not Implemented (R) } +impl + ConnectorIntegrationV2< + CreateConnectorCustomer, + SubscriptionCustomerData, + ConnectorCustomerData, + PaymentsResponseData, + > for Chargebee +{ + // Not Implemented (R) +} + impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Chargebee { diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index 572cb082a45..953dfdca788 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -1039,7 +1039,20 @@ pub struct ChargebeeCustomerCreateRequest { #[serde(rename = "first_name")] pub name: Option<Secret<String>>, pub email: Option<Email>, - pub billing_address: Option<api_models::payments::AddressDetails>, + #[serde(rename = "billing_address[first_name]")] + pub billing_address_first_name: Option<Secret<String>>, + #[serde(rename = "billing_address[last_name]")] + pub billing_address_last_name: Option<Secret<String>>, + #[serde(rename = "billing_address[line1]")] + pub billing_address_line1: Option<Secret<String>>, + #[serde(rename = "billing_address[city]")] + pub billing_address_city: Option<String>, + #[serde(rename = "billing_address[state]")] + pub billing_address_state: Option<Secret<String>>, + #[serde(rename = "billing_address[zip]")] + pub billing_address_zip: Option<Secret<String>>, + #[serde(rename = "billing_address[country]")] + pub billing_address_country: Option<String>, } impl TryFrom<&ChargebeeRouterData<&hyperswitch_domain_models::types::ConnectorCustomerRouterData>> @@ -1062,7 +1075,34 @@ impl TryFrom<&ChargebeeRouterData<&hyperswitch_domain_models::types::ConnectorCu .clone(), name: req.name.clone(), email: req.email.clone(), - billing_address: req.billing_address.clone(), + billing_address_first_name: req + .billing_address + .as_ref() + .and_then(|address| address.first_name.clone()), + billing_address_last_name: req + .billing_address + .as_ref() + .and_then(|address| address.last_name.clone()), + billing_address_line1: req + .billing_address + .as_ref() + .and_then(|addr| addr.line1.clone()), + billing_address_city: req + .billing_address + .as_ref() + .and_then(|addr| addr.city.clone()), + billing_address_country: req + .billing_address + .as_ref() + .and_then(|addr| addr.country.map(|country| country.to_string())), + billing_address_state: req + .billing_address + .as_ref() + .and_then(|addr| addr.state.clone()), + billing_address_zip: req + .billing_address + .as_ref() + .and_then(|addr| addr.zip.clone()), }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/recurly.rs b/crates/hyperswitch_connectors/src/connectors/recurly.rs index 738a7026c8d..bfa9a50a99a 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly.rs @@ -12,7 +12,7 @@ use hyperswitch_domain_models::{ router_data_v2::{ flow_common_types::{ GetSubscriptionEstimateData, GetSubscriptionPlanPricesData, GetSubscriptionPlansData, - SubscriptionCreateData, + SubscriptionCreateData, SubscriptionCustomerData, }, UasFlowData, }, @@ -24,6 +24,7 @@ use hyperswitch_domain_models::{ unified_authentication_service::{ Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, }, + CreateConnectorCustomer, }, router_request_types::{ subscriptions::{ @@ -35,10 +36,14 @@ use hyperswitch_domain_models::{ UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, + ConnectorCustomerData, }, - router_response_types::subscriptions::{ - GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, - GetSubscriptionPlansResponse, SubscriptionCreateResponse, + router_response_types::{ + subscriptions::{ + GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, + GetSubscriptionPlansResponse, SubscriptionCreateResponse, + }, + PaymentsResponseData, }, }; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] @@ -156,6 +161,7 @@ impl impl api::revenue_recovery_v2::RevenueRecoveryV2 for Recurly {} impl api::subscriptions_v2::SubscriptionsV2 for Recurly {} impl api::subscriptions_v2::GetSubscriptionPlansV2 for Recurly {} +impl api::subscriptions_v2::SubscriptionConnectorCustomerV2 for Recurly {} impl ConnectorIntegrationV2< @@ -167,6 +173,16 @@ impl { } +impl + ConnectorIntegrationV2< + CreateConnectorCustomer, + SubscriptionCustomerData, + ConnectorCustomerData, + PaymentsResponseData, + > for Recurly +{ +} + impl api::subscriptions_v2::GetSubscriptionPlanPricesV2 for Recurly {} impl diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index 095e2a392c5..42c2398582c 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -1547,6 +1547,21 @@ impl Profile { Cow::Borrowed(common_types::consts::DEFAULT_PAYOUT_WEBHOOK_TRIGGER_STATUSES) }) } + + pub fn get_billing_processor_id( + &self, + ) -> CustomResult< + common_utils::id_type::MerchantConnectorAccountId, + api_error_response::ApiErrorResponse, + > { + self.billing_processor_id + .to_owned() + .ok_or(error_stack::report!( + api_error_response::ApiErrorResponse::MissingRequiredField { + field_name: "billing_processor_id" + } + )) + } } #[cfg(feature = "v2")] 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 830b90fc763..f096ba78632 100644 --- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs +++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs @@ -321,6 +321,8 @@ pub enum ApiErrorResponse { }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Tokenization record not found for the given token_id {id}")] TokenizationRecordNotFound { id: String }, + #[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "Subscription operation: {operation} failed with connector")] + SubscriptionError { operation: String }, } #[derive(Clone)] @@ -710,6 +712,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon Self::TokenizationRecordNotFound{ id } => { AER::NotFound(ApiError::new("HE", 2, format!("Tokenization record not found for the given token_id '{id}' "), None)) } + Self::SubscriptionError { operation } => { + AER::BadRequest(ApiError::new("CE", 9, format!("Subscription operation: {operation} failed with connector"), None)) + } } } } diff --git a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs index 40be24722a5..245d57064b9 100644 --- a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs +++ b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs @@ -151,13 +151,24 @@ pub struct FilesFlowData { pub struct InvoiceRecordBackData; #[derive(Debug, Clone)] -pub struct SubscriptionCreateData; +pub struct SubscriptionCustomerData { + pub connector_meta_data: Option<pii::SecretSerdeValue>, +} + +#[derive(Debug, Clone)] +pub struct SubscriptionCreateData { + pub connector_meta_data: Option<pii::SecretSerdeValue>, +} #[derive(Debug, Clone)] -pub struct GetSubscriptionPlansData; +pub struct GetSubscriptionPlansData { + pub connector_meta_data: Option<pii::SecretSerdeValue>, +} #[derive(Debug, Clone)] -pub struct GetSubscriptionPlanPricesData; +pub struct GetSubscriptionPlanPricesData { + pub connector_meta_data: Option<pii::SecretSerdeValue>, +} #[derive(Debug, Clone)] pub struct GetSubscriptionEstimateData; diff --git a/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs b/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs index f480765effa..73b80b82075 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs @@ -13,7 +13,7 @@ pub struct SubscriptionCreateResponse { pub created_at: Option<PrimitiveDateTime>, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Copy)] pub enum SubscriptionStatus { Pending, Trial, @@ -25,6 +25,22 @@ pub enum SubscriptionStatus { Failed, } +#[cfg(feature = "v1")] +impl From<SubscriptionStatus> for api_models::subscription::SubscriptionStatus { + fn from(status: SubscriptionStatus) -> Self { + match status { + SubscriptionStatus::Pending => Self::Pending, + SubscriptionStatus::Trial => Self::Trial, + SubscriptionStatus::Active => Self::Active, + SubscriptionStatus::Paused => Self::Paused, + SubscriptionStatus::Unpaid => Self::Unpaid, + SubscriptionStatus::Onetime => Self::Onetime, + SubscriptionStatus::Cancelled => Self::Cancelled, + SubscriptionStatus::Failed => Self::Failed, + } + } +} + #[derive(Debug, Clone)] pub struct GetSubscriptionPlansResponse { pub list: Vec<SubscriptionPlans>, diff --git a/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs b/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs index 09f25918c56..47a8b4484a1 100644 --- a/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs +++ b/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs @@ -2,30 +2,35 @@ use hyperswitch_domain_models::{ router_data_v2::flow_common_types::{ GetSubscriptionEstimateData, GetSubscriptionPlanPricesData, GetSubscriptionPlansData, - SubscriptionCreateData, + SubscriptionCreateData, SubscriptionCustomerData, }, - router_flow_types::subscriptions::{ - GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, - SubscriptionCreate, + router_flow_types::{ + subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate}, + CreateConnectorCustomer, GetSubscriptionEstimate, }, - router_request_types::subscriptions::{ - GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, - GetSubscriptionPlansRequest, SubscriptionCreateRequest, + router_request_types::{ + subscriptions::{ + GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, + GetSubscriptionPlansRequest, SubscriptionCreateRequest, + }, + ConnectorCustomerData, }, - router_response_types::subscriptions::{ - GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, - GetSubscriptionPlansResponse, SubscriptionCreateResponse, + router_response_types::{ + subscriptions::{ + GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, + GetSubscriptionPlansResponse, SubscriptionCreateResponse, + }, + PaymentsResponseData, }, }; -use super::payments_v2::ConnectorCustomerV2; use crate::connector_integration_v2::ConnectorIntegrationV2; /// trait SubscriptionsV2 pub trait SubscriptionsV2: GetSubscriptionPlansV2 + SubscriptionsCreateV2 - + ConnectorCustomerV2 + + SubscriptionConnectorCustomerV2 + GetSubscriptionPlanPricesV2 + GetSubscriptionEstimateV2 { @@ -64,6 +69,16 @@ pub trait SubscriptionsCreateV2: { } +/// trait SubscriptionConnectorCustomerV2 +pub trait SubscriptionConnectorCustomerV2: + ConnectorIntegrationV2< + CreateConnectorCustomer, + SubscriptionCustomerData, + ConnectorCustomerData, + PaymentsResponseData, +> +{ +} /// trait GetSubscriptionEstimate for V2 pub trait GetSubscriptionEstimateV2: ConnectorIntegrationV2< diff --git a/crates/hyperswitch_interfaces/src/conversion_impls.rs b/crates/hyperswitch_interfaces/src/conversion_impls.rs index 3d3219a33f8..ed83c8235f1 100644 --- a/crates/hyperswitch_interfaces/src/conversion_impls.rs +++ b/crates/hyperswitch_interfaces/src/conversion_impls.rs @@ -14,7 +14,7 @@ use hyperswitch_domain_models::{ ExternalVaultProxyFlowData, FilesFlowData, GetSubscriptionPlanPricesData, GetSubscriptionPlansData, GiftCardBalanceCheckFlowData, InvoiceRecordBackData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData, SubscriptionCreateData, - UasFlowData, VaultConnectorFlowData, WebhookSourceVerifyData, + SubscriptionCustomerData, UasFlowData, VaultConnectorFlowData, WebhookSourceVerifyData, }, RouterDataV2, }, @@ -846,7 +846,9 @@ macro_rules! default_router_data_conversion { where Self: Sized, { - let resource_common_data = Self {}; + let resource_common_data = Self { + connector_meta_data: old_router_data.connector_meta_data.clone(), + }; Ok(RouterDataV2 { flow: std::marker::PhantomData, tenant_id: old_router_data.tenant_id.clone(), @@ -863,16 +865,19 @@ macro_rules! default_router_data_conversion { where Self: Sized, { - let router_data = get_default_router_data( + let Self { + connector_meta_data, + } = new_router_data.resource_common_data; + let mut router_data = get_default_router_data( new_router_data.tenant_id.clone(), stringify!($flow_name), new_router_data.request, new_router_data.response, ); - Ok(RouterData { - connector_auth_type: new_router_data.connector_auth_type.clone(), - ..router_data - }) + router_data.connector_meta_data = connector_meta_data; + router_data.connector_auth_type = new_router_data.connector_auth_type; + + Ok(router_data) } } }; @@ -880,6 +885,7 @@ macro_rules! default_router_data_conversion { default_router_data_conversion!(GetSubscriptionPlansData); default_router_data_conversion!(GetSubscriptionPlanPricesData); default_router_data_conversion!(SubscriptionCreateData); +default_router_data_conversion!(SubscriptionCustomerData); impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for UasFlowData { fn from_old_router_data( diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index a30f8d4c565..a0bec1a5a1b 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -285,6 +285,8 @@ pub enum StripeErrorCode { PlatformUnauthorizedRequest, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Profile Acquirer not found")] ProfileAcquirerNotFound, + #[error(error_type = StripeErrorType::HyperswitchError, code = "Subscription Error", message = "Subscription operation: {operation} failed with connector")] + SubscriptionError { operation: String }, // [#216]: https://github.com/juspay/hyperswitch/issues/216 // Implement the remaining stripe error codes @@ -697,6 +699,9 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { object: "tokenization record".to_owned(), id, }, + errors::ApiErrorResponse::SubscriptionError { operation } => { + Self::SubscriptionError { operation } + } } } } @@ -781,7 +786,8 @@ impl actix_web::ResponseError for StripeErrorCode { | Self::WebhookProcessingError | Self::InvalidTenant | Self::ExternalVaultFailed - | Self::AmountConversionFailed { .. } => StatusCode::INTERNAL_SERVER_ERROR, + | Self::AmountConversionFailed { .. } + | Self::SubscriptionError { .. } => StatusCode::INTERNAL_SERVER_ERROR, Self::ReturnUrlUnavailable => StatusCode::SERVICE_UNAVAILABLE, Self::ExternalConnectorError { status_code, .. } => { StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR) diff --git a/crates/router/src/core/subscription.rs b/crates/router/src/core/subscription.rs index 32c6754e2fe..b5c760ad3ec 100644 --- a/crates/router/src/core/subscription.rs +++ b/crates/router/src/core/subscription.rs @@ -1,16 +1,31 @@ use std::str::FromStr; -use api_models::subscription::{ - self as subscription_types, CreateSubscriptionResponse, SubscriptionStatus, +use api_models::{ + enums as api_enums, + subscription::{self as subscription_types, CreateSubscriptionResponse, SubscriptionStatus}, }; -use common_utils::id_type::GenerateId; +use common_utils::{ext_traits::ValueExt, id_type::GenerateId, pii}; use diesel_models::subscription::SubscriptionNew; use error_stack::ResultExt; -use hyperswitch_domain_models::{api::ApplicationResponse, merchant_context::MerchantContext}; +use hyperswitch_domain_models::{ + api::ApplicationResponse, + merchant_context::MerchantContext, + router_data_v2::flow_common_types::{SubscriptionCreateData, SubscriptionCustomerData}, + router_request_types::{subscriptions as subscription_request_types, ConnectorCustomerData}, + router_response_types::{ + subscriptions as subscription_response_types, ConnectorCustomerResponseData, + PaymentsResponseData, + }, +}; use masking::Secret; use super::errors::{self, RouterResponse}; -use crate::routes::SessionState; +use crate::{ + core::payments as payments_core, routes::SessionState, services, types::api as api_types, +}; + +pub const SUBSCRIPTION_CONNECTOR_ID: &str = "DefaultSubscriptionConnectorId"; +pub const SUBSCRIPTION_PAYMENT_ID: &str = "DefaultSubscriptionPaymentId"; pub async fn create_subscription( state: SessionState, @@ -63,3 +78,544 @@ pub async fn create_subscription( Ok(ApplicationResponse::Json(response)) } + +pub async fn confirm_subscription( + state: SessionState, + merchant_context: MerchantContext, + profile_id: String, + request: subscription_types::ConfirmSubscriptionRequest, + subscription_id: common_utils::id_type::SubscriptionId, +) -> RouterResponse<subscription_types::ConfirmSubscriptionResponse> { + let profile_id = common_utils::id_type::ProfileId::from_str(&profile_id).change_context( + errors::ApiErrorResponse::InvalidDataValue { + field_name: "X-Profile-Id", + }, + )?; + + let key_manager_state = &(&state).into(); + let merchant_key_store = merchant_context.get_merchant_key_store(); + + let profile = state + .store + .find_business_profile_by_profile_id(key_manager_state, merchant_key_store, &profile_id) + .await + .change_context(errors::ApiErrorResponse::ProfileNotFound { + id: profile_id.get_string_repr().to_string(), + })?; + + let customer = state + .store + .find_customer_by_customer_id_merchant_id( + key_manager_state, + &request.customer_id, + merchant_context.get_merchant_account().get_id(), + merchant_key_store, + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::CustomerNotFound) + .attach_printable("subscriptions: unable to fetch customer from database")?; + + let handler = SubscriptionHandler::new(state, merchant_context, request, profile); + + let mut subscription_entry = handler + .find_subscription(subscription_id.get_string_repr().to_string()) + .await?; + + let billing_handler = subscription_entry.get_billing_handler(customer).await?; + let invoice_handler = subscription_entry.get_invoice_handler().await?; + + let _customer_create_response = billing_handler + .create_customer_on_connector(&handler.state) + .await?; + + let subscription_create_response = billing_handler + .create_subscription_on_connector(&handler.state) + .await?; + + // let payment_response = invoice_handler.create_cit_payment().await?; + + let invoice_entry = invoice_handler + .create_invoice_entry( + &handler.state, + subscription_entry.profile.get_billing_processor_id()?, + None, + billing_handler.request.amount, + billing_handler.request.currency.to_string(), + common_enums::connector_enums::InvoiceStatus::InvoiceCreated, + billing_handler.connector_data.connector_name, + None, + ) + .await?; + + // invoice_entry + // .create_invoice_record_back_job(&payment_response) + // .await?; + + subscription_entry + .update_subscription_status( + SubscriptionStatus::from(subscription_create_response.status).to_string(), + ) + .await?; + + let response = subscription_entry + .generate_response(&invoice_entry, subscription_create_response.status)?; + + Ok(ApplicationResponse::Json(response)) +} + +pub struct SubscriptionHandler { + state: SessionState, + merchant_context: MerchantContext, + request: subscription_types::ConfirmSubscriptionRequest, + profile: hyperswitch_domain_models::business_profile::Profile, +} + +impl SubscriptionHandler { + pub fn new( + state: SessionState, + merchant_context: MerchantContext, + request: subscription_types::ConfirmSubscriptionRequest, + profile: hyperswitch_domain_models::business_profile::Profile, + ) -> Self { + Self { + state, + merchant_context, + request, + profile, + } + } + pub async fn find_subscription( + &self, + subscription_id: String, + ) -> errors::RouterResult<SubscriptionWithHandler<'_>> { + let subscription = self + .state + .store + .find_by_merchant_id_subscription_id( + self.merchant_context.get_merchant_account().get_id(), + subscription_id.clone(), + ) + .await + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: format!("subscription not found for id: {subscription_id}"), + })?; + + Ok(SubscriptionWithHandler { + handler: self, + subscription, + profile: self.profile.clone(), + }) + } +} +pub struct SubscriptionWithHandler<'a> { + handler: &'a SubscriptionHandler, + subscription: diesel_models::subscription::Subscription, + profile: hyperswitch_domain_models::business_profile::Profile, +} + +impl<'a> SubscriptionWithHandler<'a> { + fn generate_response( + &self, + invoice: &diesel_models::invoice::Invoice, + // _payment_response: &subscription_types::PaymentResponseData, + status: subscription_response_types::SubscriptionStatus, + ) -> errors::RouterResult<subscription_types::ConfirmSubscriptionResponse> { + Ok(subscription_types::ConfirmSubscriptionResponse { + id: self.subscription.id.clone(), + merchant_reference_id: self.subscription.merchant_reference_id.clone(), + status: SubscriptionStatus::from(status), + plan_id: None, + profile_id: self.subscription.profile_id.to_owned(), + payment: None, + customer_id: Some(self.subscription.customer_id.clone()), + price_id: None, + coupon: None, + invoice: Some(subscription_types::Invoice { + id: invoice.id.clone(), + subscription_id: invoice.subscription_id.clone(), + merchant_id: invoice.merchant_id.clone(), + profile_id: invoice.profile_id.clone(), + merchant_connector_id: invoice.merchant_connector_id.clone(), + payment_intent_id: invoice.payment_intent_id.clone(), + payment_method_id: invoice.payment_method_id.clone(), + customer_id: invoice.customer_id.clone(), + amount: invoice.amount, + currency: api_enums::Currency::from_str(invoice.currency.as_str()) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "currency", + }) + .attach_printable(format!( + "unable to parse currency name {currency:?}", + currency = invoice.currency + ))?, + status: invoice.status.clone(), + }), + }) + } + + async fn update_subscription_status(&mut self, status: String) -> errors::RouterResult<()> { + let db = self.handler.state.store.as_ref(); + let updated_subscription = db + .update_subscription_entry( + self.handler + .merchant_context + .get_merchant_account() + .get_id(), + self.subscription.id.get_string_repr().to_string(), + diesel_models::subscription::SubscriptionUpdate::new(None, Some(status)), + ) + .await + .change_context(errors::ApiErrorResponse::SubscriptionError { + operation: "Subscription Update".to_string(), + }) + .attach_printable("subscriptions: unable to update subscription entry in database")?; + + self.subscription = updated_subscription; + + Ok(()) + } + + pub async fn get_billing_handler( + &self, + customer: hyperswitch_domain_models::customer::Customer, + ) -> errors::RouterResult<BillingHandler> { + let mca_id = self.profile.get_billing_processor_id()?; + + let billing_processor_mca = self + .handler + .state + .store + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &(&self.handler.state).into(), + self.handler + .merchant_context + .get_merchant_account() + .get_id(), + &mca_id, + self.handler.merchant_context.get_merchant_key_store(), + ) + .await + .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: mca_id.get_string_repr().to_string(), + })?; + + let connector_name = billing_processor_mca.connector_name.clone(); + + let auth_type: hyperswitch_domain_models::router_data::ConnectorAuthType = + payments_core::helpers::MerchantConnectorAccountType::DbVal(Box::new( + billing_processor_mca.clone(), + )) + .get_connector_account_details() + .parse_value("ConnectorAuthType") + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "connector_account_details".to_string(), + expected_format: "auth_type and api_key".to_string(), + })?; + + let connector_data = api_types::ConnectorData::get_connector_by_name( + &self.handler.state.conf.connectors, + &connector_name, + api_types::GetToken::Connector, + Some(billing_processor_mca.get_id()), + ) + .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) + .attach_printable( + "invalid connector name received in billing merchant connector account", + )?; + + let connector_enum = + common_enums::connector_enums::Connector::from_str(connector_name.as_str()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable(format!("unable to parse connector name {connector_name:?}"))?; + + let connector_params = + hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params( + &self.handler.state.conf.connectors, + connector_enum, + ) + .change_context(errors::ApiErrorResponse::ConfigNotFound) + .attach_printable(format!( + "cannot find connector params for this connector {connector_name} in this flow", + ))?; + + Ok(BillingHandler { + subscription: self.subscription.clone(), + auth_type, + connector_data, + connector_params, + request: self.handler.request.clone(), + connector_metadata: billing_processor_mca.metadata.clone(), + customer, + }) + } + + pub async fn get_invoice_handler(&self) -> errors::RouterResult<InvoiceHandler> { + Ok(InvoiceHandler { + subscription: self.subscription.clone(), + }) + } +} + +pub struct BillingHandler { + subscription: diesel_models::subscription::Subscription, + auth_type: hyperswitch_domain_models::router_data::ConnectorAuthType, + connector_data: api_types::ConnectorData, + connector_params: hyperswitch_domain_models::connector_endpoints::ConnectorParams, + connector_metadata: Option<pii::SecretSerdeValue>, + customer: hyperswitch_domain_models::customer::Customer, + request: subscription_types::ConfirmSubscriptionRequest, +} + +pub struct InvoiceHandler { + subscription: diesel_models::subscription::Subscription, +} + +#[allow(clippy::todo)] +impl InvoiceHandler { + #[allow(clippy::too_many_arguments)] + pub async fn create_invoice_entry( + self, + state: &SessionState, + merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, + payment_intent_id: Option<common_utils::id_type::PaymentId>, + amount: common_utils::types::MinorUnit, + currency: String, + status: common_enums::connector_enums::InvoiceStatus, + provider_name: common_enums::connector_enums::Connector, + metadata: Option<pii::SecretSerdeValue>, + ) -> errors::RouterResult<diesel_models::invoice::Invoice> { + let invoice_new = diesel_models::invoice::InvoiceNew::new( + self.subscription.id.to_owned(), + self.subscription.merchant_id.to_owned(), + self.subscription.profile_id.to_owned(), + merchant_connector_id, + payment_intent_id, + self.subscription.payment_method_id.clone(), + self.subscription.customer_id.to_owned(), + amount, + currency, + status, + provider_name, + metadata, + ); + + let invoice = state + .store + .insert_invoice_entry(invoice_new) + .await + .change_context(errors::ApiErrorResponse::SubscriptionError { + operation: "Subscription Confirm".to_string(), + }) + .attach_printable("invoices: unable to insert invoice entry to database")?; + + Ok(invoice) + } + + pub async fn create_cit_payment( + &self, + ) -> errors::RouterResult<subscription_types::PaymentResponseData> { + // Create a CIT payment for the invoice + todo!("Create a CIT payment for the invoice") + } + + pub async fn create_invoice_record_back_job( + &self, + // _invoice: &subscription_types::Invoice, + _payment_response: &subscription_types::PaymentResponseData, + ) -> errors::RouterResult<()> { + // Create an invoice job entry based on payment status + todo!("Create an invoice job entry based on payment status") + } +} + +#[allow(clippy::todo)] +impl BillingHandler { + pub async fn create_customer_on_connector( + &self, + state: &SessionState, + ) -> errors::RouterResult<ConnectorCustomerResponseData> { + let customer_req = ConnectorCustomerData { + email: self.customer.email.clone().map(pii::Email::from), + payment_method_data: self + .request + .payment_details + .payment_method_data + .payment_method_data + .clone() + .map(|pmd| pmd.into()), + description: None, + phone: None, + name: None, + preprocessing_id: None, + split_payments: None, + setup_future_usage: None, + customer_acceptance: None, + customer_id: Some(self.subscription.customer_id.to_owned()), + billing_address: self + .request + .billing_address + .as_ref() + .and_then(|add| add.address.clone()) + .and_then(|addr| addr.into()), + }; + let router_data = self.build_router_data( + state, + customer_req, + SubscriptionCustomerData { + connector_meta_data: self.connector_metadata.clone(), + }, + )?; + let connector_integration = self.connector_data.connector.get_connector_integration(); + + let response = Box::pin(self.call_connector( + state, + router_data, + "create customer on connector", + connector_integration, + )) + .await?; + + match response { + Ok(response_data) => match response_data { + PaymentsResponseData::ConnectorCustomerResponse(customer_response) => { + Ok(customer_response) + } + _ => Err(errors::ApiErrorResponse::SubscriptionError { + operation: "Subscription Customer Create".to_string(), + } + .into()), + }, + Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: self.connector_data.connector_name.to_string(), + status_code: err.status_code, + reason: err.reason, + } + .into()), + } + } + pub async fn create_subscription_on_connector( + &self, + state: &SessionState, + ) -> errors::RouterResult<subscription_response_types::SubscriptionCreateResponse> { + let subscription_item = subscription_request_types::SubscriptionItem { + item_price_id: self.request.get_item_price_id().change_context( + errors::ApiErrorResponse::MissingRequiredField { + field_name: "item_price_id", + }, + )?, + quantity: Some(1), + }; + let subscription_req = subscription_request_types::SubscriptionCreateRequest { + subscription_id: self.subscription.id.to_owned(), + customer_id: self.subscription.customer_id.to_owned(), + subscription_items: vec![subscription_item], + billing_address: self.request.get_billing_address().change_context( + errors::ApiErrorResponse::MissingRequiredField { + field_name: "billing_address", + }, + )?, + auto_collection: subscription_request_types::SubscriptionAutoCollection::Off, + connector_params: self.connector_params.clone(), + }; + + let router_data = self.build_router_data( + state, + subscription_req, + SubscriptionCreateData { + connector_meta_data: self.connector_metadata.clone(), + }, + )?; + let connector_integration = self.connector_data.connector.get_connector_integration(); + + let response = self + .call_connector( + state, + router_data, + "create subscription on connector", + connector_integration, + ) + .await?; + + match response { + Ok(response_data) => Ok(response_data), + Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: self.connector_data.connector_name.to_string(), + status_code: err.status_code, + reason: err.reason, + } + .into()), + } + } + + async fn call_connector<F, ResourceCommonData, Req, Resp>( + &self, + state: &SessionState, + router_data: hyperswitch_domain_models::router_data_v2::RouterDataV2< + F, + ResourceCommonData, + Req, + Resp, + >, + operation_name: &str, + connector_integration: hyperswitch_interfaces::connector_integration_interface::BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>, + ) -> errors::RouterResult<Result<Resp, hyperswitch_domain_models::router_data::ErrorResponse>> + where + F: Clone + std::fmt::Debug + 'static, + Req: Clone + std::fmt::Debug + 'static, + Resp: Clone + std::fmt::Debug + 'static, + ResourceCommonData: + hyperswitch_interfaces::connector_integration_interface::RouterDataConversion< + F, + Req, + Resp, + > + Clone + + 'static, + { + let old_router_data = ResourceCommonData::to_old_router_data(router_data).change_context( + errors::ApiErrorResponse::SubscriptionError { + operation: { operation_name.to_string() }, + }, + )?; + + let router_resp = services::execute_connector_processing_step( + state, + connector_integration, + &old_router_data, + payments_core::CallConnectorAction::Trigger, + None, + None, + ) + .await + .change_context(errors::ApiErrorResponse::SubscriptionError { + operation: operation_name.to_string(), + }) + .attach_printable(format!( + "Failed while in subscription operation: {operation_name}" + ))?; + + Ok(router_resp.response) + } + + fn build_router_data<F, ResourceCommonData, Req, Resp>( + &self, + state: &SessionState, + req: Req, + resource_common_data: ResourceCommonData, + ) -> errors::RouterResult< + hyperswitch_domain_models::router_data_v2::RouterDataV2<F, ResourceCommonData, Req, Resp>, + > { + Ok(hyperswitch_domain_models::router_data_v2::RouterDataV2 { + flow: std::marker::PhantomData, + connector_auth_type: self.auth_type.clone(), + resource_common_data, + tenant_id: state.tenant.tenant_id.clone(), + request: req, + response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), + }) + } +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 1de0029f767..0d7da850f11 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1174,13 +1174,21 @@ pub struct Subscription; #[cfg(all(feature = "oltp", feature = "v1"))] impl Subscription { pub fn server(state: AppState) -> Scope { - web::scope("/subscription/create") - .app_data(web::Data::new(state.clone())) - .service(web::resource("").route( + let route = web::scope("/subscription").app_data(web::Data::new(state.clone())); + + route + .service(web::resource("/create").route( web::post().to(|state, req, payload| { subscription::create_subscription(state, req, payload) }), )) + .service( + web::resource("/{subscription_id}/confirm").route(web::post().to( + |state, req, id, payload| { + subscription::confirm_subscription(state, req, id, payload) + }, + )), + ) } } diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 992edb61c35..c0c670f3eee 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -88,7 +88,7 @@ impl From<Flow> for ApiIdentifier { | Flow::DecisionEngineDecideGatewayCall | Flow::DecisionEngineGatewayFeedbackCall => Self::Routing, - Flow::CreateSubscription => Self::Subscription, + Flow::CreateSubscription | Flow::ConfirmSubscription => Self::Subscription, Flow::RetrieveForexFlow => Self::Forex, Flow::AddToBlocklist => Self::Blocklist, diff --git a/crates/router/src/routes/subscription.rs b/crates/router/src/routes/subscription.rs index d4b716f63c0..aacf03392be 100644 --- a/crates/router/src/routes/subscription.rs +++ b/crates/router/src/routes/subscription.rs @@ -67,3 +67,55 @@ pub async fn create_subscription( )) .await } + +#[cfg(all(feature = "olap", feature = "v1"))] +#[instrument(skip_all)] +pub async fn confirm_subscription( + state: web::Data<AppState>, + req: HttpRequest, + subscription_id: web::Path<common_utils::id_type::SubscriptionId>, + json_payload: web::Json<subscription_types::ConfirmSubscriptionRequest>, +) -> impl Responder { + let flow = Flow::ConfirmSubscription; + let subscription_id = subscription_id.into_inner(); + let profile_id = match req.headers().get(X_PROFILE_ID) { + Some(val) => val.to_str().unwrap_or_default().to_string(), + None => { + return HttpResponse::BadRequest().json( + errors::api_error_response::ApiErrorResponse::MissingRequiredField { + field_name: "x-profile-id", + }, + ); + } + }; + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: auth::AuthenticationData, payload, _| { + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( + domain::Context(auth.merchant_account, auth.key_store), + )); + subscription::confirm_subscription( + state, + merchant_context, + profile_id.clone(), + payload.clone(), + subscription_id.clone(), + ) + }, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }), + &auth::JWTAuth { + permission: Permission::ProfileSubscriptionWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index d8f5f1a3a3b..b2582d7e3fe 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -3,6 +3,7 @@ use std::{fmt::Debug, marker::PhantomData, str::FromStr, sync::Arc, time::Durati use async_trait::async_trait; use common_utils::{id_type::GenerateId, pii::Email}; use error_stack::Report; +use hyperswitch_domain_models::router_data_v2::flow_common_types::PaymentFlowData; use masking::Secret; use router::{ configs::settings::Settings, @@ -117,7 +118,8 @@ pub trait ConnectorActions: Connector { payment_data: Option<types::ConnectorCustomerData>, payment_info: Option<PaymentInfo>, ) -> Result<types::ConnectorCustomerRouterData, Report<ConnectorError>> { - let integration = self.get_data().connector.get_connector_integration(); + let integration: BoxedConnectorIntegrationInterface<_, PaymentFlowData, _, _> = + self.get_data().connector.get_connector_integration(); let request = self.generate_data( types::ConnectorCustomerData { ..(payment_data.unwrap_or(CustomerType::default().0)) diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 50c47489108..1bbc2605f6b 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -265,6 +265,8 @@ pub enum Flow { RoutingDeleteConfig, /// Subscription create flow, CreateSubscription, + /// Subscription confirm flow, + ConfirmSubscription, /// Create dynamic routing CreateDynamicRoutingConfig, /// Toggle dynamic routing diff --git a/migrations/2025-09-23-112547_add_billing_processor_in_connector_type/down.sql b/migrations/2025-09-23-112547_add_billing_processor_in_connector_type/down.sql new file mode 100644 index 00000000000..d0b08278125 --- /dev/null +++ b/migrations/2025-09-23-112547_add_billing_processor_in_connector_type/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +SELECT(1); \ No newline at end of file diff --git a/migrations/2025-09-23-112547_add_billing_processor_in_connector_type/up.sql b/migrations/2025-09-23-112547_add_billing_processor_in_connector_type/up.sql new file mode 100644 index 00000000000..0201e3753f1 --- /dev/null +++ b/migrations/2025-09-23-112547_add_billing_processor_in_connector_type/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TYPE "ConnectorType" +ADD VALUE 'billing_processor'; \ No newline at end of file
2025-09-10T15:31:58Z
This pull request introduces a new subscription feature to the codebase, adding comprehensive support for subscription management via new API models, endpoints, and supporting logic. The changes include new data models, API routes, core business logic for creating and confirming subscriptions, and integration with customer management. The implementation is gated behind the `v1` and `olap` feature flags. **New Subscription Feature** * Added `subscription` module to `api_models`, including request and response types, core data structures (`Subscription`, `Invoice`), and helper functions for mapping customer data. * Introduced a new `Subscription` resource to the global `Resource` enum for system-wide referencing. **Core Logic and Utilities** * Implemented core business logic in `core/subscription.rs` for creating and confirming subscriptions, including customer handling, client secret generation, and placeholder billing processor integration. * Added utility functions in `core/subscription/utils.rs` for customer retrieval/creation and extracting customer details from subscription requests. * Updated customer helper function signature in payouts to allow broader usage in subscription flows. **Database and Model Changes** * Added client secret generation to the `SubscriptionNew` model in `diesel_models`, supporting secure subscription creation. [[1]](diffhunk://#diff-18a18c6db4052184eddf2b35c376f2eff90d566c06c6d2fbc4aea751852b0f3aR85-R94) [[2]](diffhunk://#diff-18a18c6db4052184eddf2b35c376f2eff90d566c06c6d2fbc4aea751852b0f3aL1-R1) **API Routing and Integration** * Registered new subscription endpoints in the API routes and application server, enabling `/subscription` and `/subscription/{subscription_id}/confirm` endpoints for managing subscriptions. [[1]](diffhunk://#diff-a6e49b399ffdee83dd322b3cb8bee170c65fb9c6e2e52c14222ec310f6927c54R1164-R1186) [[2]](diffhunk://#diff-911527e4effff636e27a7c44689ecc4a5c37963f0e9198193eacb52e1488cab5R212) [[3]](diffhunk://#diff-7e1080d750a904d5d9ea4a8041a6b210d2b0c1fa9e45207500824f0dad7fbc51R53-R54) [[4]](diffhunk://#diff-7e1080d750a904d5d9ea4a8041a6b210d2b0c1fa9e45207500824f0dad7fbc51L99-R101) [[5]](diffhunk://#diff-a6e49b399ffdee83dd322b3cb8bee170c65fb9c6e2e52c14222ec310f6927c54L68-R70) * Added subscription module references to core and feature-gated module lists for proper compilation and integration. [[1]](diffhunk://#diff-77a35e04ebe8b59efecf0b6a986e706e15170eb486b847e8c8c55514c5e55486R45-R46) [[2]](diffhunk://#diff-3f92a5ed20c7decce0129ef9eb838b87bae76de2197e8efa267657c26f590f4bR52-R53) * Updated API identifier enums to include `Subscription` for locking and routing utilities.] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. create a customer ``` curl --location 'http://localhost:8080/customers' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Ske75Nx2J7qtHsP8cc7pFx5k4dccYBedM6UAExaLOdHCkji3uVWSqfmZ0Qz0Tnyj' \ --data-raw '{ "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 2. create a subscription ``` curl --location 'http://localhost:8080/subscription/create' \ --header 'Content-Type: application/json' \ --header 'X-Profile-Id: pro_X16mQSHipgRuWbTEMkMp' \ --header 'api-key: dev_Ske75Nx2J7qtHsP8cc7pFx5k4dccYBedM6UAExaLOdHCkji3uVWSqfmZ0Qz0Tnyj' \ --data '{ "customer_id": "cus_NdHhw4wwWyYXSldO9oYE" }' ``` response - ``` {"id":"subscription_wBV1G9dhh6EBhTOTXRBA","merchant_reference_id":null,"status":"Created","plan_id":null,"profile_id":"pro_X16mQSHipgRuWbTEMkMp","client_secret":"subscription_wBV1G9dhh6EBhTOTXRBA_secret_6W89VL1bl5C3esgbxpJp","merchant_id":"merchant_1758626894","coupon_code":null,"customer_id":"cus_NdHhw4wwWyYXSldO9oYE"} ``` 3. Confirm subscription ``` curl --location 'http://localhost:8080/subscription/subscription_wBV1G9dhh6EBhTOTXRBA/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_2WzEeiNyj8fSCObXqo36' \ --header 'api-key: dev_Ske75Nx2J7qtHsP8cc7pFx5k4dccYBedM6UAExaLOdHCkji3uVWSqfmZ0Qz0Tnyj' \ --data '{ "amount": 14100, "currency": "INR", "item_price_id": "cbdemo_enterprise-suite-INR-Daily", "customer_id": "cus_NdHhw4wwWyYXSldO9oYE", "billing_address": { "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_details": { "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "setup_future_usage": "off_session", "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" } } } }' ``` Response - ``` {"id":"subscription_wBV1G9dhh6EBhTOTXRBA","merchant_reference_id":null,"status":"Active","plan_id":null,"price_id":null,"coupon":null,"profile_id":"pro_X16mQSHipgRuWbTEMkMp","payment":null,"customer_id":"cus_NdHhw4wwWyYXSldO9oYE","invoice":{"id":"invoice_0XANlbhMp2V7wUvWRhhJ","subscription_id":"subscription_wBV1G9dhh6EBhTOTXRBA","merchant_id":"merchant_1758626894","profile_id":"pro_X16mQSHipgRuWbTEMkMp","merchant_connector_id":"mca_eN6JxSK2NkuT0wSYAH5s","payment_intent_id":null,"payment_method_id":null,"customer_id":"cus_NdHhw4wwWyYXSldO9oYE","amount":14100,"currency":"INR","status":"InvoiceCreated"}} ``` ## 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.117.0
b26e845198407f3672a7f80d8eea670419858e0e
b26e845198407f3672a7f80d8eea670419858e0e
juspay/hyperswitch
juspay__hyperswitch-9101
Bug: Gift Card Balance check API for split payments We need to add an API to check balance for gift card. This API will be called by the SDK and based on the gift card balance and transaction amount, we will collect either only gift card details or gift card details + another payment method
diff --git a/api-reference/docs.json b/api-reference/docs.json index aa3cae620fc..46531c95c3f 100644 --- a/api-reference/docs.json +++ b/api-reference/docs.json @@ -150,9 +150,7 @@ }, { "group": "Platform Account", - "pages": [ - "v1/platform/platform--create" - ] + "pages": ["v1/platform/platform--create"] }, { "group": "API Key", @@ -268,7 +266,8 @@ "v2/payments/payments--confirm-intent", "v2/payments/payments--get", "v2/payments/payments--create-and-confirm-intent", - "v2/payments/payments--list" + "v2/payments/payments--list", + "v2/payments/payments--gift-card-balance-check" ] }, { diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 1559dce9183..f29e2a30056 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -2593,6 +2593,64 @@ ] } }, + "/v2/payments/{id}/check-gift-card-balance": { + "get": { + "tags": [ + "Payments" + ], + "summary": "Payments - Gift Card Balance Check", + "description": "Check the balance of the provided gift card. This endpoint also returns whether the gift card balance is enough to cover the entire amount or another payment method is needed", + "operationId": "Retrieve Gift Card Balance", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "The global payment id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "X-Profile-Id", + "in": "header", + "description": "Profile ID associated to the payment intent", + "required": true, + "schema": { + "type": "string" + }, + "example": "pro_abcdefghijklmnop" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentsGiftCardBalanceCheckRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Get the Gift Card Balance", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GiftCardBalanceCheckResponse" + } + } + } + } + }, + "security": [ + { + "publishable_key": [] + } + ] + } + }, "/v2/payment-methods": { "post": { "tags": [ @@ -12143,6 +12201,35 @@ } ] }, + "GiftCardBalanceCheckResponse": { + "type": "object", + "required": [ + "payment_id", + "balance", + "currency", + "needs_additional_pm_data", + "remaining_amount" + ], + "properties": { + "payment_id": { + "type": "string", + "description": "Global Payment Id for the payment" + }, + "balance": { + "$ref": "#/components/schemas/MinorUnit" + }, + "currency": { + "$ref": "#/components/schemas/Currency" + }, + "needs_additional_pm_data": { + "type": "boolean", + "description": "Whether the gift card balance is enough for the transaction (Used for split payments case)" + }, + "remaining_amount": { + "$ref": "#/components/schemas/MinorUnit" + } + } + }, "GiftCardData": { "oneOf": [ { @@ -19344,6 +19431,19 @@ } } }, + "PaymentsGiftCardBalanceCheckRequest": { + "type": "object", + "description": "Request for Gift Card balance check", + "required": [ + "gift_card_data" + ], + "properties": { + "gift_card_data": { + "$ref": "#/components/schemas/GiftCardData" + } + }, + "additionalProperties": false + }, "PaymentsIncrementalAuthorizationRequest": { "type": "object", "required": [ diff --git a/api-reference/v2/payments/payments--gift-card-balance-check.mdx b/api-reference/v2/payments/payments--gift-card-balance-check.mdx new file mode 100644 index 00000000000..680d08ada41 --- /dev/null +++ b/api-reference/v2/payments/payments--gift-card-balance-check.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/payments/{id}/check-gift-card-balance +--- \ No newline at end of file diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index 2571ca53816..8a0af806334 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -181,6 +181,13 @@ impl ApiEventMetric for PaymentsCreateIntentRequest { } } +#[cfg(feature = "v2")] +impl ApiEventMetric for payments::GiftCardBalanceCheckResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + None + } +} + #[cfg(feature = "v2")] impl ApiEventMetric for PaymentsRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 52f75bbe8be..62390067d3b 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -664,6 +664,23 @@ pub struct PaymentsIntentResponse { pub payment_type: api_enums::PaymentType, } +#[cfg(feature = "v2")] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct GiftCardBalanceCheckResponse { + /// Global Payment Id for the payment + #[schema(value_type = String)] + pub payment_id: id_type::GlobalPaymentId, + /// The balance of the gift card + pub balance: MinorUnit, + /// The currency of the Gift Card + #[schema(value_type = Currency)] + pub currency: common_enums::Currency, + /// Whether the gift card balance is enough for the transaction (Used for split payments case) + pub needs_additional_pm_data: bool, + /// Transaction amount left after subtracting gift card balance (Used for split payments) + pub remaining_amount: MinorUnit, +} + #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { @@ -5768,6 +5785,17 @@ pub struct PaymentsConfirmIntentRequest { pub return_raw_connector_response: Option<bool>, } +// Serialize is implemented because, this will be serialized in the api events. +// Usually request types should not have serialize implemented. +// +/// Request for Gift Card balance check +#[cfg(feature = "v2")] +#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct PaymentsGiftCardBalanceCheckRequest { + pub gift_card_data: GiftCardData, +} + #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] 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 94ffbed57af..b6d62689ec5 100644 --- a/crates/common_utils/src/id_type/global_id/payment.rs +++ b/crates/common_utils/src/id_type/global_id/payment.rs @@ -36,6 +36,11 @@ impl GlobalPaymentId { ) -> String { format!("{runner}_{task}_{}", self.get_string_repr()) } + + /// Generate a key for gift card connector + pub fn get_gift_card_connector_key(&self) -> String { + format!("gift_mca_{}", self.get_string_repr()) + } } // TODO: refactor the macro to include this id use case as well diff --git a/crates/hyperswitch_connectors/src/connectors/adyen.rs b/crates/hyperswitch_connectors/src/connectors/adyen.rs index 47f2eefeafc..a07986ba18e 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen.rs @@ -25,24 +25,25 @@ use hyperswitch_domain_models::{ Void, }, refunds::{Execute, RSync}, - Accept, Defend, Evidence, Retrieve, Upload, + Accept, Defend, Evidence, GiftCardBalanceCheck, Retrieve, Upload, }, router_request_types::{ AcceptDisputeRequestData, AccessTokenRequestData, DefendDisputeRequestData, - PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, - PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, - RefundsData, RetrieveFileRequestData, SetupMandateRequestData, SubmitEvidenceRequestData, - SyncRequestType, UploadFileRequestData, + GiftCardBalanceCheckRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, + PaymentsSyncData, RefundsData, RetrieveFileRequestData, SetupMandateRequestData, + SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData, }, router_response_types::{ - AcceptDisputeResponse, ConnectorInfo, DefendDisputeResponse, PaymentMethodDetails, - PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, - SupportedPaymentMethods, SupportedPaymentMethodsExt, UploadFileResponse, + AcceptDisputeResponse, ConnectorInfo, DefendDisputeResponse, + GiftCardBalanceCheckResponseData, PaymentMethodDetails, PaymentsResponseData, + RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, SupportedPaymentMethods, + SupportedPaymentMethodsExt, UploadFileResponse, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, - PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundsRouterData, - SetupMandateRouterData, + PaymentsGiftCardBalanceCheckRouterData, PaymentsPreProcessingRouterData, + PaymentsSyncRouterData, RefundsRouterData, SetupMandateRouterData, }, }; #[cfg(feature = "payouts")] @@ -69,8 +70,8 @@ use hyperswitch_interfaces::{ events::connector_api_logs::ConnectorEvent, types::{ AcceptDisputeType, DefendDisputeType, PaymentsAuthorizeType, PaymentsCaptureType, - PaymentsPreProcessingType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType, Response, - SetupMandateType, SubmitEvidenceType, + PaymentsGiftCardBalanceCheckType, PaymentsPreProcessingType, PaymentsSyncType, + PaymentsVoidType, RefundExecuteType, Response, SetupMandateType, SubmitEvidenceType, }, webhooks::{IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails}, }; @@ -416,6 +417,7 @@ impl api::PaymentCapture for Adyen {} impl api::MandateSetup for Adyen {} impl api::ConnectorAccessToken for Adyen {} impl api::PaymentToken for Adyen {} +impl api::PaymentsGiftCardBalanceCheck for Adyen {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Adyen @@ -1164,6 +1166,114 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Ad } } +impl + ConnectorIntegration< + GiftCardBalanceCheck, + GiftCardBalanceCheckRequestData, + GiftCardBalanceCheckResponseData, + > for Adyen +{ + fn get_headers( + &self, + req: &PaymentsGiftCardBalanceCheckRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + PaymentsGiftCardBalanceCheckType::get_content_type(self) + .to_string() + .into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } + + fn get_url( + &self, + req: &PaymentsGiftCardBalanceCheckRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let endpoint = build_env_specific_endpoint( + self.base_url(connectors), + req.test_mode, + &req.connector_meta_data, + )?; + Ok(format!( + "{endpoint}{ADYEN_API_VERSION}/paymentMethods/balance", + )) + } + + fn get_request_body( + &self, + req: &PaymentsGiftCardBalanceCheckRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = adyen::AdyenBalanceRequest::try_from(req)?; + + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsGiftCardBalanceCheckRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsGiftCardBalanceCheckType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(PaymentsGiftCardBalanceCheckType::get_headers( + self, req, connectors, + )?) + .set_body(PaymentsGiftCardBalanceCheckType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsGiftCardBalanceCheckRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsGiftCardBalanceCheckRouterData, errors::ConnectorError> { + let response: adyen::AdyenBalanceResponse = res + .response + .parse_struct("AdyenBalanceResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } + + fn get_5xx_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + impl api::Payouts for Adyen {} #[cfg(feature = "payouts")] impl api::PayoutCancel for Adyen {} diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index 4858e70b6fc..6b679f40b1f 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -27,14 +27,19 @@ use hyperswitch_domain_models::{ router_data::{ ConnectorAuthType, ErrorResponse, PaymentMethodBalance, PaymentMethodToken, RouterData, }, - router_request_types::{PaymentsPreProcessingData, ResponseId, SubmitEvidenceRequestData}, + router_flow_types::GiftCardBalanceCheck, + router_request_types::{ + GiftCardBalanceCheckRequestData, PaymentsPreProcessingData, ResponseId, + SubmitEvidenceRequestData, + }, router_response_types::{ - AcceptDisputeResponse, DefendDisputeResponse, MandateReference, PaymentsResponseData, - RedirectForm, RefundsResponseData, SubmitEvidenceResponse, + AcceptDisputeResponse, DefendDisputeResponse, GiftCardBalanceCheckResponseData, + MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, + SubmitEvidenceResponse, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, - PaymentsPreProcessingRouterData, RefundsRouterData, + PaymentsGiftCardBalanceCheckRouterData, PaymentsPreProcessingRouterData, RefundsRouterData, }, }; #[cfg(feature = "payouts")] @@ -1805,6 +1810,41 @@ impl TryFrom<&PaymentsPreProcessingRouterData> for AdyenBalanceRequest<'_> { } } +impl TryFrom<&PaymentsGiftCardBalanceCheckRouterData> for AdyenBalanceRequest<'_> { + type Error = Error; + fn try_from(item: &PaymentsGiftCardBalanceCheckRouterData) -> Result<Self, Self::Error> { + let payment_method = match &item.request.payment_method_data { + PaymentMethodData::GiftCard(gift_card_data) => match gift_card_data.as_ref() { + GiftCardData::Givex(gift_card_data) => { + let balance_pm = BalancePmData { + number: gift_card_data.number.clone(), + cvc: gift_card_data.cvc.clone(), + }; + Ok(AdyenPaymentMethod::PaymentMethodBalance(Box::new( + balance_pm, + ))) + } + GiftCardData::PaySafeCard {} | GiftCardData::BhnCardNetwork(_) => { + Err(errors::ConnectorError::FlowNotSupported { + flow: "Balance".to_string(), + connector: "adyen".to_string(), + }) + } + }, + _ => Err(errors::ConnectorError::FlowNotSupported { + flow: "Balance".to_string(), + connector: "adyen".to_string(), + }), + }?; + + let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; + Ok(Self { + payment_method, + merchant_account: auth_type.merchant_account, + }) + } +} + impl From<&PaymentsAuthorizeRouterData> for AdyenShopperInteraction { fn from(item: &PaymentsAuthorizeRouterData) -> Self { match item.request.off_session { @@ -3929,6 +3969,40 @@ impl<F> } } +impl + TryFrom< + ResponseRouterData< + GiftCardBalanceCheck, + AdyenBalanceResponse, + GiftCardBalanceCheckRequestData, + GiftCardBalanceCheckResponseData, + >, + > + for RouterData< + GiftCardBalanceCheck, + GiftCardBalanceCheckRequestData, + GiftCardBalanceCheckResponseData, + > +{ + type Error = Error; + fn try_from( + item: ResponseRouterData< + GiftCardBalanceCheck, + AdyenBalanceResponse, + GiftCardBalanceCheckRequestData, + GiftCardBalanceCheckResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(GiftCardBalanceCheckResponseData { + balance: item.response.balance.value, + currency: item.response.balance.currency, + }), + ..item.data + }) + } +} + pub fn get_adyen_response( response: AdyenResponse, is_capture_manual: bool, diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 1e404df7f97..8b742d71026 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -35,9 +35,9 @@ use hyperswitch_domain_models::{ mandate_revoke::MandateRevoke, payments::{ Approve, AuthorizeSessionToken, CalculateTax, CompleteAuthorize, - CreateConnectorCustomer, CreateOrder, IncrementalAuthorization, PostCaptureVoid, - PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, - UpdateMetadata, + CreateConnectorCustomer, CreateOrder, GiftCardBalanceCheck, IncrementalAuthorization, + PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, + SdkSessionUpdate, UpdateMetadata, }, subscriptions::GetSubscriptionPlans, webhooks::VerifyWebhookSource, @@ -56,8 +56,8 @@ use hyperswitch_domain_models::{ AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, DisputeSyncData, ExternalVaultProxyPaymentsData, - FetchDisputesRequestData, MandateRevokeRequestData, PaymentsApproveData, - PaymentsAuthenticateData, PaymentsCancelPostCaptureData, + FetchDisputesRequestData, GiftCardBalanceCheckRequestData, MandateRevokeRequestData, + PaymentsApproveData, PaymentsAuthenticateData, PaymentsCancelPostCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsTaxCalculationData, @@ -68,9 +68,10 @@ use hyperswitch_domain_models::{ router_response_types::{ subscriptions::GetSubscriptionPlansResponse, AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse, DisputeSyncResponse, - FetchDisputesResponse, MandateRevokeResponseData, PaymentsResponseData, - RetrieveFileResponse, SubmitEvidenceResponse, TaxCalculationResponseData, - UploadFileResponse, VaultResponseData, VerifyWebhookSourceResponseData, + FetchDisputesResponse, GiftCardBalanceCheckResponseData, MandateRevokeResponseData, + PaymentsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, + TaxCalculationResponseData, UploadFileResponse, VaultResponseData, + VerifyWebhookSourceResponseData, }, }; #[cfg(feature = "frm")] @@ -125,8 +126,8 @@ use hyperswitch_interfaces::{ PaymentAuthorizeSessionToken, PaymentIncrementalAuthorization, PaymentPostCaptureVoid, PaymentPostSessionTokens, PaymentReject, PaymentSessionUpdate, PaymentUpdateMetadata, PaymentsAuthenticate, PaymentsCompleteAuthorize, PaymentsCreateOrder, - PaymentsPostAuthenticate, PaymentsPostProcessing, PaymentsPreAuthenticate, - PaymentsPreProcessing, TaxCalculation, + PaymentsGiftCardBalanceCheck, PaymentsPostAuthenticate, PaymentsPostProcessing, + PaymentsPreAuthenticate, PaymentsPreProcessing, TaxCalculation, }, revenue_recovery::RevenueRecovery, subscriptions::{GetSubscriptionPlansFlow, Subscriptions}, @@ -7797,6 +7798,149 @@ default_imp_for_external_vault_insert!( connectors::Zsl ); +macro_rules! default_imp_for_gift_card_balance_check { + ($($path:ident::$connector:ident),*) => { + $( + impl PaymentsGiftCardBalanceCheck for $path::$connector {} + impl + ConnectorIntegration< + GiftCardBalanceCheck, + GiftCardBalanceCheckRequestData, + GiftCardBalanceCheckResponseData, + > for $path::$connector + {} + )* + }; +} +default_imp_for_gift_card_balance_check!( + connectors::Aci, + connectors::Adyenplatform, + connectors::Affirm, + connectors::Airwallex, + connectors::Amazonpay, + connectors::Archipel, + connectors::Authipay, + connectors::Authorizedotnet, + connectors::Bambora, + connectors::Bamboraapac, + connectors::Bankofamerica, + connectors::Barclaycard, + connectors::Billwerk, + connectors::Bitpay, + connectors::Blackhawknetwork, + connectors::Bluecode, + connectors::Bluesnap, + connectors::Boku, + connectors::Braintree, + connectors::Breadpay, + connectors::Cashtocode, + connectors::Celero, + connectors::Chargebee, + connectors::Checkbook, + connectors::Checkout, + connectors::Coinbase, + connectors::Coingate, + connectors::Cryptopay, + connectors::CtpMastercard, + connectors::Custombilling, + connectors::Cybersource, + connectors::Datatrans, + connectors::Deutschebank, + connectors::Digitalvirgo, + connectors::Dlocal, + connectors::Dwolla, + connectors::Ebanx, + connectors::Elavon, + connectors::Facilitapay, + connectors::Fiserv, + connectors::Fiservemea, + connectors::Fiuu, + connectors::Flexiti, + connectors::Forte, + connectors::Getnet, + connectors::Globalpay, + connectors::Globepay, + connectors::Gocardless, + connectors::Gpayments, + connectors::Helcim, + connectors::Hipay, + connectors::HyperswitchVault, + connectors::Hyperwallet, + connectors::Iatapay, + connectors::Inespay, + connectors::Itaubank, + connectors::Jpmorgan, + connectors::Juspaythreedsserver, + connectors::Katapult, + connectors::Klarna, + connectors::Mifinity, + connectors::Mollie, + connectors::Moneris, + connectors::Mpgs, + connectors::Multisafepay, + connectors::Netcetera, + connectors::Nexinets, + connectors::Nexixpay, + connectors::Nmi, + connectors::Nomupay, + connectors::Noon, + connectors::Nordea, + connectors::Novalnet, + connectors::Nuvei, + connectors::Opayo, + connectors::Opennode, + connectors::Paybox, + connectors::Payeezy, + connectors::Payload, + connectors::Payme, + connectors::Payone, + connectors::Paypal, + connectors::Paystack, + connectors::Paysafe, + connectors::Paytm, + connectors::Payu, + connectors::Peachpayments, + connectors::Phonepe, + connectors::Placetopay, + connectors::Plaid, + connectors::Powertranz, + connectors::Prophetpay, + connectors::Rapyd, + connectors::Razorpay, + connectors::Recurly, + connectors::Redsys, + connectors::Riskified, + connectors::Santander, + connectors::Shift4, + connectors::Sift, + connectors::Signifyd, + connectors::Silverflow, + connectors::Square, + connectors::Stax, + connectors::Stripe, + connectors::Stripebilling, + connectors::Taxjar, + connectors::Threedsecureio, + connectors::Thunes, + connectors::Tokenio, + connectors::Trustpay, + connectors::Trustpayments, + connectors::Tsys, + connectors::UnifiedAuthenticationService, + connectors::Vgs, + connectors::Volt, + connectors::Wellsfargo, + connectors::Wellsfargopayout, + connectors::Wise, + connectors::Worldline, + connectors::Worldpay, + connectors::Worldpayvantiv, + connectors::Worldpayxml, + connectors::Xendit, + connectors::Zen, + connectors::Zsl +); + macro_rules! default_imp_for_external_vault_retrieve { ($($path:ident::$connector:ident),*) => { $( @@ -8622,6 +8766,18 @@ impl<const T: u8> ConnectorIntegration<Dsync, DisputeSyncData, DisputeSyncRespon { } +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PaymentsGiftCardBalanceCheck for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration< + GiftCardBalanceCheck, + GiftCardBalanceCheckRequestData, + GiftCardBalanceCheckResponseData, + > for connectors::DummyConnector<T> +{ +} + #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentsPreProcessing for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 836ad796a05..01c42dfe63f 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -3,8 +3,8 @@ use hyperswitch_domain_models::{ router_data_v2::{ flow_common_types::{ BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData, - DisputesFlowData, InvoiceRecordBackData, MandateRevokeFlowData, PaymentFlowData, - RefundFlowData, WebhookSourceVerifyData, + DisputesFlowData, GiftCardBalanceCheckFlowData, InvoiceRecordBackData, + MandateRevokeFlowData, PaymentFlowData, RefundFlowData, WebhookSourceVerifyData, }, AccessTokenFlowData, AuthenticationTokenFlowData, ExternalAuthenticationFlowData, FilesFlowData, VaultConnectorFlowData, @@ -18,9 +18,10 @@ use hyperswitch_domain_models::{ mandate_revoke::MandateRevoke, payments::{ Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, - CreateConnectorCustomer, CreateOrder, ExternalVaultProxy, IncrementalAuthorization, - PSync, PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, - PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, + CreateConnectorCustomer, CreateOrder, ExternalVaultProxy, GiftCardBalanceCheck, + IncrementalAuthorization, PSync, PaymentMethodToken, PostCaptureVoid, PostProcessing, + PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, + UpdateMetadata, Void, }, refunds::{Execute, RSync}, revenue_recovery::{ @@ -39,10 +40,10 @@ use hyperswitch_domain_models::{ AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, DisputeSyncData, - ExternalVaultProxyPaymentsData, FetchDisputesRequestData, MandateRevokeRequestData, - PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, - PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, + ExternalVaultProxyPaymentsData, FetchDisputesRequestData, GiftCardBalanceCheckRequestData, + MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsApproveData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, + PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, RetrieveFileRequestData, @@ -55,9 +56,9 @@ use hyperswitch_domain_models::{ InvoiceRecordBackResponse, }, AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse, - DisputeSyncResponse, FetchDisputesResponse, MandateRevokeResponseData, - PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, - TaxCalculationResponseData, UploadFileResponse, VaultResponseData, + DisputeSyncResponse, FetchDisputesResponse, GiftCardBalanceCheckResponseData, + MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, + SubmitEvidenceResponse, TaxCalculationResponseData, UploadFileResponse, VaultResponseData, VerifyWebhookSourceResponseData, }, }; @@ -108,8 +109,8 @@ use hyperswitch_interfaces::{ PaymentCreateOrderV2, PaymentIncrementalAuthorizationV2, PaymentPostCaptureVoidV2, PaymentPostSessionTokensV2, PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, PaymentSyncV2, PaymentTokenV2, PaymentUpdateMetadataV2, PaymentV2, PaymentVoidV2, - PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, - TaxCalculationV2, + PaymentsCompleteAuthorizeV2, PaymentsGiftCardBalanceCheckV2, PaymentsPostProcessingV2, + PaymentsPreProcessingV2, TaxCalculationV2, }, refunds_v2::{RefundExecuteV2, RefundSyncV2, RefundV2}, revenue_recovery_v2::{ @@ -147,6 +148,7 @@ macro_rules! default_imp_for_new_connector_integration_payment { impl PaymentTokenV2 for $path::$connector{} impl ConnectorCustomerV2 for $path::$connector{} impl PaymentsPreProcessingV2 for $path::$connector{} + impl PaymentsGiftCardBalanceCheckV2 for $path::$connector{} impl PaymentsPostProcessingV2 for $path::$connector{} impl TaxCalculationV2 for $path::$connector{} impl PaymentSessionUpdateV2 for $path::$connector{} @@ -216,6 +218,12 @@ macro_rules! default_imp_for_new_connector_integration_payment { PaymentsPreProcessingData, PaymentsResponseData, > for $path::$connector{} + impl ConnectorIntegrationV2< + GiftCardBalanceCheck, + GiftCardBalanceCheckFlowData, + GiftCardBalanceCheckRequestData, + GiftCardBalanceCheckResponseData, + > for $path::$connector{} impl ConnectorIntegrationV2< PostProcessing, PaymentFlowData, diff --git a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs index 7e72bfa023f..471d2227640 100644 --- a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs +++ b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs @@ -170,6 +170,9 @@ pub struct VaultConnectorFlowData { pub merchant_id: common_utils::id_type::MerchantId, } +#[derive(Debug, Clone)] +pub struct GiftCardBalanceCheckFlowData; + #[derive(Debug, Clone)] pub struct ExternalVaultProxyFlowData { pub merchant_id: common_utils::id_type::MerchantId, diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs index eece6330e33..2b0e8b42046 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs @@ -85,3 +85,6 @@ pub struct PaymentGetListAttempts; #[derive(Debug, Clone)] pub struct ExternalVaultProxy; + +#[derive(Debug, Clone)] +pub struct GiftCardBalanceCheck; diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index b97675006ed..0a91a9207e0 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -555,6 +555,13 @@ pub struct PaymentsPreProcessingData { pub minor_amount: Option<MinorUnit>, } +#[derive(Debug, Clone)] +pub struct GiftCardBalanceCheckRequestData { + pub payment_method_data: PaymentMethodData, + pub currency: Option<storage_enums::Currency>, + pub minor_amount: Option<MinorUnit>, +} + impl TryFrom<PaymentsAuthorizeData> for PaymentsPreProcessingData { type Error = error_stack::Report<ApiErrorResponse>; diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs index cc766a00ba8..7ee0574178c 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types.rs @@ -86,6 +86,12 @@ pub enum PaymentsResponseData { }, } +#[derive(Debug, Clone)] +pub struct GiftCardBalanceCheckResponseData { + pub balance: MinorUnit, + pub currency: common_enums::Currency, +} + #[derive(Debug, Clone)] pub struct TaxCalculationResponseData { pub order_tax_amount: MinorUnit, diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs index 683e2842837..15b1a3086a6 100644 --- a/crates/hyperswitch_domain_models/src/types.rs +++ b/crates/hyperswitch_domain_models/src/types.rs @@ -9,9 +9,9 @@ use crate::{ Authenticate, AuthenticationConfirmation, Authorize, AuthorizeSessionToken, BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, Execute, ExternalVaultProxy, - IncrementalAuthorization, PSync, PaymentMethodToken, PostAuthenticate, PostCaptureVoid, - PostSessionTokens, PreAuthenticate, PreProcessing, RSync, SdkSessionUpdate, Session, - SetupMandate, UpdateMetadata, VerifyWebhookSource, Void, + GiftCardBalanceCheck, IncrementalAuthorization, PSync, PaymentMethodToken, + PostAuthenticate, PostCaptureVoid, PostSessionTokens, PreAuthenticate, PreProcessing, + RSync, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, VerifyWebhookSource, Void, }, router_request_types::{ revenue_recovery::{ @@ -26,14 +26,14 @@ use crate::{ }, AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, - ExternalVaultProxyPaymentsData, MandateRevokeRequestData, PaymentMethodTokenizationData, - PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, - PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, - PaymentsPostAuthenticateData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, - PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, - PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, - SdkPaymentsSessionUpdateData, SetupMandateRequestData, VaultRequestData, - VerifyWebhookSourceRequestData, + ExternalVaultProxyPaymentsData, GiftCardBalanceCheckRequestData, MandateRevokeRequestData, + PaymentMethodTokenizationData, PaymentsAuthenticateData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, + PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, + PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, + PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, + PaymentsUpdateMetadataData, RefundsData, SdkPaymentsSessionUpdateData, + SetupMandateRequestData, VaultRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ revenue_recovery::{ @@ -41,8 +41,9 @@ use crate::{ InvoiceRecordBackResponse, }, subscriptions::GetSubscriptionPlansResponse, - MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData, - TaxCalculationResponseData, VaultResponseData, VerifyWebhookSourceResponseData, + GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData, + RefundsResponseData, TaxCalculationResponseData, VaultResponseData, + VerifyWebhookSourceResponseData, }, }; #[cfg(feature = "payouts")] @@ -85,6 +86,11 @@ pub type AccessTokenAuthenticationRouterData = RouterData< AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse, >; +pub type PaymentsGiftCardBalanceCheckRouterData = RouterData< + GiftCardBalanceCheck, + GiftCardBalanceCheckRequestData, + GiftCardBalanceCheckResponseData, +>; pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>; pub type PaymentsPostSessionTokensRouterData = RouterData<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>; diff --git a/crates/hyperswitch_interfaces/src/api/payments.rs b/crates/hyperswitch_interfaces/src/api/payments.rs index f4aa421240b..2120d3cf063 100644 --- a/crates/hyperswitch_interfaces/src/api/payments.rs +++ b/crates/hyperswitch_interfaces/src/api/payments.rs @@ -8,19 +8,23 @@ use hyperswitch_domain_models::{ PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, - Authenticate, CreateOrder, ExternalVaultProxy, PostAuthenticate, PreAuthenticate, + Authenticate, CreateOrder, ExternalVaultProxy, GiftCardBalanceCheck, PostAuthenticate, + PreAuthenticate, }, router_request_types::{ AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, - CreateOrderRequestData, ExternalVaultProxyPaymentsData, PaymentMethodTokenizationData, - PaymentsApproveData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, - PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, - PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, - PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsRejectData, - PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, - PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, + CreateOrderRequestData, ExternalVaultProxyPaymentsData, GiftCardBalanceCheckRequestData, + PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthenticateData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, + PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, + PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, + PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, + PaymentsTaxCalculationData, PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, + SetupMandateRequestData, + }, + router_response_types::{ + GiftCardBalanceCheckResponseData, PaymentsResponseData, TaxCalculationResponseData, }, - router_response_types::{PaymentsResponseData, TaxCalculationResponseData}, }; use crate::api; @@ -51,6 +55,7 @@ pub trait Payment: + PaymentUpdateMetadata + PaymentsCreateOrder + ExternalVaultProxyPaymentsCreateV1 + + PaymentsGiftCardBalanceCheck { } @@ -207,3 +212,13 @@ pub trait ExternalVaultProxyPaymentsCreateV1: api::ConnectorIntegration<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData> { } + +/// trait PaymentsGiftCardBalanceCheck +pub trait PaymentsGiftCardBalanceCheck: + api::ConnectorIntegration< + GiftCardBalanceCheck, + GiftCardBalanceCheckRequestData, + GiftCardBalanceCheckResponseData, +> +{ +} diff --git a/crates/hyperswitch_interfaces/src/api/payments_v2.rs b/crates/hyperswitch_interfaces/src/api/payments_v2.rs index 88c3e39ca40..c0681670ebc 100644 --- a/crates/hyperswitch_interfaces/src/api/payments_v2.rs +++ b/crates/hyperswitch_interfaces/src/api/payments_v2.rs @@ -1,7 +1,7 @@ //! Payments V2 interface use hyperswitch_domain_models::{ - router_data_v2::PaymentFlowData, + router_data_v2::{flow_common_types::GiftCardBalanceCheckFlowData, PaymentFlowData}, router_flow_types::{ payments::{ Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, @@ -9,19 +9,22 @@ use hyperswitch_domain_models::{ PSync, PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, - Authenticate, PostAuthenticate, PreAuthenticate, + Authenticate, GiftCardBalanceCheck, PostAuthenticate, PreAuthenticate, }, router_request_types::{ AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, - CreateOrderRequestData, ExternalVaultProxyPaymentsData, PaymentMethodTokenizationData, - PaymentsApproveData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, - PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, - PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, - PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsRejectData, - PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, - PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, + CreateOrderRequestData, ExternalVaultProxyPaymentsData, GiftCardBalanceCheckRequestData, + PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthenticateData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, + PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, + PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, + PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, + PaymentsTaxCalculationData, PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, + SetupMandateRequestData, + }, + router_response_types::{ + GiftCardBalanceCheckResponseData, PaymentsResponseData, TaxCalculationResponseData, }, - router_response_types::{PaymentsResponseData, TaxCalculationResponseData}, }; use crate::api::{ @@ -203,6 +206,17 @@ pub trait PaymentsPreProcessingV2: { } +/// trait PaymentsGiftCardBalanceCheckV2 +pub trait PaymentsGiftCardBalanceCheckV2: + ConnectorIntegrationV2< + GiftCardBalanceCheck, + GiftCardBalanceCheckFlowData, + GiftCardBalanceCheckRequestData, + GiftCardBalanceCheckResponseData, +> +{ +} + /// trait PaymentsPreAuthenticateV2 pub trait PaymentsPreAuthenticateV2: ConnectorIntegrationV2< @@ -235,7 +249,6 @@ pub trait PaymentsPostAuthenticateV2: > { } - /// trait PaymentsPostProcessingV2 pub trait PaymentsPostProcessingV2: ConnectorIntegrationV2< @@ -285,5 +298,6 @@ pub trait PaymentV2: + PaymentUpdateMetadataV2 + PaymentCreateOrderV2 + ExternalVaultProxyPaymentsCreate + + PaymentsGiftCardBalanceCheckV2 { } diff --git a/crates/hyperswitch_interfaces/src/conversion_impls.rs b/crates/hyperswitch_interfaces/src/conversion_impls.rs index 288ec0db952..32818ca5d4b 100644 --- a/crates/hyperswitch_interfaces/src/conversion_impls.rs +++ b/crates/hyperswitch_interfaces/src/conversion_impls.rs @@ -12,8 +12,9 @@ use hyperswitch_domain_models::{ AccessTokenFlowData, AuthenticationTokenFlowData, BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData, DisputesFlowData, ExternalAuthenticationFlowData, ExternalVaultProxyFlowData, FilesFlowData, GetSubscriptionPlansData, - InvoiceRecordBackData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData, - UasFlowData, VaultConnectorFlowData, WebhookSourceVerifyData, + GiftCardBalanceCheckFlowData, InvoiceRecordBackData, MandateRevokeFlowData, + PaymentFlowData, RefundFlowData, UasFlowData, VaultConnectorFlowData, + WebhookSourceVerifyData, }, RouterDataV2, }, @@ -167,6 +168,45 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for AccessTo } } +impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> + for GiftCardBalanceCheckFlowData +{ + fn from_old_router_data( + old_router_data: &RouterData<T, Req, Resp>, + ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> + where + Self: Sized, + { + let resource_common_data = Self; + Ok(RouterDataV2 { + flow: std::marker::PhantomData, + tenant_id: old_router_data.tenant_id.clone(), + resource_common_data, + connector_auth_type: old_router_data.connector_auth_type.clone(), + request: old_router_data.request.clone(), + response: old_router_data.response.clone(), + }) + } + + fn to_old_router_data( + new_router_data: RouterDataV2<T, Self, Req, Resp>, + ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> + where + Self: Sized, + { + let request = new_router_data.request.clone(); + let response = new_router_data.response.clone(); + let mut router_data = get_default_router_data( + new_router_data.tenant_id.clone(), + "gift card balance check", + request, + response, + ); + router_data.connector_auth_type = new_router_data.connector_auth_type; + Ok(router_data) + } +} + impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for PaymentFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs index e263735b8af..3afe6405315 100644 --- a/crates/hyperswitch_interfaces/src/types.rs +++ b/crates/hyperswitch_interfaces/src/types.rs @@ -25,7 +25,7 @@ use hyperswitch_domain_models::{ ExternalVaultRetrieveFlow, }, webhooks::VerifyWebhookSource, - AccessTokenAuthentication, BillingConnectorInvoiceSync, + AccessTokenAuthentication, BillingConnectorInvoiceSync, GiftCardBalanceCheck, }, router_request_types::{ revenue_recovery::{ @@ -41,12 +41,13 @@ use hyperswitch_domain_models::{ AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, DisputeSyncData, - FetchDisputesRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, - PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, - PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, - PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, - PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsSessionData, - PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, + FetchDisputesRequestData, GiftCardBalanceCheckRequestData, MandateRevokeRequestData, + PaymentMethodTokenizationData, PaymentsAuthenticateData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, + PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, + PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, + PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, + PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, SubmitEvidenceRequestData, UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData, @@ -58,8 +59,9 @@ use hyperswitch_domain_models::{ }, subscriptions::GetSubscriptionPlansResponse, AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, - MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, - SubmitEvidenceResponse, TaxCalculationResponseData, UploadFileResponse, VaultResponseData, + GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData, + RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, + TaxCalculationResponseData, UploadFileResponse, VaultResponseData, VerifyWebhookSourceResponseData, }, }; @@ -140,6 +142,12 @@ pub type PaymentsPreAuthorizeType = dyn ConnectorIntegration< AuthorizeSessionTokenData, PaymentsResponseData, >; +/// Type alias for `ConnectorIntegration<GiftCardBalanceCheck, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData>` +pub type PaymentsGiftCardBalanceCheckType = dyn ConnectorIntegration< + GiftCardBalanceCheck, + GiftCardBalanceCheckRequestData, + GiftCardBalanceCheckResponseData, +>; /// Type alias for `ConnectorIntegration<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>` pub type PaymentsInitType = dyn ConnectorIntegration<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>; diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 71fe216322d..3942d01abf2 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -128,6 +128,7 @@ Never share your secret api keys. Keep them guarded and secure. routes::payments::payments_connector_session, routes::payments::list_payment_methods, routes::payments::payments_list, + routes::payments::payment_check_gift_card_balance, //Routes for payment methods routes::payment_method::create_payment_method_api, @@ -543,6 +544,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::RequestSurchargeDetails, api_models::payments::PaymentRevenueRecoveryMetadata, api_models::payments::BillingConnectorPaymentDetails, + api_models::payments::GiftCardBalanceCheckResponse, + api_models::payments::PaymentsGiftCardBalanceCheckRequest, api_models::enums::PaymentConnectorTransmission, api_models::enums::TriggeredBy, api_models::payments::PaymentAttemptResponse, diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs index d3abd208e9a..026f4d6cc03 100644 --- a/crates/openapi/src/routes/payments.rs +++ b/crates/openapi/src/routes/payments.rs @@ -1268,3 +1268,30 @@ pub fn list_payment_methods() {} security(("api_key" = []), ("jwt_key" = [])) )] pub fn payments_list() {} + +/// Payments - Gift Card Balance Check +/// +/// Check the balance of the provided gift card. This endpoint also returns whether the gift card balance is enough to cover the entire amount or another payment method is needed +#[cfg(feature = "v2")] +#[utoipa::path( + get, + path = "/v2/payments/{id}/check-gift-card-balance", + params( + ("id" = String, Path, description = "The global payment id"), + ( + "X-Profile-Id" = String, Header, + description = "Profile ID associated to the payment intent", + example = "pro_abcdefghijklmnop" + ), + ), + request_body( + content = PaymentsGiftCardBalanceCheckRequest, + ), + responses( + (status = 200, description = "Get the Gift Card Balance", body = GiftCardBalanceCheckResponse), + ), + tag = "Payments", + operation_id = "Retrieve Gift Card Balance", + security(("publishable_key" = [])) +)] +pub fn payment_check_gift_card_balance() {} diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 0fe3e57f872..f7cb256f587 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -24,6 +24,8 @@ pub mod external_service_auth; pub mod files; #[cfg(feature = "frm")] pub mod fraud_check; +#[cfg(feature = "v2")] +pub mod gift_card; pub mod gsm; pub mod health_check; #[cfg(feature = "v1")] diff --git a/crates/router/src/core/gift_card.rs b/crates/router/src/core/gift_card.rs new file mode 100644 index 00000000000..d1c89eafdbb --- /dev/null +++ b/crates/router/src/core/gift_card.rs @@ -0,0 +1,179 @@ +use std::marker::PhantomData; + +#[cfg(feature = "v2")] +use api_models::payments::{GiftCardBalanceCheckResponse, PaymentsGiftCardBalanceCheckRequest}; +use common_enums::CallConnectorAction; +#[cfg(feature = "v2")] +use common_utils::id_type; +use common_utils::types::MinorUnit; +use error_stack::ResultExt; +#[cfg(feature = "v2")] +use hyperswitch_domain_models::payments::HeaderPayload; +use hyperswitch_domain_models::{ + router_data_v2::{flow_common_types::GiftCardBalanceCheckFlowData, RouterDataV2}, + router_flow_types::GiftCardBalanceCheck, + router_request_types::GiftCardBalanceCheckRequestData, + router_response_types::GiftCardBalanceCheckResponseData, +}; +use hyperswitch_interfaces::connector_integration_interface::RouterDataConversion; + +use crate::db::errors::StorageErrorExt; +#[cfg(feature = "v2")] +use crate::{ + core::{ + errors::{self, RouterResponse}, + payments::helpers, + }, + routes::{app::ReqState, SessionState}, + services, + types::{api, domain}, +}; + +#[cfg(feature = "v2")] +#[allow(clippy::too_many_arguments)] +pub async fn payments_check_gift_card_balance_core( + state: SessionState, + merchant_context: domain::MerchantContext, + profile: domain::Profile, + _req_state: ReqState, + req: PaymentsGiftCardBalanceCheckRequest, + _header_payload: HeaderPayload, + payment_id: id_type::GlobalPaymentId, +) -> RouterResponse<GiftCardBalanceCheckResponse> { + let db = state.store.as_ref(); + + let key_manager_state = &(&state).into(); + + let storage_scheme = merchant_context.get_merchant_account().storage_scheme; + let payment_intent = db + .find_payment_intent_by_id( + key_manager_state, + &payment_id, + merchant_context.get_merchant_key_store(), + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + let redis_conn = db + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Could not get redis connection")?; + + let gift_card_connector_id: String = redis_conn + .get_key(&payment_id.get_gift_card_connector_key().as_str().into()) + .await + .attach_printable("Failed to fetch gift card connector from redis") + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: "No connector found with Gift Card Support".to_string(), + })?; + + let gift_card_connector_id = id_type::MerchantConnectorAccountId::wrap(gift_card_connector_id) + .attach_printable("Failed to deserialize MCA") + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: "No connector found with Gift Card Support".to_string(), + })?; + + let merchant_connector_account = + domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( + helpers::get_merchant_connector_account_v2( + &state, + merchant_context.get_merchant_key_store(), + Some(&gift_card_connector_id), + ) + .await + .attach_printable( + "failed to fetch merchant connector account for gift card balance check", + )?, + )); + + let connector_name = merchant_connector_account + .get_connector_name() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Connector name not present for gift card balance check")?; // always get the connector name from this call + + let connector_data = api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &connector_name.to_string(), + api::GetToken::Connector, + merchant_connector_account.get_mca_id(), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get the connector data")?; + + let connector_auth_type = merchant_connector_account + .get_connector_account_details() + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + let resource_common_data = GiftCardBalanceCheckFlowData; + + let router_data: RouterDataV2< + GiftCardBalanceCheck, + GiftCardBalanceCheckFlowData, + GiftCardBalanceCheckRequestData, + GiftCardBalanceCheckResponseData, + > = RouterDataV2 { + flow: PhantomData, + resource_common_data, + tenant_id: state.tenant.tenant_id.clone(), + connector_auth_type, + request: GiftCardBalanceCheckRequestData { + payment_method_data: domain::PaymentMethodData::GiftCard(Box::new( + req.gift_card_data.into(), + )), + currency: Some(payment_intent.amount_details.currency), + minor_amount: Some(payment_intent.amount_details.order_amount), + }, + response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), + }; + + let old_router_data = GiftCardBalanceCheckFlowData::to_old_router_data(router_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Cannot construct router data for making the gift card balance check api call", + )?; + let connector_integration: services::BoxedGiftCardBalanceCheckIntegrationInterface< + GiftCardBalanceCheck, + GiftCardBalanceCheckRequestData, + GiftCardBalanceCheckResponseData, + > = connector_data.connector.get_connector_integration(); + + let connector_response = services::execute_connector_processing_step( + &state, + connector_integration, + &old_router_data, + CallConnectorAction::Trigger, + None, + None, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while calling gift card balance check connector api")?; + + let gift_card_balance = connector_response + .response + .map_err(|_| errors::ApiErrorResponse::UnprocessableEntity { + message: "Error while fetching gift card balance".to_string(), + }) + .attach_printable("Connector returned invalid response")?; + + let balance = gift_card_balance.balance; + let currency = gift_card_balance.currency; + let remaining_amount = + if (payment_intent.amount_details.order_amount - balance).is_greater_than(0) { + payment_intent.amount_details.order_amount - balance + } else { + MinorUnit::zero() + }; + let needs_additional_pm_data = remaining_amount.is_greater_than(0); + + let resp = GiftCardBalanceCheckResponse { + payment_id: payment_intent.id.clone(), + balance, + currency, + needs_additional_pm_data, + remaining_amount, + }; + + Ok(services::ApplicationResponse::Json(resp)) +} diff --git a/crates/router/src/core/payments/payment_methods.rs b/crates/router/src/core/payments/payment_methods.rs index 36a8120fd18..9a2a809ba89 100644 --- a/crates/router/src/core/payments/payment_methods.rs +++ b/crates/router/src/core/payments/payment_methods.rs @@ -78,6 +78,7 @@ pub async fn list_payment_methods( &req, &payment_intent, ).await? + .store_gift_card_mca_in_redis(&payment_id, db, &profile).await .merge_and_transform() .get_required_fields(RequiredFieldsInput::new(state.conf.required_fields.clone(), payment_intent.setup_future_usage)) .perform_surcharge_calculation() @@ -189,6 +190,50 @@ impl FilteredPaymentMethodsEnabled { .collect(); MergedEnabledPaymentMethodTypes(values) } + async fn store_gift_card_mca_in_redis( + self, + payment_id: &id_type::GlobalPaymentId, + db: &dyn crate::db::StorageInterface, + profile: &domain::Profile, + ) -> Self { + let gift_card_connector_id = self + .0 + .iter() + .find(|item| item.payment_method == common_enums::PaymentMethod::GiftCard) + .map(|item| &item.merchant_connector_id); + + if let Some(gift_card_mca) = gift_card_connector_id { + let gc_key = payment_id.get_gift_card_connector_key(); + let redis_expiry = profile + .get_order_fulfillment_time() + .unwrap_or(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME); + + let redis_conn = db + .get_redis_conn() + .map_err(|redis_error| logger::error!(?redis_error)) + .ok(); + + if let Some(rc) = redis_conn { + rc.set_key_with_expiry( + &gc_key.as_str().into(), + gift_card_mca.get_string_repr().to_string(), + redis_expiry, + ) + .await + .attach_printable("Failed to store gift card mca_id in redis") + .unwrap_or_else(|error| { + logger::error!(?error); + }) + }; + } else { + logger::error!( + "Could not find any configured MCA supporting gift card for payment_id -> {}", + payment_id.get_string_repr() + ); + } + + self + } } /// Element container to hold the filtered payment methods with payment_experience and connectors merged for a pm_subtype diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f12730d7b63..d52dc1570ce 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -737,6 +737,10 @@ impl Payments { ) .service( web::resource("/capture").route(web::post().to(payments::payments_capture)), + ) + .service( + web::resource("/check-gift-card-balance") + .route(web::post().to(payments::payment_check_gift_card_balance)), ), ); diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index c3efb561b42..28581198d83 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -163,6 +163,7 @@ impl From<Flow> for ApiIdentifier { | Flow::PaymentsConfirmIntent | Flow::PaymentsCreateIntent | Flow::PaymentsGetIntent + | Flow::GiftCardBalanceCheck | Flow::PaymentsPostSessionTokens | Flow::PaymentsUpdateMetadata | Flow::PaymentsUpdateIntent diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 1136e9f84a6..6f29b4cb5d9 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -11,6 +11,8 @@ use router_env::{env, instrument, logger, tracing, types, Flow}; use super::app::ReqState; #[cfg(feature = "v2")] +use crate::core::gift_card; +#[cfg(feature = "v2")] use crate::core::revenue_recovery::api as recovery; use crate::{ self as app, @@ -2984,6 +2986,69 @@ pub async fn payment_confirm_intent( .await } +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::GiftCardBalanceCheck, payment_id))] +pub async fn payment_check_gift_card_balance( + state: web::Data<app::AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<api_models::payments::PaymentsGiftCardBalanceCheckRequest>, + path: web::Path<common_utils::id_type::GlobalPaymentId>, +) -> impl Responder { + let flow = Flow::GiftCardBalanceCheck; + + let global_payment_id = path.into_inner(); + 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.clone(), + payload: json_payload.into_inner(), + }; + + let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { + Ok(headers) => headers, + Err(err) => { + return api::log_and_return_error_response(err); + } + }; + + Box::pin(api::server_wrap( + flow, + state, + &req, + internal_payload, + |state, auth: auth::AuthenticationData, req, req_state| async { + let payment_id = req.global_payment_id; + let request = req.payload; + + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( + domain::Context(auth.merchant_account, auth.key_store), + )); + Box::pin(gift_card::payments_check_gift_card_balance_core( + state, + merchant_context, + auth.profile, + req_state, + request, + header_payload.clone(), + payment_id, + )) + .await + }, + auth::api_or_client_auth( + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( + global_payment_id, + )), + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::ProxyConfirmIntent, payment_id))] pub async fn proxy_confirm_intent( diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 28928307646..e7e03a5f322 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -129,6 +129,9 @@ pub type BoxedBillingConnectorPaymentsSyncIntegrationInterface<T, Req, Res> = pub type BoxedVaultConnectorIntegrationInterface<T, Req, Res> = BoxedConnectorIntegrationInterface<T, common_types::VaultConnectorFlowData, Req, Res>; +pub type BoxedGiftCardBalanceCheckIntegrationInterface<T, Req, Res> = + BoxedConnectorIntegrationInterface<T, common_types::GiftCardBalanceCheckFlowData, Req, Res>; + /// Handle UCS webhook response processing fn handle_ucs_response<T, Req, Resp>( router_data: types::RouterData<T, Req, Resp>, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 2345469a4e1..f5359d84010 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -652,6 +652,8 @@ pub enum Flow { RecoveryPaymentsCreate, /// Tokenization delete flow TokenizationDelete, + /// Gift card balance check flow + GiftCardBalanceCheck, } /// Trait for providing generic behaviour to flow metric
2025-08-29T09:47: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 --> - Added `check-gift-card-balance` API - Added `GiftCardBalanceCheck` flow for connectors and implemented it for Adyen - Updated PML flow to store gift card enabled MCA in redis <img width="2314" height="1286" alt="image" src="https://github.com/user-attachments/assets/50087048-1ac5-459f-84ee-d6af7cdbfcae" /> ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This change is required for supporting split payments. SDK will call this endpoint and based on the gift card balance and transaction amount it will either collect Gift card details only or Gift card + another payment method. Closes #9101 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create-Intent Call 2. PML for payments call 3. Request: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_019937e3515f7462b97fe6f5f6901191/check-gift-card-balance' \ --header 'api-key: dev_vzsdTpwwx2h18nUXDFGPaIJmPifOT7zsX9DkCIA3FZQyJgny7c7MrV6RTdgStgOB' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_qAkCNwFOT6asT6ENbmFn' \ --header 'Authorization: publishable-key=pk_dev_433fd28e6bd24a6bb79527cde2af25e1, client-secret=cs_019937e351c171f19b62d7c44802d53e' \ --data '{ "gift_card_data": { "givex": { "number": "6036280000000000000", "cvc": "123" } } }' ``` Response: ``` { "payment_id": "12345_pay_019937e3515f7462b97fe6f5f6901191", "balance": 5000, "currency": "EUR", "needs_additional_pm_data": false, "remaining_amount": 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.117.0
f3ab3d63f69279af9254f15eba5654c0680a0747
f3ab3d63f69279af9254f15eba5654c0680a0747
juspay/hyperswitch
juspay__hyperswitch-9098
Bug: Subscription table and core change
diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index 246807a041a..caf979b2c5f 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -44,6 +44,7 @@ pub mod relay; pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; +pub mod subscription; pub mod types; pub mod unified_translations; diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs index 7c8831b3811..17eae2427e7 100644 --- a/crates/diesel_models/src/query.rs +++ b/crates/diesel_models/src/query.rs @@ -39,6 +39,7 @@ pub mod relay; pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; +pub mod subscription; #[cfg(feature = "tokenization_v2")] pub mod tokenization; pub mod unified_translations; diff --git a/crates/diesel_models/src/query/subscription.rs b/crates/diesel_models/src/query/subscription.rs new file mode 100644 index 00000000000..e25f1617873 --- /dev/null +++ b/crates/diesel_models/src/query/subscription.rs @@ -0,0 +1,59 @@ +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; +use error_stack::report; + +use super::generics; +use crate::{ + errors, + schema::subscription::dsl, + subscription::{Subscription, SubscriptionNew, SubscriptionUpdate}, + PgPooledConn, StorageResult, +}; + +impl SubscriptionNew { + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Subscription> { + generics::generic_insert(conn, self).await + } +} + +impl Subscription { + pub async fn find_by_merchant_id_subscription_id( + conn: &PgPooledConn, + merchant_id: &common_utils::id_type::MerchantId, + subscription_id: String, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::subscription_id.eq(subscription_id.to_owned())), + ) + .await + } + + pub async fn update_subscription_entry( + conn: &PgPooledConn, + merchant_id: &common_utils::id_type::MerchantId, + subscription_id: String, + subscription_update: SubscriptionUpdate, + ) -> StorageResult<Self> { + generics::generic_update_with_results::< + <Self as HasTable>::Table, + SubscriptionUpdate, + _, + _, + >( + conn, + dsl::subscription_id + .eq(subscription_id.to_owned()) + .and(dsl::merchant_id.eq(merchant_id.to_owned())), + subscription_update, + ) + .await? + .first() + .cloned() + .ok_or_else(|| { + report!(errors::DatabaseError::NotFound) + .attach_printable("Error while updating subscription entry") + }) + } +} diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 08675d904de..0d4564c83c3 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1465,6 +1465,36 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + subscription (id) { + id -> Int4, + #[max_length = 128] + subscription_id -> Varchar, + #[max_length = 128] + status -> Varchar, + #[max_length = 128] + billing_processor -> Nullable<Varchar>, + #[max_length = 128] + payment_method_id -> Nullable<Varchar>, + #[max_length = 128] + mca_id -> Nullable<Varchar>, + #[max_length = 128] + client_secret -> Nullable<Varchar>, + #[max_length = 128] + connector_subscription_id -> Nullable<Varchar>, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 64] + customer_id -> Varchar, + metadata -> Nullable<Jsonb>, + created_at -> Timestamp, + modified_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1650,6 +1680,7 @@ diesel::allow_tables_to_appear_in_same_query!( reverse_lookup, roles, routing_algorithm, + subscription, themes, unified_translations, user_authentication_methods, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index ea3980d942a..b734e2c4bb8 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1400,6 +1400,36 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + subscription (id) { + id -> Int4, + #[max_length = 128] + subscription_id -> Varchar, + #[max_length = 128] + status -> Varchar, + #[max_length = 128] + billing_processor -> Nullable<Varchar>, + #[max_length = 128] + payment_method_id -> Nullable<Varchar>, + #[max_length = 128] + mca_id -> Nullable<Varchar>, + #[max_length = 128] + client_secret -> Nullable<Varchar>, + #[max_length = 128] + connector_subscription_id -> Nullable<Varchar>, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 64] + customer_id -> Varchar, + metadata -> Nullable<Jsonb>, + created_at -> Timestamp, + modified_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1605,6 +1635,7 @@ diesel::allow_tables_to_appear_in_same_query!( reverse_lookup, roles, routing_algorithm, + subscription, themes, tokenization, unified_translations, diff --git a/crates/diesel_models/src/subscription.rs b/crates/diesel_models/src/subscription.rs new file mode 100644 index 00000000000..0cabb6a7b44 --- /dev/null +++ b/crates/diesel_models/src/subscription.rs @@ -0,0 +1,93 @@ +use common_utils::pii::SecretSerdeValue; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; +use serde::{Deserialize, Serialize}; + +use crate::schema::subscription; + +#[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] +#[diesel(table_name = subscription)] +pub struct SubscriptionNew { + subscription_id: String, + status: String, + billing_processor: Option<String>, + payment_method_id: Option<String>, + mca_id: Option<String>, + client_secret: Option<String>, + connector_subscription_id: Option<String>, + merchant_id: common_utils::id_type::MerchantId, + customer_id: common_utils::id_type::CustomerId, + metadata: Option<SecretSerdeValue>, + created_at: time::PrimitiveDateTime, + modified_at: time::PrimitiveDateTime, +} + +#[derive( + Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize, +)] +#[diesel(table_name = subscription, primary_key(id), check_for_backend(diesel::pg::Pg))] +pub struct Subscription { + #[serde(skip_serializing, skip_deserializing)] + pub id: i32, + pub subscription_id: String, + pub status: String, + pub billing_processor: Option<String>, + pub payment_method_id: Option<String>, + pub mca_id: Option<String>, + pub client_secret: Option<String>, + pub connector_subscription_id: Option<String>, + pub merchant_id: common_utils::id_type::MerchantId, + pub customer_id: common_utils::id_type::CustomerId, + pub metadata: Option<serde_json::Value>, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, +} + +#[derive(Clone, Debug, Eq, PartialEq, AsChangeset, router_derive::DebugAsDisplay, Deserialize)] +#[diesel(table_name = subscription)] +pub struct SubscriptionUpdate { + pub payment_method_id: Option<String>, + pub status: Option<String>, + pub modified_at: time::PrimitiveDateTime, +} + +impl SubscriptionNew { + #[allow(clippy::too_many_arguments)] + pub fn new( + subscription_id: String, + status: String, + billing_processor: Option<String>, + payment_method_id: Option<String>, + mca_id: Option<String>, + client_secret: Option<String>, + connector_subscription_id: Option<String>, + merchant_id: common_utils::id_type::MerchantId, + customer_id: common_utils::id_type::CustomerId, + metadata: Option<SecretSerdeValue>, + ) -> Self { + let now = common_utils::date_time::now(); + Self { + subscription_id, + status, + billing_processor, + payment_method_id, + mca_id, + client_secret, + connector_subscription_id, + merchant_id, + customer_id, + metadata, + created_at: now, + modified_at: now, + } + } +} + +impl SubscriptionUpdate { + pub fn new(payment_method_id: Option<String>, status: Option<String>) -> Self { + Self { + payment_method_id, + status, + modified_at: common_utils::date_time::now(), + } + } +} diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 59c31d4b2b8..f675e316aef 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -34,6 +34,7 @@ pub mod relay; pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; +pub mod subscription; pub mod unified_translations; pub mod user; pub mod user_authentication_method; @@ -143,6 +144,7 @@ pub trait StorageInterface: + payment_method_session::PaymentMethodsSessionInterface + tokenization::TokenizationInterface + callback_mapper::CallbackMapperInterface + + subscription::SubscriptionInterface + 'static { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; diff --git a/crates/router/src/db/subscription.rs b/crates/router/src/db/subscription.rs new file mode 100644 index 00000000000..5242c44299b --- /dev/null +++ b/crates/router/src/db/subscription.rs @@ -0,0 +1,140 @@ +use error_stack::report; +use router_env::{instrument, tracing}; +use storage_impl::MockDb; + +use super::Store; +use crate::{ + connection, + core::errors::{self, CustomResult}, + db::kafka_store::KafkaStore, + types::storage, +}; + +#[async_trait::async_trait] +pub trait SubscriptionInterface { + async fn insert_subscription_entry( + &self, + subscription_new: storage::subscription::SubscriptionNew, + ) -> CustomResult<storage::Subscription, errors::StorageError>; + + async fn find_by_merchant_id_subscription_id( + &self, + merchant_id: &common_utils::id_type::MerchantId, + subscription_id: String, + ) -> CustomResult<storage::Subscription, errors::StorageError>; + + async fn update_subscription_entry( + &self, + merchant_id: &common_utils::id_type::MerchantId, + subscription_id: String, + data: storage::SubscriptionUpdate, + ) -> CustomResult<storage::Subscription, errors::StorageError>; +} + +#[async_trait::async_trait] +impl SubscriptionInterface for Store { + #[instrument(skip_all)] + async fn insert_subscription_entry( + &self, + subscription_new: storage::subscription::SubscriptionNew, + ) -> CustomResult<storage::Subscription, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + subscription_new + .insert(&conn) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[instrument(skip_all)] + async fn find_by_merchant_id_subscription_id( + &self, + merchant_id: &common_utils::id_type::MerchantId, + subscription_id: String, + ) -> CustomResult<storage::Subscription, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Subscription::find_by_merchant_id_subscription_id( + &conn, + merchant_id, + subscription_id, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[instrument(skip_all)] + async fn update_subscription_entry( + &self, + merchant_id: &common_utils::id_type::MerchantId, + subscription_id: String, + data: storage::SubscriptionUpdate, + ) -> CustomResult<storage::Subscription, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Subscription::update_subscription_entry(&conn, merchant_id, subscription_id, data) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } +} + +#[async_trait::async_trait] +impl SubscriptionInterface for MockDb { + #[instrument(skip_all)] + async fn insert_subscription_entry( + &self, + _subscription_new: storage::subscription::SubscriptionNew, + ) -> CustomResult<storage::Subscription, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn find_by_merchant_id_subscription_id( + &self, + _merchant_id: &common_utils::id_type::MerchantId, + _subscription_id: String, + ) -> CustomResult<storage::Subscription, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn update_subscription_entry( + &self, + _merchant_id: &common_utils::id_type::MerchantId, + _subscription_id: String, + _data: storage::SubscriptionUpdate, + ) -> CustomResult<storage::Subscription, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } +} + +#[async_trait::async_trait] +impl SubscriptionInterface for KafkaStore { + #[instrument(skip_all)] + async fn insert_subscription_entry( + &self, + subscription_new: storage::subscription::SubscriptionNew, + ) -> CustomResult<storage::Subscription, errors::StorageError> { + self.diesel_store + .insert_subscription_entry(subscription_new) + .await + } + + #[instrument(skip_all)] + async fn find_by_merchant_id_subscription_id( + &self, + merchant_id: &common_utils::id_type::MerchantId, + subscription_id: String, + ) -> CustomResult<storage::Subscription, errors::StorageError> { + self.diesel_store + .find_by_merchant_id_subscription_id(merchant_id, subscription_id) + .await + } + + #[instrument(skip_all)] + async fn update_subscription_entry( + &self, + merchant_id: &common_utils::id_type::MerchantId, + subscription_id: String, + data: storage::SubscriptionUpdate, + ) -> CustomResult<storage::Subscription, errors::StorageError> { + self.diesel_store + .update_subscription_entry(merchant_id, subscription_id, data) + .await + } +} diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 70a0a344150..5d4c4a8bb29 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -41,6 +41,7 @@ pub mod revenue_recovery_redis_operation; pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; +pub mod subscription; pub mod unified_translations; pub mod user; pub mod user_authentication_method; @@ -77,5 +78,5 @@ pub use self::{ generic_link::*, gsm::*, locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*, payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*, routing_algorithm::*, - unified_translations::*, user::*, user_authentication_method::*, user_role::*, + subscription::*, unified_translations::*, user::*, user_authentication_method::*, user_role::*, }; diff --git a/crates/router/src/types/storage/subscription.rs b/crates/router/src/types/storage/subscription.rs new file mode 100644 index 00000000000..973c2283494 --- /dev/null +++ b/crates/router/src/types/storage/subscription.rs @@ -0,0 +1 @@ +pub use diesel_models::subscription::{Subscription, SubscriptionNew, SubscriptionUpdate}; diff --git a/migrations/2025-08-21-110802_add_subcription_table/down.sql b/migrations/2025-08-21-110802_add_subcription_table/down.sql new file mode 100644 index 00000000000..0979103e48c --- /dev/null +++ b/migrations/2025-08-21-110802_add_subcription_table/down.sql @@ -0,0 +1 @@ +DROP table subscription; diff --git a/migrations/2025-08-21-110802_add_subcription_table/up.sql b/migrations/2025-08-21-110802_add_subcription_table/up.sql new file mode 100644 index 00000000000..4e5419aefd4 --- /dev/null +++ b/migrations/2025-08-21-110802_add_subcription_table/up.sql @@ -0,0 +1,17 @@ +CREATE TABLE subscription ( + id SERIAL PRIMARY KEY, + subscription_id VARCHAR(128) NOT NULL, + status VARCHAR(128) NOT NULL, + billing_processor VARCHAR(128), + payment_method_id VARCHAR(128), + mca_id VARCHAR(128), + client_secret VARCHAR(128), + connector_subscription_id VARCHAR(128), + merchant_id VARCHAR(64) NOT NULL, + customer_id VARCHAR(64) NOT NULL, + metadata JSONB, + created_at TIMESTAMP NOT NULL, + modified_at TIMESTAMP NOT NULL +); + +CREATE UNIQUE INDEX merchant_subscription_unique_index ON subscription (merchant_id, subscription_id);
2025-09-01T13:07:55Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Description Introduce **Subscriptions** as a first-class entity in the router. This PR adds a `subscription` table, Diesel models, storage interfaces, and query helpers to **create**, **fetch**, and **update** subscription entries keyed by `(merchant_id, customer_id, subscription_id)`. ### What’s included **Database (PostgreSQL)** - New table: `subscription` - Columns: - `id VARCHAR(128) PRIMARY KEY` - `subscription_id VARCHAR(128) NULL` - `billing_processor VARCHAR(128) NULL` - `payment_method_id VARCHAR(128) NULL` - `mca_id VARCHAR(128) NULL` - `client_secret VARCHAR(128) NULL` - `merchant_id VARCHAR(64) NOT NULL` - `customer_id VARCHAR(64) NOT NULL` - `metadata JSONB NULL` - `created_at TIMESTAMP NOT NULL` - `modified_at TIMESTAMP NOT NULL` - Indexes: - `CREATE UNIQUE INDEX merchant_customer_subscription_unique_index ON subscription (merchant_id, customer_id, subscription_id);` **Migrations** - `up.sql` creates the table + unique index - `down.sql` drops the table **Diesel models & schema** - `crates/diesel_models/src/schema.rs`: `subscription` table mapping - `crates/diesel_models/src/subscription.rs`: - `SubscriptionNew` (insert) - `Subscription` (read) - `SubscriptionUpdate` (update: `subscription_id`, `payment_method_id`, `modified_at`) - Query functions: `crates/diesel_models/src/query/subscription.rs` - `SubscriptionNew::insert` - `Subscription::find_by_merchant_id_customer_id_subscription_id` - `Subscription::update_subscription_entry` **Router storage interface** - Trait: `SubscriptionInterface` (`crates/router/src/db/subscription.rs`) - `insert_subscription_entry` - `find_by_merchant_id_customer_id_subscription_id` - `update_subscription_entry` - Implemented for `Store`, `KafkaStore` (delegates), and `MockDb` (stubbed) **Wiring** - Re-exports in `crates/router/src/types/storage.rs` and module plumbing in `db.rs`, `diesel_models/src/lib.rs`, `query.rs`. --- ## Motivation and Context Subscriptions are often provisioned/managed outside Payments, but Payments needs a lightweight mapping to: - Track **billing processor** and connector meta (`mca_id`, `client_secret`) - Attach or rotate **payment_method_id** per subscription - Support **idempotent** reads keyed by merchant & customer context This schema enables upstream orchestration to store/retrieve subscription context without coupling to payment flows. --- ## API / Contract / Config Impact - **DB schema change**: βœ… (new table + unique index) - **API contract**: ❌ (no external API changes in this PR) - **Config/env**: ❌ --- ### Testing can't be performed, as in this PR we only have created the tables and not used it anywhere in the upcoming micro-prs, this will be used. however I have used it myself by making code changes, here are the screenshots. <img width="3456" height="1182" alt="Screenshot 2025-08-26 at 20 31 13" src="https://github.com/user-attachments/assets/320f6b05-74a9-44d2-ad9a-5514431e5ca2" /> <img width="3456" height="998" alt="Screenshot 2025-08-26 at 20 31 38" src="https://github.com/user-attachments/assets/123a55a4-74bd-4aa4-812b-821a0e73caa4" /> ## 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.116.0
e30842892a48ff6e4bc0e7c0a4990d3e5fc50027
e30842892a48ff6e4bc0e7c0a4990d3e5fc50027
juspay/hyperswitch
juspay__hyperswitch-9092
Bug: Remove delete_merchant call from DE
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 7d625a78396..3e41150e05a 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1220,25 +1220,6 @@ pub async fn merchant_account_delete( is_deleted = is_merchant_account_deleted && is_merchant_key_store_deleted; } - // Call to DE here - #[cfg(all(feature = "dynamic_routing", feature = "v1"))] - { - if state.conf.open_router.dynamic_routing_enabled && is_deleted { - merchant_account - .default_profile - .as_ref() - .async_map(|profile_id| { - routing::helpers::delete_decision_engine_merchant(&state, profile_id) - }) - .await - .transpose() - .map_err(|err| { - logger::error!("Failed to delete merchant in Decision Engine {err:?}"); - }) - .ok(); - } - } - let state = state.clone(); authentication::decision::spawn_tracked_job( async move {
2025-08-28T08:21:26Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description When deleting a merchant account, the code previously included a direct call to the **Decision Engine (DE)** to remove the merchant configuration (`delete_decision_engine_merchant`). This was gated behind the `dynamic_routing` and `v1` feature flags and executed synchronously within the merchant deletion flow. #### **Change** * **Removed** the in-place DE cleanup logic inside `merchant_account_delete`. * Merchant deletion in the Decision Engine will now be handled separately instead of being triggered inline. #### **Impact** * Merchant deletion continues to work as expected. * Decision Engine merchant cleanup is no longer triggered directly during merchant deletion. * Any required DE sync/cleanup should be handled through explicit decision engine flows. ## How did you test it? **Curls and Responses** merchant_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_1756372072", "locker_id": "m0010", "merchant_name": "NewAge Retailer", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "JohnTest@test.com", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "JohnTest2@test.com", "secondary_phone": "cillum do dolor id", "website": "https://www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name":"john", "last_name":"Doe" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url":"https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "parent_merchant_id":"merchant_123", "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` ``` { "merchant_id": "merchant_1756370034", "merchant_name": "NewAge Retailer", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "vPKpQFWxI6vvWeAClk6U0JQ01ueIluSMVrsUv7uiFQL2Vmgo4fp1zCW1qXRzX7p3", "redirect_to_merchant_with_http_post": false, "merchant_details": { "primary_contact_person": "John Test", "primary_phone": "sunt laborum", "primary_email": "JohnTest@test.com", "secondary_contact_person": "John Test2", "secondary_phone": "cillum do dolor id", "secondary_email": "JohnTest2@test.com", "website": "https://www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe", "origin_zip": null } }, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": "https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true, "payment_statuses_enabled": null, "refund_statuses_enabled": null, "payout_statuses_enabled": null }, "payout_routing_algorithm": null, "sub_merchants_enabled": false, "parent_merchant_id": null, "publishable_key": "pk_dev_bb568f9c214f4428b24e81ff7173b7be", "metadata": { "city": "NY", "unit": "245", "compatible_connector": null }, "locker_id": "m0010", "primary_business_details": [ { "country": "US", "business": "default" } ], "frm_routing_algorithm": null, "organization_id": "org_5pSgHUtY3PbAsrEDWkij", "is_recon_enabled": false, "default_profile": "pro_t5bthtS2CtfrpA3UjL4H", "recon_status": "not_requested", "pm_collect_link_config": null, "product_type": "orchestration", "merchant_account_type": "standard" } ``` create_sr_routing ``` curl --location 'http://localhost:8080/account/merchant_1756370034/business_profile/pro_t5bthtS2CtfrpA3UjL4H/dynamic_routing/success_based/create?enable=dynamic_connector_selection' \ --header 'Content-Type: application/json' \ --header 'api-key:****' \ --data '{ "decision_engine_configs": { "defaultLatencyThreshold": 90, "defaultBucketSize": 200, "defaultHedgingPercent": 5, "subLevelInputConfig": [ { "paymentMethodType": "card", "paymentMethod": "credit", "bucketSize": 250, "hedgingPercent": 1 } ] } }' ``` ``` { "id": "routing_usG7HRI5Ij3FoaOhOb5A", "profile_id": "pro_t5bthtS2CtfrpA3UjL4H", "name": "Success rate based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1756370043, "modified_at": 1756370043, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` activate ``` curl --location 'http://localhost:8080/routing/routing_usG7HRI5Ij3FoaOhOb5A/activate' \ --header 'Content-Type: application/json' \ --header 'api-key:****' \ --data '{}' ``` ``` { "id": "routing_usG7HRI5Ij3FoaOhOb5A", "profile_id": "pro_t5bthtS2CtfrpA3UjL4H", "name": "Success rate based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1756370043, "modified_at": 1756370043, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` delete_merchant ``` curl --location --request DELETE 'http://localhost:8080/accounts/merchant_1756370034' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` ``` { "merchant_id": "merchant_1756370034", "deleted": true } ``` delete business_profile ``` curl --location --request DELETE 'http://localhost:8080/account/merchant_1756370034/business_profile/pro_t5bthtS2CtfrpA3UjL4H' \ --header 'api-key: test_admin' ``` ```true``` <img width="1313" height="333" alt="Screenshot 2025-08-28 at 2 50 14β€―PM" src="https://github.com/user-attachments/assets/2d005743-8ccd-4592-9547-fb52adf44b64" /> Deleted from hyperswitch <img width="670" height="52" alt="Screenshot 2025-08-28 at 2 46 31β€―PM" src="https://github.com/user-attachments/assets/9412c39b-5bb6-4133-b6a2-d1f401aa070f" /> <img width="667" height="48" alt="Screenshot 2025-08-28 at 2 50 27β€―PM" src="https://github.com/user-attachments/assets/5a9da55d-d0f3-49fe-8ac5-1cc5f4d6c9e0" /> Not deleted from DE <img width="757" height="316" alt="Screenshot 2025-08-28 at 2 47 01β€―PM" src="https://github.com/user-attachments/assets/3a0a12c6-4062-48c3-8c4d-edbf85aa7a96" />
v1.116.0
26930a47e905baf647f218328e81529951d4f563
26930a47e905baf647f218328e81529951d4f563
juspay/hyperswitch
juspay__hyperswitch-9085
Bug: [FEATURE] NTID Support + googlepay & applepay mandate support ### Feature Description - Add NTID proxy support for nuvei. ( NOTE: Nuvei is not responding with NTID as of now hence we cant make ntid originated flow via nuvei to other connector. We are verifying NTID originated from other connector through nuvei. ) - Extend mandate support for googlepay and applepay. ( decrypt flow only) ### Possible Implementation Implement NTID AND wallet (GOOGLEPAY + APPLEPAY) MANDATES ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 21ac732394f..482da1feca0 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -209,9 +209,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen" } card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,worldpay,nmi,bankofamerica,wellsfargo,bamboraapac,nexixpay,novalnet,paypal,archipel" card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,worldpay,nmi,bankofamerica,wellsfargo,bamboraapac,nexixpay,novalnet,paypal,archipel" pay_later.klarna.connector_list = "adyen" -wallet.apple_pay.connector_list = "adyen,cybersource,bankofamerica,novalnet,authorizedotnet" +wallet.apple_pay.connector_list = "adyen,cybersource,bankofamerica,novalnet,nuvei,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "adyen,cybersource,bankofamerica,novalnet,authorizedotnet" +wallet.google_pay.connector_list = "adyen,cybersource,bankofamerica,novalnet,nuvei,authorizedotnet" wallet.paypal.connector_list = "adyen,novalnet" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" @@ -258,7 +258,7 @@ card.credit = { connector_list = "cybersource" } # Update Mandate sup card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card [network_transaction_id_supported_connectors] -connector_list = "adyen,archipel,cybersource,novalnet,stripe,worldpay,worldpayvantiv" +connector_list = "adyen,archipel,cybersource,novalnet,nuvei,stripe,worldpay,worldpayvantiv" [payouts] diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 853ec279f66..090520d1bab 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -209,9 +209,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen" } card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,worldpay,nmi,bankofamerica,wellsfargo,bamboraapac,nexixpay,novalnet,paypal,archipel" card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,worldpay,nmi,bankofamerica,wellsfargo,bamboraapac,nexixpay,novalnet,paypal,archipel" pay_later.klarna.connector_list = "adyen" -wallet.apple_pay.connector_list = "adyen,cybersource,bankofamerica,novalnet,authorizedotnet" +wallet.apple_pay.connector_list = "adyen,cybersource,bankofamerica,novalnet,nuvei,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "adyen,cybersource,bankofamerica,novalnet,authorizedotnet" +wallet.google_pay.connector_list = "adyen,cybersource,bankofamerica,novalnet,nuvei,authorizedotnet" wallet.paypal.connector_list = "adyen,novalnet" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" @@ -258,7 +258,7 @@ card.credit = { connector_list = "cybersource" } # Update Mandate sup card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card [network_transaction_id_supported_connectors] -connector_list = "adyen,archipel,stripe,worldpayvantiv" +connector_list = "adyen,archipel,stripe,nuvei,worldpayvantiv" [payouts] payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index dbd5e87e520..92ea9264cca 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -216,9 +216,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen" } card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,worldpay,nmi,bankofamerica,wellsfargo,bamboraapac,nexixpay,novalnet,paypal,archipel" card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,worldpay,nmi,bankofamerica,wellsfargo,bamboraapac,nexixpay,novalnet,paypal,archipel" pay_later.klarna.connector_list = "adyen" -wallet.apple_pay.connector_list = "adyen,cybersource,bankofamerica,novalnet,authorizedotnet" +wallet.apple_pay.connector_list = "adyen,cybersource,bankofamerica,novalnet,nuvei,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "adyen,cybersource,bankofamerica,novalnet,authorizedotnet" +wallet.google_pay.connector_list = "adyen,cybersource,bankofamerica,novalnet,nuvei,authorizedotnet" wallet.paypal.connector_list = "adyen,novalnet" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" @@ -265,7 +265,7 @@ card.credit = { connector_list = "cybersource" } # Update Mandate sup card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card [network_transaction_id_supported_connectors] -connector_list = "adyen,archipel,cybersource,novalnet,stripe,worldpay,worldpayvantiv" +connector_list = "adyen,archipel,cybersource,novalnet,nuvei,stripe,worldpay,worldpayvantiv" [payouts] diff --git a/config/development.toml b/config/development.toml index 1215c323628..c8da369704b 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1048,9 +1048,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,xendit,moneris,archipel,worldpayvantiv,payload" 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,xendit,moneris,archipel,worldpayvantiv,payload" pay_later.klarna.connector_list = "adyen,aci" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet,wellsfargo,worldpayvantiv" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nuvei,nexinets,novalnet,authorizedotnet,wellsfargo,worldpayvantiv" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet,wellsfargo,worldpayvantiv" +wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,nuvei,authorizedotnet,wellsfargo,worldpayvantiv" wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal,authorizedotnet" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" @@ -1073,7 +1073,7 @@ card.credit = { connector_list = "cybersource" } card.debit = { connector_list = "cybersource" } [network_transaction_id_supported_connectors] -connector_list = "adyen,archipel,cybersource,novalnet,stripe,worldpay,worldpayvantiv" +connector_list = "adyen,archipel,cybersource,novalnet,nuvei,stripe,worldpay,worldpayvantiv" [connector_request_reference_id_config] merchant_ids_send_payment_id_as_connector_request_id = [] diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei.rs b/crates/hyperswitch_connectors/src/connectors/nuvei.rs index 8fda86c4512..259495d0545 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei.rs @@ -114,7 +114,12 @@ impl ConnectorValidation for Nuvei { 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, + PaymentMethodDataType::NetworkTransactionIdAndCardDetails, + ]); is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } } @@ -709,7 +714,9 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData .response .parse_struct("NuveiPaymentsResponse") .switch()?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, @@ -1286,7 +1293,7 @@ static NUVEI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = Lazy enums::PaymentMethod::Wallet, enums::PaymentMethodType::ApplePay, PaymentMethodDetails { - mandates: enums::FeatureStatus::NotSupported, + mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, @@ -1296,7 +1303,7 @@ static NUVEI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = Lazy enums::PaymentMethod::Wallet, enums::PaymentMethodType::GooglePay, PaymentMethodDetails { - mandates: enums::FeatureStatus::NotSupported, + mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index fa9c3e4d499..e260934852e 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -1,4 +1,4 @@ -use common_enums::{enums, CaptureMethod, FutureUsage, PaymentChannel}; +use common_enums::{enums, CaptureMethod, CardNetwork, FutureUsage, PaymentChannel}; use common_types::payments::{ApplePayPaymentData, GpayTokenizationData}; use common_utils::{ crypto::{self, GenerateDigest}, @@ -14,8 +14,8 @@ use error_stack::ResultExt; use hyperswitch_domain_models::{ address::Address, payment_method_data::{ - self, ApplePayWalletData, BankRedirectData, GooglePayWalletData, PayLaterData, - PaymentMethodData, WalletData, + self, ApplePayWalletData, BankRedirectData, CardDetailsForNetworkTransactionId, + GooglePayWalletData, PayLaterData, PaymentMethodData, WalletData, }, router_data::{ AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, @@ -76,6 +76,7 @@ trait NuveiAuthorizePreprocessingCommon { fn get_related_transaction_id(&self) -> Option<String>; fn get_complete_authorize_url(&self) -> Option<String>; fn get_is_moto(&self) -> Option<bool>; + fn get_ntid(&self) -> Option<String>; fn get_connector_mandate_id(&self) -> Option<String>; fn get_return_url_required( &self, @@ -182,13 +183,18 @@ impl NuveiAuthorizePreprocessingCommon for SetupMandateRequestData { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(FutureUsage::OffSession) } + fn get_ntid(&self) -> Option<String> { + None + } } impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData { fn get_browser_info(&self) -> Option<BrowserInformation> { self.browser_info.clone() } - + fn get_ntid(&self) -> Option<String> { + self.get_optional_network_transaction_id() + } fn get_related_transaction_id(&self) -> Option<String> { self.related_transaction_id.clone() } @@ -328,6 +334,10 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsPreProcessingData { fn get_is_partial_approval(&self) -> Option<PartialApprovalFlag> { None } + + fn get_ntid(&self) -> Option<String> { + None + } } #[derive(Debug, Serialize, Default, Deserialize)] @@ -396,6 +406,7 @@ pub struct NuveiPaymentsRequest { pub url_details: Option<UrlDetails>, pub amount_details: Option<NuvieAmountDetails>, pub is_partial_approval: Option<PartialApprovalFlag>, + pub external_scheme_details: Option<ExternalSchemeDetails>, } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] @@ -886,7 +897,12 @@ struct GooglePayInfoCamelCase { card_details: Secret<String>, assurance_details: Option<GooglePayAssuranceDetailsCamelCase>, } - +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ExternalSchemeDetails { + transaction_id: Secret<String>, // This is sensitive information + brand: Option<CardNetwork>, +} #[derive(Serialize, Debug)] #[serde(rename_all = "camelCase")] struct GooglePayAssuranceDetailsCamelCase { @@ -919,176 +935,203 @@ struct ApplePayPaymentMethodCamelCase { #[serde(rename = "type")] pm_type: Secret<String>, } - -impl TryFrom<GooglePayWalletData> for NuveiPaymentsRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(gpay_data: GooglePayWalletData) -> Result<Self, Self::Error> { - match gpay_data.tokenization_data { - GpayTokenizationData::Decrypted(ref gpay_predecrypt_data) => Ok(Self { - payment_option: PaymentOption { - card: Some(Card { - brand: Some(gpay_data.info.card_network.clone()), - card_number: Some( - gpay_predecrypt_data - .application_primary_account_number - .clone(), - ), - last4_digits: Some(Secret::new( - gpay_predecrypt_data - .application_primary_account_number - .clone() - .get_last4(), - )), - expiration_month: Some(gpay_predecrypt_data.card_exp_month.clone()), - expiration_year: Some(gpay_predecrypt_data.card_exp_year.clone()), - external_token: Some(ExternalToken { - external_token_provider: ExternalTokenProvider::GooglePay, - mobile_token: None, - cryptogram: gpay_predecrypt_data.cryptogram.clone(), - eci_provider: gpay_predecrypt_data.eci_indicator.clone(), - }), - ..Default::default() +fn get_googlepay_info<F, Req>( + item: &RouterData<F, Req, PaymentsResponseData>, + gpay_data: &GooglePayWalletData, +) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> +where + Req: NuveiAuthorizePreprocessingCommon, +{ + let is_rebilling = if item.request.is_customer_initiated_mandate_payment() { + Some("0".to_string()) + } else { + None + }; + match gpay_data.tokenization_data { + GpayTokenizationData::Decrypted(ref gpay_predecrypt_data) => Ok(NuveiPaymentsRequest { + is_rebilling, + payment_option: PaymentOption { + card: Some(Card { + brand: Some(gpay_data.info.card_network.clone()), + card_number: Some( + gpay_predecrypt_data + .application_primary_account_number + .clone(), + ), + last4_digits: Some(Secret::new( + gpay_predecrypt_data + .application_primary_account_number + .clone() + .get_last4(), + )), + expiration_month: Some(gpay_predecrypt_data.card_exp_month.clone()), + expiration_year: Some(gpay_predecrypt_data.card_exp_year.clone()), + external_token: Some(ExternalToken { + external_token_provider: ExternalTokenProvider::GooglePay, + mobile_token: None, + cryptogram: gpay_predecrypt_data.cryptogram.clone(), + eci_provider: gpay_predecrypt_data.eci_indicator.clone(), }), ..Default::default() - }, + }), ..Default::default() - }), - GpayTokenizationData::Encrypted(encrypted_data) => Ok(Self { - payment_option: PaymentOption { - card: Some(Card { - external_token: Some(ExternalToken { - external_token_provider: ExternalTokenProvider::GooglePay, - - mobile_token: { - let (token_type, token) = ( - encrypted_data.token_type.clone(), - encrypted_data.token.clone(), - ); - - let google_pay: GooglePayCamelCase = GooglePayCamelCase { - pm_type: Secret::new(gpay_data.pm_type.clone()), - description: Secret::new(gpay_data.description.clone()), - info: GooglePayInfoCamelCase { - card_network: Secret::new( - gpay_data.info.card_network.clone(), - ), - card_details: Secret::new( - gpay_data.info.card_details.clone(), - ), - assurance_details: gpay_data - .info - .assurance_details - .as_ref() - .map(|details| GooglePayAssuranceDetailsCamelCase { - card_holder_authenticated: details - .card_holder_authenticated, - account_verified: details.account_verified, - }), - }, - tokenization_data: GooglePayTokenizationDataCamelCase { - token_type: token_type.into(), - token: token.into(), - }, - }; - Some(Secret::new( - google_pay.encode_to_string_of_json().change_context( - errors::ConnectorError::RequestEncodingFailed, - )?, - )) - }, - cryptogram: None, - eci_provider: None, - }), - ..Default::default() + }, + ..Default::default() + }), + GpayTokenizationData::Encrypted(ref encrypted_data) => Ok(NuveiPaymentsRequest { + is_rebilling, + payment_option: PaymentOption { + card: Some(Card { + external_token: Some(ExternalToken { + external_token_provider: ExternalTokenProvider::GooglePay, + + mobile_token: { + let (token_type, token) = ( + encrypted_data.token_type.clone(), + encrypted_data.token.clone(), + ); + + let google_pay: GooglePayCamelCase = GooglePayCamelCase { + pm_type: Secret::new(gpay_data.pm_type.clone()), + description: Secret::new(gpay_data.description.clone()), + info: GooglePayInfoCamelCase { + card_network: Secret::new(gpay_data.info.card_network.clone()), + card_details: Secret::new(gpay_data.info.card_details.clone()), + assurance_details: gpay_data + .info + .assurance_details + .as_ref() + .map(|details| GooglePayAssuranceDetailsCamelCase { + card_holder_authenticated: details + .card_holder_authenticated, + account_verified: details.account_verified, + }), + }, + tokenization_data: GooglePayTokenizationDataCamelCase { + token_type: token_type.into(), + token: token.into(), + }, + }; + Some(Secret::new( + google_pay.encode_to_string_of_json().change_context( + errors::ConnectorError::RequestEncodingFailed, + )?, + )) + }, + cryptogram: None, + eci_provider: None, }), ..Default::default() - }, + }), ..Default::default() - }), - } + }, + ..Default::default() + }), } } -impl TryFrom<ApplePayWalletData> for NuveiPaymentsRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(apple_pay_data: ApplePayWalletData) -> Result<Self, Self::Error> { - match apple_pay_data.payment_data { - ApplePayPaymentData::Decrypted(apple_pay_predecrypt_data) => Ok(Self { - payment_option: PaymentOption { - card: Some(Card { - brand:Some(apple_pay_data.payment_method.network.clone()), - card_number: Some( - apple_pay_predecrypt_data - .application_primary_account_number - .clone(), - ), - last4_digits: Some(Secret::new( - apple_pay_predecrypt_data - .application_primary_account_number - .get_last4(), - )), - expiration_month: Some( + +fn get_applepay_info<F, Req>( + item: &RouterData<F, Req, PaymentsResponseData>, + apple_pay_data: &ApplePayWalletData, +) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> +where + Req: NuveiAuthorizePreprocessingCommon, +{ + let is_rebilling = if item.request.is_customer_initiated_mandate_payment() { + Some("0".to_string()) + } else { + None + }; + match apple_pay_data.payment_data { + ApplePayPaymentData::Decrypted(ref apple_pay_predecrypt_data) => Ok(NuveiPaymentsRequest { + is_rebilling, + payment_option: PaymentOption { + card: Some(Card { + brand: Some(apple_pay_data.payment_method.network.clone()), + card_number: Some( + apple_pay_predecrypt_data + .application_primary_account_number + .clone(), + ), + last4_digits: Some(Secret::new( + apple_pay_predecrypt_data + .application_primary_account_number + .get_last4(), + )), + expiration_month: Some( + apple_pay_predecrypt_data + .application_expiration_month + .clone(), + ), + expiration_year: Some( + apple_pay_predecrypt_data + .application_expiration_year + .clone(), + ), + external_token: Some(ExternalToken { + external_token_provider: ExternalTokenProvider::ApplePay, + mobile_token: None, + cryptogram: Some( apple_pay_predecrypt_data - .application_expiration_month + .payment_data + .online_payment_cryptogram .clone(), ), - expiration_year: Some( + eci_provider: Some( apple_pay_predecrypt_data - .application_expiration_year - .clone(), + .payment_data + .eci_indicator.clone() + .ok_or_else(missing_field_err( + "payment_method_data.wallet.apple_pay.payment_data.eci_indicator", + ))?, ), - external_token: Some(ExternalToken { - external_token_provider: ExternalTokenProvider::ApplePay, - mobile_token: None, - cryptogram: Some( - apple_pay_predecrypt_data - .payment_data - .online_payment_cryptogram, - ), - eci_provider: Some( - apple_pay_predecrypt_data - .payment_data - .eci_indicator - .ok_or_else(missing_field_err("payment_method_data.wallet.apple_pay.payment_data.eci_indicator"))?, - ), - }), - ..Default::default() }), ..Default::default() - }, + }), ..Default::default() - }), - ApplePayPaymentData::Encrypted(encrypted_data) => Ok(Self { - payment_option: PaymentOption { - card: Some(Card { - external_token: Some(ExternalToken { - external_token_provider: ExternalTokenProvider::ApplePay, - mobile_token: { - let apple_pay: ApplePayCamelCase = ApplePayCamelCase { - payment_data:encrypted_data.into(), - payment_method: ApplePayPaymentMethodCamelCase { - display_name: Secret::new(apple_pay_data.payment_method.display_name.clone()), - network: Secret::new(apple_pay_data.payment_method.network.clone()), - pm_type: Secret::new(apple_pay_data.payment_method.pm_type.clone()), - }, - transaction_identifier: Secret::new(apple_pay_data.transaction_identifier.clone()), - }; - - Some(Secret::new( - apple_pay.encode_to_string_of_json().change_context( - errors::ConnectorError::RequestEncodingFailed, - )?, - )) - }, - cryptogram: None, - eci_provider: None, - }), - ..Default::default() + }, + ..Default::default() + }), + ApplePayPaymentData::Encrypted(ref encrypted_data) => Ok(NuveiPaymentsRequest { + is_rebilling, + payment_option: PaymentOption { + card: Some(Card { + external_token: Some(ExternalToken { + external_token_provider: ExternalTokenProvider::ApplePay, + mobile_token: { + let apple_pay: ApplePayCamelCase = ApplePayCamelCase { + payment_data: encrypted_data.to_string().into(), + payment_method: ApplePayPaymentMethodCamelCase { + display_name: Secret::new( + apple_pay_data.payment_method.display_name.clone(), + ), + network: Secret::new( + apple_pay_data.payment_method.network.clone(), + ), + pm_type: Secret::new( + apple_pay_data.payment_method.pm_type.clone(), + ), + }, + transaction_identifier: Secret::new( + apple_pay_data.transaction_identifier.clone(), + ), + }; + + Some(Secret::new( + apple_pay.encode_to_string_of_json().change_context( + errors::ConnectorError::RequestEncodingFailed, + )?, + )) + }, + cryptogram: None, + eci_provider: None, }), ..Default::default() - }, + }), ..Default::default() - }), - } + }, + ..Default::default() + }), } } @@ -1336,6 +1379,52 @@ where }) } +fn get_ntid_card_info<F, Req>( + router_data: &RouterData<F, Req, PaymentsResponseData>, + data: CardDetailsForNetworkTransactionId, +) -> Result<NuveiPaymentsRequest, error_stack::Report<errors::ConnectorError>> +where + Req: NuveiAuthorizePreprocessingCommon, +{ + let external_scheme_details = Some(ExternalSchemeDetails { + transaction_id: router_data + .request + .get_ntid() + .ok_or_else(missing_field_err("network_transaction_id")) + .attach_printable("Nuvei unable to find NTID for MIT")? + .into(), + brand: Some( + data.card_network + .ok_or_else(missing_field_err("recurring_details.data.card_network"))?, + ), + }); + let payment_option: PaymentOption = PaymentOption { + card: Some(Card { + card_number: Some(data.card_number), + card_holder_name: data.card_holder_name, + expiration_month: Some(data.card_exp_month), + expiration_year: Some(data.card_exp_year), + ..Default::default() // CVV should be disabled by nuvei fo + }), + redirect_url: None, + user_payment_option_id: None, + alternative_payment_method: None, + billing_address: None, + shipping_address: None, + }; + let is_rebilling = if router_data.request.is_customer_initiated_mandate_payment() { + Some("0".to_string()) + } else { + None + }; + Ok(NuveiPaymentsRequest { + external_scheme_details, + payment_option, + is_rebilling, + ..Default::default() + }) +} + impl<F, Req> TryFrom<(&RouterData<F, Req, PaymentsResponseData>, String)> for NuveiPaymentsRequest where Req: NuveiAuthorizePreprocessingCommon, @@ -1348,9 +1437,12 @@ where let request_data = match item.request.get_payment_method_data_required()?.clone() { PaymentMethodData::Card(card) => get_card_info(item, &card), PaymentMethodData::MandatePayment => Self::try_from(item), + PaymentMethodData::CardDetailsForNetworkTransactionId(data) => { + get_ntid_card_info(item, data) + } PaymentMethodData::Wallet(wallet) => match wallet { - WalletData::GooglePay(gpay_data) => Self::try_from(gpay_data), - WalletData::ApplePay(apple_pay_data) => Ok(Self::try_from(apple_pay_data)?), + WalletData::GooglePay(gpay_data) => get_googlepay_info(item, &gpay_data), + WalletData::ApplePay(apple_pay_data) => get_applepay_info(item, &apple_pay_data), WalletData::PaypalRedirect(_) => Self::foreign_try_from(( AlternativePaymentMethodType::Expresscheckout, None, @@ -1463,13 +1555,10 @@ where | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) - | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("nuvei"), - ) - .into()) - } + | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("nuvei"), + ) + .into()), }?; let currency = item.request.get_currency_required()?; let request = Self::try_from(NuveiPaymentRequestData {
2025-08-29T04:32:45Z
## 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 --> 1. Add NTID proxy support for nuvei. ( NOTE: Nuvei is not responding with NTID as of now hence we cant make ntid originated flow via nuvei to other connector. We are verifying NTID originated from other connector through nuvei. ) 2. Extend mandate support for googlepay and applepay. ( decrypt flow only) ## test ### 1. NTID Proxy flow 1. Enable `is_connector_agnostic_mit_enabled` for business profile. ```sh curl --location 'localhost:8080/account/merchant_1756365601/business_profile/pro_081OLMJnVwN9FKpv728n' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_DtdoS2OQrXtZtx2ORkcSVGmwPs6fnV73boCOqv3XkXZa4RdYAxu8MEEIzIVplGQi' \ --data '{ "is_connector_agnostic_mit_enabled":true }' ``` <details> <summary> Make a mandate payment via cybersource to get ntid </summary> ## Request ```json { "amount": 0, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "singh", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "connector": [ "cybersource" ], "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "setup_future_usage": "off_session", "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": {}, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 0, "account_name": "transaction_processing" } ] } ``` ## response ```json { "payment_id": "pay_xmji3uvqkwBFMjMBxRAZ", "merchant_id": "merchant_1756365601", "status": "processing", "amount": 0, "net_amount": 0, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "cybersource", "client_secret": "pay_xmji3uvqkwBFMjMBxRAZ_secret_LyBJlTjcQFbIqyIviNiG", "created": "2025-08-29T04:10:34.820Z", "currency": "USD", "customer_id": "singh", "customer": { "id": "singh", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": null }, "authentication_data": null }, "billing": null }, "payment_token": "token_B4GiWHRdxg3g3BjsvoWY", "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", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": [ { "sku": null, "upc": null, "brand": null, "amount": 0, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "description": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "total_amount": null, "commodity_code": null, "unit_of_measure": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null, "unit_discount_amount": null } ], "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "singh", "created_at": 1756440634, "expires": 1756444234, "secret": "epk_7eb79d3657f24ff285bd9a532dc966f3" }, "manual_retry_allowed": false, "connector_transaction_id": "7564406363016111504807", "frm_message": null, "metadata": {}, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_xmji3uvqkwBFMjMBxRAZ_1", "payment_link": null, "profile_id": "pro_Gb5wEfhtfFlPj8H5vses", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_iXmGyeq1jo6FcvXLsQ78", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-29T04:25:34.819Z", "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_channel": null, "payment_method_id": "pm_DIW13s8bZ8neb24aSnov", "network_transaction_id": "016150703802094", "payment_method_status": "inactive", "updated": "2025-08-29T04:10:37.227Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details> <details> <summary> Make a proxy call with nuvei with cybersource obtained ntid </summary> ## Request ```json { "amount": 10023, "currency": "EUR", "confirm": true, "customer_id": "nithxxinn", "return_url": "https://www.google.com", "capture_method": "automatic", "authentication_type": "no_three_ds", "description": "hellow world", "billing": { "address": { "zip": "560095", "country": "US", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" } }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "hello@gmail.com", "payment_method": "card", "payment_method_type": "credit", "off_session": true, "recurring_details": { "type": "network_transaction_id_and_card_details", "data": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_network":"VISA", "network_transaction_id": "016150703802094" } } } ``` ## Response ```json { "payment_id": "pay_75VJuP2CMXo3Z43zThif", "merchant_id": "merchant_1756365601", "status": "succeeded", "amount": 10023, "net_amount": 10023, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10023, "connector": "nuvei", "client_secret": "pay_75VJuP2CMXo3Z43zThif_secret_rHK1wcFimQTTTjwb6A72", "created": "2025-08-29T04:17:33.772Z", "currency": "EUR", "customer_id": null, "customer": null, "description": "hellow world", "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": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nithxxinn", "created_at": 1756441053, "expires": 1756444653, "secret": "epk_9107d76964ea44bb821a5a44eeabf189" }, "manual_retry_allowed": false, "connector_transaction_id": "7110000000016800600", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "8321086111", "payment_link": null, "profile_id": "pro_Gb5wEfhtfFlPj8H5vses", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_RFiJ87uP0hCqNImMBrZc", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-29T04:32:33.772Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-29T04:17:35.842Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details> ### 2. NTID confirm via nuvei using payment token <details> <summary> Create a on session payment via cybersource</summary> ## Request ```json { "amount": 390, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "singh", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "connector": [ "cybersource" ], "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "setup_future_usage": "on_session", "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": {}, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 0, "account_name": "transaction_processing" } ] } ``` ## Response ```json { "payment_id": "pay_1ImanuhWyquBc95H6hns", "merchant_id": "merchant_1756365601", "status": "requires_confirmation", "amount": 390, "net_amount": 390, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_1ImanuhWyquBc95H6hns_secret_llGkXJVaZI2TYZHvHI7v", "created": "2025-08-29T05:48:04.092Z", "currency": "USD", "customer_id": "singh", "customer": { "id": "singh", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_oq7VkgN5Ao3OAXnX190c", "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", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": [ { "sku": null, "upc": null, "brand": null, "amount": 0, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "description": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "total_amount": null, "commodity_code": null, "unit_of_measure": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null, "unit_discount_amount": null } ], "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "singh", "created_at": 1756446484, "expires": 1756450084, "secret": "epk_607f5a2355114e88b1e75523be174604" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": {}, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_Gb5wEfhtfFlPj8H5vses", "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-08-29T06:03:04.092Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-29T05:48:04.118Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details> <details> <summary> Confirm via nuvei passing the payment token </summary> ## Request ```sh curl --location --globoff '{{baseUrl}}/payments/{{payment_id}}/confirm' \ --header 'api-key: api-key' \ --header 'Content-Type: application/json' \ --data '{ "payment_method": "card", "routing": { "type": "single", "data": { "connector": "nuvei", "merchant_connector_id": "mca_RFiJ87uP0hCqNImMBrZc" } }, "payment_token": "token_dWdH51U5LEGh7XA1qntS" }' ``` ## Response ```json { "payment_id": "pay_1ImanuhWyquBc95H6hns", "merchant_id": "merchant_1756365601", "status": "succeeded", "amount": 390, "net_amount": 390, "shipping_cost": null, "amount_capturable": 0, "amount_received": 390, "connector": "nuvei", "client_secret": "pay_1ImanuhWyquBc95H6hns_secret_llGkXJVaZI2TYZHvHI7v", "created": "2025-08-29T05:48:04.092Z", "currency": "USD", "customer_id": "singh", "customer": { "id": "singh", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "avs_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "challengePreferenceReason": "12" } }, "billing": null }, "payment_token": "token_oq7VkgN5Ao3OAXnX190c", "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", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": [ { "sku": null, "upc": null, "brand": null, "amount": 0, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "description": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "total_amount": null, "commodity_code": null, "unit_of_measure": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null, "unit_discount_amount": null } ], "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7110000000016803027", "frm_message": null, "metadata": {}, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8321797111", "payment_link": null, "profile_id": "pro_Gb5wEfhtfFlPj8H5vses", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_RFiJ87uP0hCqNImMBrZc", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-29T06:03:04.092Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-29T05:48:19.225Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details> ### 3. Google pay mandates <details> <summary>Google pay Mandates </summary> ## Googlepay Mandate Request ```json { "amount": 12, "currency": "EUR", "confirm": true, "customer_id": "nithxxinn", "return_url": "https://www.google.com", "capture_method": "automatic", "payment_method": "wallet", "payment_method_type": "google_pay", "authentication_type": "no_three_ds", "description": "hellow world", "customer_acceptance": { "acceptance_type": "online", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, // "order_tax_amount": 100, "setup_future_usage": "off_session", "billing": { "address": { "zip": "560095", "country": "UA", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" }, "email":"test@gmail.com" }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "hello@gmail.com", "payment_method_data": { "wallet": { "google_pay": { "type": "CARD", "tokenization_data": { "application_primary_account_number": "4761*********1390", "card_exp_month": "12", "card_exp_year": "25", "cryptogram": "ejJ******************U=", "eci_indicator": "5" }, "info": { "card_details": "Discover 9319", "card_network": "VISA" }, "description": "something" } } } } ``` ## Response ```json { "payment_id": "pay_iywIHCV5A8QA4mtOWyGt", "merchant_id": "merchant_1756365601", "status": "succeeded", "amount": 0, "net_amount": 0, "shipping_cost": null, "amount_capturable": 0, "amount_received": 0, "connector": "nuvei", "client_secret": "pay_iywIHCV5A8QA4mtOWyGt_secret_p1YwZ5CEGkcNI5Gb07m1", "created": "2025-08-29T05:53:15.386Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "hello@gmail.com", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": { "google_pay": { "last4": "Discover 9319", "card_network": "VISA", "type": "CARD" } }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "UA", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": "test@gmail.com" }, "order_details": null, "email": "hello@gmail.com", "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "google_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nithxxinn", "created_at": 1756446795, "expires": 1756450395, "secret": "epk_56c83dfed43e4766bdc0b4de08459f5b" }, "manual_retry_allowed": false, "connector_transaction_id": "7110000000016803203", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8321860111", "payment_link": null, "profile_id": "pro_Gb5wEfhtfFlPj8H5vses", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_RFiJ87uP0hCqNImMBrZc", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-29T06:08:15.386Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": "pm_jovQAOvn8XLwQg9OunFi", "network_transaction_id": null, "payment_method_status": "active", "updated": "2025-08-29T05:53:17.641Z", "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": "2117920111", "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` ## Mandate request using payment_method_id ```json { "amount": 333, "currency": "EUR", "customer_id": "nithxxinn", "confirm": true, "off_session": true, "recurring_details": { "type": "payment_method_id", "data": "{{payment_method_id}}"//pass the payment method id here }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" } } ``` ## Mandate Response ```JSON { "payment_id": "pay_QuQhI84yF81WPOAlV0LU", "merchant_id": "merchant_1756365601", "status": "succeeded", "amount": 333, "net_amount": 333, "shipping_cost": null, "amount_capturable": 0, "amount_received": 333, "connector": "nuvei", "client_secret": "pay_QuQhI84yF81WPOAlV0LU_secret_wtlIXP9sC20TnmhOQPUv", "created": "2025-08-29T05:54:22.157Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "hello@gmail.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": null, "payment_method": "wallet", "payment_method_data": { "wallet": { "google_pay": { "last4": "Discover 9319", "card_network": "VISA", "type": "CARD" } }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "hello@gmail.com", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "google_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nithxxinn", "created_at": 1756446862, "expires": 1756450462, "secret": "epk_ed76e2ce25ec45c5959e2219bfc2c686" }, "manual_retry_allowed": false, "connector_transaction_id": "7110000000016803225", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8321866111", "payment_link": null, "profile_id": "pro_Gb5wEfhtfFlPj8H5vses", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_RFiJ87uP0hCqNImMBrZc", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-29T06:09:22.157Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": "pm_jovQAOvn8XLwQg9OunFi", "network_transaction_id": null, "payment_method_status": "active", "updated": "2025-08-29T05:54:24.044Z", "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": "2117920111", "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details> ### 4. Applepay mandate <details> <summary> Apple pay mandates </summary> ## applepay mandate request ```json { "amount": 1, "currency": "EUR", "confirm": true, // "order_tax_amount": 100, // "setup_future_usage": "off_session", // "payment_type":"setup_mandate", "customer_acceptance": { "acceptance_type": "online", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, // "order_tax_amount": 100, "setup_future_usage": "off_session", "customer_id": "nithxxinn", "return_url": "https://www.google.com", "capture_method": "automatic", "payment_method": "wallet", "payment_method_type": "apple_pay", "authentication_type": "no_three_ds", "description": "hellow world", "billing": { "address": { "zip": "560095", "country": "US", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" }, "email": "nithingowdan77@gmail.com" }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "hello@gmail.com", "payment_method_data": { "wallet": { "apple_pay": { "payment_data": { "application_primary_account_number": "42*****2", "application_expiration_month": "09", "application_expiration_year": "30", "application_brand": "VISA", "payment_data": { "online_payment_cryptogram": "Ar******A", "eci_indicator": "7" } }, "payment_method": { "display_name": "Discover 9319", "network": "VISA", "type": "debit" }, "transaction_identifier": "c635c5b3af900d*******ee65ec7afd988a678194751" } } } } ``` ## Response ```json { "payment_id": "pay_m3H9lmnjHemVrTDl86Ra", "merchant_id": "merchant_1756365601", "status": "succeeded", "amount": 1, "net_amount": 1, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1, "connector": "nuvei", "client_secret": "pay_m3H9lmnjHemVrTDl86Ra_secret_0nQUY9G0znF1u8ZghnO0", "created": "2025-08-29T05:59:23.232Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "hello@gmail.com", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": { "apple_pay": { "last4": "9319", "card_network": "VISA", "type": "debit" } }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": "nithingowdan77@gmail.com" }, "order_details": null, "email": "hello@gmail.com", "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "apple_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nithxxinn", "created_at": 1756447163, "expires": 1756450763, "secret": "epk_ff4001bc18034075a9ea2c1cea803978" }, "manual_retry_allowed": false, "connector_transaction_id": "7110000000016803352", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8321903111", "payment_link": null, "profile_id": "pro_Gb5wEfhtfFlPj8H5vses", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_RFiJ87uP0hCqNImMBrZc", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-29T06:14:23.232Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": "pm_ojHZfjBQMQscy9fSih5M", "network_transaction_id": null, "payment_method_status": "active", "updated": "2025-08-29T05:59:29.451Z", "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": "2109690111", "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` ## MIT using payment method id ### Request ```json { "amount": 333, "currency": "EUR", "customer_id": "nithxxinn", "confirm": true, "off_session": true, "recurring_details": { "type": "payment_method_id", "data": "{{payment_method_id}}"//pass the payment method id here }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" } } ``` ### Response ```json { "payment_id": "pay_V80VZo4t4Cimc1AjRECd", "merchant_id": "merchant_1756365601", "status": "succeeded", "amount": 333, "net_amount": 333, "shipping_cost": null, "amount_capturable": 0, "amount_received": 333, "connector": "nuvei", "client_secret": "pay_V80VZo4t4Cimc1AjRECd_secret_8H3jqd3Fl0Wa6qVrxocf", "created": "2025-08-29T06:01:47.718Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "hello@gmail.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": null, "payment_method": "wallet", "payment_method_data": { "wallet": { "apple_pay": { "last4": "9319", "card_network": "VISA", "type": "debit" } }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "hello@gmail.com", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "apple_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nithxxinn", "created_at": 1756447307, "expires": 1756450907, "secret": "epk_fcc84a432dec4a869b1cac1e7a034147" }, "manual_retry_allowed": false, "connector_transaction_id": "7110000000016803458", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8321949111", "payment_link": null, "profile_id": "pro_Gb5wEfhtfFlPj8H5vses", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_RFiJ87uP0hCqNImMBrZc", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-29T06:16:47.718Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": "pm_ojHZfjBQMQscy9fSih5M", "network_transaction_id": null, "payment_method_status": "active", "updated": "2025-08-29T06:01:52.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": "2109690111", "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details>
v1.116.0
9f0cd51cabb281de82b00734b532fea3cf6205fe
9f0cd51cabb281de82b00734b532fea3cf6205fe
juspay/hyperswitch
juspay__hyperswitch-9078
Bug: (connector): [Netcetera] Fix message_extension field in Netcetera Response ### Bug Description Currently we are not recieving field **message_extension** in Netcetera's authentication response since the struct is incorrectly declared in the transformers file. **Current structure** ``` NetceteraAuthenticationSuccessResponse{ .... authentication_request: { message_extension: Option<serde_json::Value>, .... } ... } ``` **Correct structure** ``` NetceteraAuthenticationSuccessResponse{ .... authentication_response: { message_extension: Option<serde_json::Value>, .... } ... } ``` ### Expected Behavior **Correct structure** ``` NetceteraAuthenticationSuccessResponse{ .... authentication_response: { message_extension: Option<serde_json::Value>, .... } ... } ``` we should be able to recieve message_extension field for CartesBacaires 3ds authentication payments via Cybersource ### Actual Behavior **Current structure** ``` NetceteraAuthenticationSuccessResponse{ .... authentication_request: { message_extension: Option<serde_json::Value>, .... } ... } ``` we are not able to currently recieve message_extension field for CartesBacaires 3ds authentication payments via Cybersource ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs index 7427cd8cd05..0c12d7415c3 100644 --- a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs @@ -170,9 +170,9 @@ impl }); let message_extension = response - .authentication_request + .authentication_response + .message_extension .as_ref() - .and_then(|req| req.message_extension.as_ref()) .and_then(|v| match serde_json::to_value(v) { Ok(val) => Some(Secret::new(val)), Err(e) => { @@ -686,7 +686,6 @@ pub struct NetceteraAuthenticationFailureResponse { pub struct AuthenticationRequest { #[serde(rename = "threeDSRequestorChallengeInd")] pub three_ds_requestor_challenge_ind: Option<ThreedsRequestorChallengeInd>, - pub message_extension: Option<serde_json::Value>, } #[derive(Debug, Serialize, Deserialize)] @@ -708,6 +707,7 @@ pub struct AuthenticationResponse { pub ds_trans_id: Option<String>, pub acs_signed_content: Option<String>, pub trans_status_reason: Option<String>, + pub message_extension: Option<serde_json::Value>, } #[derive(Debug, Deserialize, Serialize, Clone)]
2025-08-28T11:21:17Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [X] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR introduces the following struct fix for netcetera authentication response since `message_extension` is recieved in Netcetera's authentication response ARes and not in AReq. **Current structure** ``` NetceteraAuthenticationSuccessResponse{ .... authentication_request: { message_extension: Option<serde_json::Value>, .... } ... } ``` **Correct structure** ``` NetceteraAuthenticationSuccessResponse{ .... authentication_response: { message_extension: Option<serde_json::Value>, .... } ... } ``` [Ref](https://docs.3dsecure.io/3dsv2/specification_231.html#attr-ARes-messageExtension) - 3dsecure.io docs highlights **message_extension**'s correct placement i.e ARes. Adding reference to 3dsecure.io docs since Netcetera documentation is not super clear. ### 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)? --> `message_extension` field for Netcetera's authentication response is only available in prod ## 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.116.0
26930a47e905baf647f218328e81529951d4f563
26930a47e905baf647f218328e81529951d4f563
juspay/hyperswitch
juspay__hyperswitch-9072
Bug: [BUG] Additional amount gets added again during incremental authorization ### Bug Description Additional amount gets added again during incremental authorization ### Expected Behavior Additional amount should get added once only during payments-create call ### Actual Behavior Additional amount gets added again during incremental authorization ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 4d1ae8bb920..c1ed78b5773 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -1089,6 +1089,10 @@ impl NetAmount { + self.tax_on_surcharge.unwrap_or_default() } + pub fn get_additional_amount(&self) -> MinorUnit { + self.get_total_amount() - self.get_order_amount() + } + pub fn set_order_amount(&mut self, order_amount: MinorUnit) { self.order_amount = order_amount; } diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 830186eeaad..a4ef1bdac82 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -421,7 +421,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu Some( storage::PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::new( - incremental_authorization_details.total_amount, + // Internally, `NetAmount` is computed as (order_amount + additional_amount), so we subtract here to avoid double-counting. + incremental_authorization_details.total_amount - payment_data.payment_attempt.net_amount.get_additional_amount(), None, None, None, @@ -432,7 +433,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu ), Some( storage::PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { - amount: incremental_authorization_details.total_amount, + amount: incremental_authorization_details.total_amount - payment_data.payment_attempt.net_amount.get_additional_amount(), }, ), )
2025-08-27T16:11:09Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/9072) ## Description <!-- Describe your changes in detail --> Fixed net_amount on Incremental Authorization Update. Additional amount gets added again during incremental authorization. Additional amount should get added once only during payments-create call ### 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 1. Payments - Create Call (with Shipping Cost): Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_LrNckNcOPFASn7VpEoEhyyiRB48cyo9t1csS7YCdWl3jXZgegV7BLdyIZi0ZrS6Z' \ --data-raw ' { "amount": 6500, "shipping_cost": 100, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "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": "2025-07-25T11:46:12Z" }, "request_incremental_authorization": true } ' ``` Response: ``` { "payment_id": "pay_upjMvDYu9WjajAzyRlXo", "merchant_id": "merchant_1756308166", "status": "requires_capture", "amount": 6500, "net_amount": 6600, "shipping_cost": 100, "amount_capturable": 6600, "amount_received": null, "connector": "stripe", "client_secret": "pay_upjMvDYu9WjajAzyRlXo_secret_1G2kKy9iAhTmwNQa5k93", "created": "2025-08-27T15:47:52.956Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1756309672, "expires": 1756313272, "secret": "epk_4f4fb7f0092d42289f9cd9bc7eadeff2" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3S0lZlE9cSvqiivY0lSuXawj", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pi_3S0lZlE9cSvqiivY0lSuXawj", "payment_link": null, "profile_id": "pro_fW5H3dRoivQsyI9e3xgm", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bLPtb7IYMPK6HwBo25Sf", "incremental_authorization_allowed": true, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-27T16:02:52.956Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": "561027010586901", "payment_method_status": null, "updated": "2025-08-27T15:47:53.993Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` 2. Incremental Authorization Request: ``` curl --location 'http://localhost:8080/payments/pay_upjMvDYu9WjajAzyRlXo/incremental_authorization' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_LrNckNcOPFASn7VpEoEhyyiRB48cyo9t1csS7YCdWl3jXZgegV7BLdyIZi0ZrS6Z' \ --data '{ "amount": 6700 }' ``` Response: ``` { "payment_id": "pay_upjMvDYu9WjajAzyRlXo", "merchant_id": "merchant_1756308166", "status": "requires_capture", "amount": 6600, "net_amount": 6700, "shipping_cost": 100, "amount_capturable": 6700, "amount_received": null, "connector": "stripe", "client_secret": "pay_upjMvDYu9WjajAzyRlXo_secret_wd5Y8MKQvldzNS07lJg9", "created": "2025-08-27T16:09:46.666Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": 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": "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": "pi_3S0luxE9cSvqiivY19yeqwRn", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pi_3S0luxE9cSvqiivY19yeqwRn", "payment_link": null, "profile_id": "pro_fW5H3dRoivQsyI9e3xgm", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bLPtb7IYMPK6HwBo25Sf", "incremental_authorization_allowed": true, "authorization_count": 1, "incremental_authorizations": [ { "authorization_id": "auth_sz8ljqdlMKe2dckB5YzK_1", "amount": 6700, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6600 } ], "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-27T16:24:46.666Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": "561027010586901", "payment_method_status": null, "updated": "2025-08-27T16:09:50.595Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": 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.116.0
cf64d2a9dcef422e7d080e21a7e8644694337a51
cf64d2a9dcef422e7d080e21a7e8644694337a51
juspay/hyperswitch
juspay__hyperswitch-9074
Bug: Batch update payment methods API We need to make update payment methods API which can update the fields of the records in payment methods table. It will consume a CSV file which will have batch update entries. Currently it should only update connector_mandate_id, network_transaction_id and mandate_status.
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 135e0ddc248..5803a5c6876 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -285,6 +285,14 @@ pub struct PaymentMethodMigrateResponse { pub network_transaction_id_migrated: Option<bool>, } +#[derive(Debug, serde::Serialize, ToSchema)] +pub struct PaymentMethodRecordUpdateResponse { + pub payment_method_id: String, + pub status: common_enums::PaymentMethodStatus, + pub network_transaction_id: Option<String>, + pub connector_mandate_details: Option<pii::SecretSerdeValue>, +} + #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentsMandateReference( pub HashMap<id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>, @@ -2640,6 +2648,28 @@ pub struct PaymentMethodRecord { pub network_token_requestor_ref_id: Option<String>, } +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +pub struct UpdatePaymentMethodRecord { + pub payment_method_id: String, + pub status: Option<common_enums::PaymentMethodStatus>, + pub network_transaction_id: Option<String>, + pub line_number: Option<i64>, + pub payment_instrument_id: Option<masking::Secret<String>>, + pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, +} + +#[derive(Debug, serde::Serialize)] +pub struct PaymentMethodUpdateResponse { + pub payment_method_id: String, + pub status: Option<common_enums::PaymentMethodStatus>, + pub network_transaction_id: Option<String>, + pub connector_mandate_details: Option<pii::SecretSerdeValue>, + pub update_status: UpdateStatus, + #[serde(skip_serializing_if = "Option::is_none")] + pub update_error: Option<String>, + pub line_number: Option<i64>, +} + #[derive(Debug, Default, serde::Serialize)] pub struct PaymentMethodMigrationResponse { pub line_number: Option<i64>, @@ -2667,6 +2697,13 @@ pub enum MigrationStatus { Failed, } +#[derive(Debug, Default, serde::Serialize)] +pub enum UpdateStatus { + Success, + #[default] + Failed, +} + impl PaymentMethodRecord { fn create_address(&self) -> Option<payments::AddressDetails> { if self.billing_address_first_name.is_some() @@ -2725,6 +2762,12 @@ type PaymentMethodMigrationResponseType = ( PaymentMethodRecord, ); +#[cfg(feature = "v1")] +type PaymentMethodUpdateResponseType = ( + Result<PaymentMethodRecordUpdateResponse, String>, + UpdatePaymentMethodRecord, +); + #[cfg(feature = "v1")] impl From<PaymentMethodMigrationResponseType> for PaymentMethodMigrationResponse { fn from((response, record): PaymentMethodMigrationResponseType) -> Self { @@ -2755,6 +2798,32 @@ impl From<PaymentMethodMigrationResponseType> for PaymentMethodMigrationResponse } } +#[cfg(feature = "v1")] +impl From<PaymentMethodUpdateResponseType> for PaymentMethodUpdateResponse { + fn from((response, record): PaymentMethodUpdateResponseType) -> Self { + match response { + Ok(res) => Self { + payment_method_id: res.payment_method_id, + status: Some(res.status), + network_transaction_id: res.network_transaction_id, + connector_mandate_details: res.connector_mandate_details, + update_status: UpdateStatus::Success, + update_error: None, + line_number: record.line_number, + }, + Err(e) => Self { + payment_method_id: record.payment_method_id, + status: record.status, + network_transaction_id: record.network_transaction_id, + connector_mandate_details: None, + update_status: UpdateStatus::Failed, + update_error: Some(e), + line_number: record.line_number, + }, + } + } +} + impl TryFrom<( &PaymentMethodRecord, diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index 79d6865b727..34fff64e7d9 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -245,6 +245,11 @@ pub enum PaymentMethodUpdate { connector_mandate_details: Option<pii::SecretSerdeValue>, network_transaction_id: Option<Secret<String>>, }, + ConnectorNetworkTransactionIdStatusAndMandateDetailsUpdate { + connector_mandate_details: Option<pii::SecretSerdeValue>, + network_transaction_id: Option<String>, + status: Option<storage_enums::PaymentMethodStatus>, + }, } #[cfg(feature = "v2")] @@ -673,6 +678,29 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { network_token_payment_method_data: None, scheme: None, }, + PaymentMethodUpdate::ConnectorNetworkTransactionIdStatusAndMandateDetailsUpdate { + connector_mandate_details, + network_transaction_id, + status, + } => Self { + metadata: None, + payment_method_data: None, + last_used_at: None, + status, + locker_id: None, + network_token_requestor_reference_id: None, + payment_method: None, + connector_mandate_details: connector_mandate_details + .map(|mandate_details| mandate_details.expose()), + network_transaction_id, + updated_by: None, + payment_method_issuer: None, + payment_method_type: None, + last_modified: common_utils::date_time::now(), + network_token_locker_id: None, + network_token_payment_method_data: None, + scheme: None, + }, } } } diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs index 0fa3d5b4e07..003998d9ccc 100644 --- a/crates/hyperswitch_domain_models/src/payment_methods.rs +++ b/crates/hyperswitch_domain_models/src/payment_methods.rs @@ -12,7 +12,7 @@ use common_utils::{ id_type, pii, type_name, types::keymanager, }; -use diesel_models::{enums as storage_enums, PaymentMethodUpdate}; +pub use diesel_models::{enums as storage_enums, PaymentMethodUpdate}; use error_stack::ResultExt; #[cfg(feature = "v1")] use masking::ExposeInterface; diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 3a072e12cc7..06622842281 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -1,4 +1,5 @@ pub mod cards; +pub mod migration; pub mod network_tokenization; pub mod surcharge_decision_configs; #[cfg(feature = "v1")] diff --git a/crates/router/src/core/payment_methods/migration.rs b/crates/router/src/core/payment_methods/migration.rs new file mode 100644 index 00000000000..d802e432ec1 --- /dev/null +++ b/crates/router/src/core/payment_methods/migration.rs @@ -0,0 +1,257 @@ +use actix_multipart::form::{self, bytes, text}; +use api_models::payment_methods as pm_api; +use common_utils::{errors::CustomResult, id_type}; +use csv::Reader; +use error_stack::ResultExt; +use hyperswitch_domain_models::{ + api::ApplicationResponse, errors::api_error_response as errors, merchant_context, + payment_methods::PaymentMethodUpdate, +}; +use masking::PeekInterface; +use rdkafka::message::ToBytes; +use router_env::logger; + +use crate::{core::errors::StorageErrorExt, routes::SessionState}; + +type PmMigrationResult<T> = CustomResult<ApplicationResponse<T>, errors::ApiErrorResponse>; + +#[cfg(feature = "v1")] +pub async fn update_payment_methods( + state: &SessionState, + payment_methods: Vec<pm_api::UpdatePaymentMethodRecord>, + merchant_id: &id_type::MerchantId, + merchant_context: &merchant_context::MerchantContext, +) -> PmMigrationResult<Vec<pm_api::PaymentMethodUpdateResponse>> { + let mut result = Vec::with_capacity(payment_methods.len()); + + for record in payment_methods { + let update_res = + update_payment_method_record(state, record.clone(), merchant_id, merchant_context) + .await; + let res = match update_res { + Ok(ApplicationResponse::Json(response)) => Ok(response), + Err(e) => Err(e.to_string()), + _ => Err("Failed to update payment method".to_string()), + }; + + result.push(pm_api::PaymentMethodUpdateResponse::from((res, record))); + } + Ok(ApplicationResponse::Json(result)) +} + +#[cfg(feature = "v1")] +pub async fn update_payment_method_record( + state: &SessionState, + req: pm_api::UpdatePaymentMethodRecord, + merchant_id: &id_type::MerchantId, + merchant_context: &merchant_context::MerchantContext, +) -> CustomResult< + ApplicationResponse<pm_api::PaymentMethodRecordUpdateResponse>, + errors::ApiErrorResponse, +> { + use std::collections::HashMap; + + use common_enums::enums; + use common_utils::pii; + use hyperswitch_domain_models::mandates::{ + CommonMandateReference, PaymentsMandateReference, PaymentsMandateReferenceRecord, + PayoutsMandateReference, PayoutsMandateReferenceRecord, + }; + + let db = &*state.store; + let payment_method_id = req.payment_method_id.clone(); + let network_transaction_id = req.network_transaction_id.clone(); + let status = req.status; + + let payment_method = db + .find_payment_method( + &state.into(), + merchant_context.get_merchant_key_store(), + &payment_method_id, + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + + if payment_method.merchant_id != *merchant_id { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Merchant ID in the request does not match the Merchant ID in the payment method record.".to_string(), + }.into()); + } + + // Process mandate details when both payment_instrument_id and merchant_connector_id are present + let pm_update = match (&req.payment_instrument_id, &req.merchant_connector_id) { + (Some(payment_instrument_id), Some(merchant_connector_id)) => { + let mandate_details = payment_method + .get_common_mandate_reference() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize to Payment Mandate Reference ")?; + + let mca = db + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &state.into(), + merchant_context.get_merchant_account().get_id(), + merchant_connector_id, + merchant_context.get_merchant_key_store(), + ) + .await + .to_not_found_response( + errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: merchant_connector_id.get_string_repr().to_string(), + }, + )?; + + let updated_connector_mandate_details = match mca.connector_type { + enums::ConnectorType::PayoutProcessor => { + // Handle PayoutsMandateReference + let mut existing_payouts_mandate = mandate_details + .payouts + .unwrap_or_else(|| PayoutsMandateReference(HashMap::new())); + + // Create new payout mandate record + let new_payout_record = PayoutsMandateReferenceRecord { + transfer_method_id: Some(payment_instrument_id.peek().to_string()), + }; + + // Check if record exists for this merchant_connector_id + if let Some(existing_record) = + existing_payouts_mandate.0.get_mut(merchant_connector_id) + { + if let Some(transfer_method_id) = &new_payout_record.transfer_method_id { + existing_record.transfer_method_id = Some(transfer_method_id.clone()); + } + } else { + // Insert new record in connector_mandate_details + existing_payouts_mandate + .0 + .insert(merchant_connector_id.clone(), new_payout_record); + } + + // Create updated CommonMandateReference preserving payments section + CommonMandateReference { + payments: mandate_details.payments, + payouts: Some(existing_payouts_mandate), + } + } + _ => { + // Handle PaymentsMandateReference + let mut existing_payments_mandate = mandate_details + .payments + .unwrap_or_else(|| PaymentsMandateReference(HashMap::new())); + + // Check if record exists for this merchant_connector_id + if let Some(existing_record) = + existing_payments_mandate.0.get_mut(merchant_connector_id) + { + existing_record.connector_mandate_id = + payment_instrument_id.peek().to_string(); + } else { + // Insert new record in connector_mandate_details + existing_payments_mandate.0.insert( + merchant_connector_id.clone(), + PaymentsMandateReferenceRecord { + connector_mandate_id: payment_instrument_id.peek().to_string(), + payment_method_type: None, + original_payment_authorized_amount: None, + original_payment_authorized_currency: None, + mandate_metadata: None, + connector_mandate_status: None, + connector_mandate_request_reference_id: None, + }, + ); + } + + // Create updated CommonMandateReference preserving payouts section + CommonMandateReference { + payments: Some(existing_payments_mandate), + payouts: mandate_details.payouts, + } + } + }; + + let connector_mandate_details_value = updated_connector_mandate_details + .get_mandate_details_value() + .map_err(|err| { + logger::error!("Failed to get get_mandate_details_value : {:?}", err); + errors::ApiErrorResponse::MandateUpdateFailed + })?; + + PaymentMethodUpdate::ConnectorNetworkTransactionIdStatusAndMandateDetailsUpdate { + connector_mandate_details: Some(pii::SecretSerdeValue::new( + connector_mandate_details_value, + )), + network_transaction_id, + status, + } + } + _ => { + // Update only network_transaction_id and status + PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { + network_transaction_id, + status, + } + } + }; + + let response = db + .update_payment_method( + &state.into(), + merchant_context.get_merchant_key_store(), + payment_method, + pm_update, + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable(format!( + "Failed to update payment method for existing pm_id: {payment_method_id:?} in db", + ))?; + + logger::debug!("Payment method updated in db"); + + Ok(ApplicationResponse::Json( + pm_api::PaymentMethodRecordUpdateResponse { + payment_method_id: response.payment_method_id, + status: response.status, + network_transaction_id: response.network_transaction_id, + connector_mandate_details: response + .connector_mandate_details + .map(pii::SecretSerdeValue::new), + }, + )) +} + +#[derive(Debug, form::MultipartForm)] +pub struct PaymentMethodsUpdateForm { + #[multipart(limit = "1MB")] + pub file: bytes::Bytes, + + pub merchant_id: text::Text<id_type::MerchantId>, +} + +fn parse_update_csv(data: &[u8]) -> csv::Result<Vec<pm_api::UpdatePaymentMethodRecord>> { + let mut csv_reader = Reader::from_reader(data); + let mut records = Vec::new(); + let mut id_counter = 0; + for result in csv_reader.deserialize() { + let mut record: pm_api::UpdatePaymentMethodRecord = result?; + id_counter += 1; + record.line_number = Some(id_counter); + records.push(record); + } + Ok(records) +} + +type UpdateValidationResult = + Result<(id_type::MerchantId, Vec<pm_api::UpdatePaymentMethodRecord>), errors::ApiErrorResponse>; + +impl PaymentMethodsUpdateForm { + pub fn validate_and_get_payment_method_records(self) -> UpdateValidationResult { + let records = parse_update_csv(self.file.data.to_bytes()).map_err(|e| { + errors::ApiErrorResponse::PreconditionFailed { + message: e.to_string(), + } + })?; + Ok((self.merchant_id.clone(), records)) + } +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 690a4337351..c48fcd1fec1 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1429,6 +1429,10 @@ impl PaymentMethods { web::resource("/migrate-batch") .route(web::post().to(payment_methods::migrate_payment_methods)), ) + .service( + web::resource("/update-batch") + .route(web::post().to(payment_methods::update_payment_methods)), + ) .service( web::resource("/tokenize-card") .route(web::post().to(payment_methods::tokenize_card_api)), diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 27b66e5bb54..0c42909b457 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -121,6 +121,7 @@ impl From<Flow> for ApiIdentifier { Flow::PaymentMethodsCreate | Flow::PaymentMethodsMigrate + | Flow::PaymentMethodsBatchUpdate | Flow::PaymentMethodsList | Flow::CustomerPaymentMethodsList | Flow::GetPaymentMethodTokenData diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 08b84e40977..7aa1ba949ba 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -21,7 +21,7 @@ use crate::{ core::{ api_locking, errors::{self, utils::StorageErrorExt}, - payment_methods::{self as payment_methods_routes, cards}, + payment_methods::{self as payment_methods_routes, cards, migration as update_migration}, }, services::{self, api, authentication as auth, authorization::permissions::Permission}, types::{ @@ -413,6 +413,46 @@ pub async fn migrate_payment_methods( .await } +#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] +#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsBatchUpdate))] +pub async fn update_payment_methods( + state: web::Data<AppState>, + req: HttpRequest, + MultipartForm(form): MultipartForm<update_migration::PaymentMethodsUpdateForm>, +) -> HttpResponse { + let flow = Flow::PaymentMethodsBatchUpdate; + let (merchant_id, records) = match form.validate_and_get_payment_method_records() { + Ok((merchant_id, records)) => (merchant_id, records), + Err(e) => return api::log_and_return_error_response(e.into()), + }; + Box::pin(api::server_wrap( + flow, + state, + &req, + records, + |state, _, req, _| { + let merchant_id = merchant_id.clone(); + async move { + let (key_store, merchant_account) = + get_merchant_account(&state, &merchant_id).await?; + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( + domain::Context(merchant_account.clone(), key_store.clone()), + )); + Box::pin(update_migration::update_payment_methods( + &state, + req, + &merchant_id, + &merchant_context, + )) + .await + } + }, + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSave))] pub async fn save_payment_method_api( diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index b758d98f498..ae5f34fd78f 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -118,6 +118,8 @@ pub enum Flow { PaymentMethodsCreate, /// Payment methods migrate flow. PaymentMethodsMigrate, + /// Payment methods batch update flow. + PaymentMethodsBatchUpdate, /// Payment methods list flow. PaymentMethodsList, /// Payment method save flow
2025-08-28T05:46:42Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> We need to make update payment methods API which can update the fields of the records in payment methods table. It will consume a CSV file which will have batch update entries. Currently it should only update connector_mandate_id, network_transaction_id and mandate_status. ### 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). --> Frequent DB updates on payment methods table due to ongoing migrations of merchants. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location 'http://localhost:8080/payment_methods/update-batch' \ --header 'api-key: test_admin' \ --form 'file=@"/Users/mrudul.vajpayee/Downloads/update_sample.csv"' \ --form 'merchant_id="merchant_1756355489"' ``` Sample output: ``` [ { "payment_method_id": "pm_RsWnXeiOhlaVseKdk0Mm", "status": "active", "network_transaction_id": "063AF598E0A5C5", "connector_mandate_details": { "payouts": { "mca_SbUFb1h4NfixAWFaLQeT": { "transfer_method_id": "ARM-678ab3997b16cb7cd" } }, "mca_Qwuqfidvy2Lk2y0PbvFa": { "mandate_metadata": null, "payment_method_type": "google_pay", "connector_mandate_id": "2D5D6F0E961E639BE063AF598E0A9A32", "connector_mandate_status": "active", "original_payment_authorized_amount": 20000, "original_payment_authorized_currency": "EUR", "connector_mandate_request_reference_id": "ytlaTEEjkONzieVl0k" }, "mca_xHIYFXMCUsYTZIZ1rwgY": { "mandate_metadata": null, "payment_method_type": null, "connector_mandate_id": "6D981A0542DDF0EBE063AF598E0A5C5E", "connector_mandate_status": null, "original_payment_authorized_amount": null, "original_payment_authorized_currency": null, "connector_mandate_request_reference_id": null } }, "update_status": "Success", "line_number": 1 }, { "payment_method_id": "pm_RsWnXeiOhlaVseKdk0Mm", "status": "active", "network_transaction_id": "063AF598E0A5C5", "connector_mandate_details": { "payouts": { "mca_SbUFb1h4NfixAWFaLQeT": { "transfer_method_id": "ARM-678ab3997b16cb7cd" } }, "mca_Qwuqfidvy2Lk2y0PbvFa": { "mandate_metadata": null, "payment_method_type": "google_pay", "connector_mandate_id": "2D5D6F0E961E639BE063AF598E0A9A32", "connector_mandate_status": "active", "original_payment_authorized_amount": 20000, "original_payment_authorized_currency": "EUR", "connector_mandate_request_reference_id": "ytlaTEEjkONzieVl0k" }, "mca_xHIYFXMCUsYTZIZ1rwgY": { "mandate_metadata": null, "payment_method_type": null, "connector_mandate_id": "6D981A0542DDF0EBE063AF598E0A5C5E", "connector_mandate_status": null, "original_payment_authorized_amount": null, "original_payment_authorized_currency": null, "connector_mandate_request_reference_id": null } }, "update_status": "Success", "line_number": 2 }, { "payment_method_id": "pm_RsWnXeiOhlaVseKdk0Mm", "status": "active", "network_transaction_id": "063AF598E0A5C5", "connector_mandate_details": { "payouts": { "mca_SbUFb1h4NfixAWFaLQeT": { "transfer_method_id": "ARM-678ab3997b16cb7cd" } }, "mca_Qwuqfidvy2Lk2y0PbvFa": { "mandate_metadata": null, "payment_method_type": "google_pay", "connector_mandate_id": "2D5D6F0E961E639BE063AF598E0A9A32", "connector_mandate_status": "active", "original_payment_authorized_amount": 20000, "original_payment_authorized_currency": "EUR", "connector_mandate_request_reference_id": "ytlaTEEjkONzieVl0k" }, "mca_xHIYFXMCUsYTZIZ1rwgY": { "mandate_metadata": null, "payment_method_type": null, "connector_mandate_id": "6D981A0542DDF0EBE063AF598E0A5C5E", "connector_mandate_status": null, "original_payment_authorized_amount": null, "original_payment_authorized_currency": null, "connector_mandate_request_reference_id": null } }, "update_status": "Success", "line_number": 3 } ] ``` [update_sample.csv](https://github.com/user-attachments/files/22072833/update_sample.csv) ## 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.116.0
10cf161d14810cc9c6320933909e9cd3bfdc41ca
10cf161d14810cc9c6320933909e9cd3bfdc41ca
juspay/hyperswitch
juspay__hyperswitch-9082
Bug: [FEATURE] Payment void endpoint for v2 ### Feature Description Add support for Payment Cancel in V2. ### Possible Implementation Add V2 payments_cancel flow by completing GetTracker, UpdateTracker, and Domain traits for payment cancel endpoint. ### 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_v2.json b/api-reference/v2/openapi_spec_v2.json index f29e2a30056..cec3f96a4ed 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -18961,14 +18961,6 @@ "type": "string", "description": "The reason for the payment cancel", "nullable": true - }, - "merchant_connector_details": { - "allOf": [ - { - "$ref": "#/components/schemas/MerchantConnectorDetailsWrap" - } - ], - "nullable": true } } }, diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index 8a0af806334..ad107225177 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -238,6 +238,22 @@ impl ApiEventMetric for payments::PaymentsResponse { } } +#[cfg(feature = "v2")] +impl ApiEventMetric for payments::PaymentsCancelRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + None + } +} + +#[cfg(feature = "v2")] +impl ApiEventMetric for payments::PaymentsCancelResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Payment { + payment_id: self.id.clone(), + }) + } +} + #[cfg(feature = "v1")] impl ApiEventMetric for payments::PaymentsResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 62390067d3b..43bd9c2a119 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4873,6 +4873,56 @@ pub struct PaymentsCaptureResponse { pub amount: PaymentAmountDetailsResponse, } +#[cfg(feature = "v2")] +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] +pub struct PaymentsCancelRequest { + /// The reason for the payment cancel + pub cancellation_reason: Option<String>, +} + +#[cfg(feature = "v2")] +#[derive(Debug, Clone, serde::Serialize, ToSchema)] +pub struct PaymentsCancelResponse { + /// The unique identifier for the payment + pub id: id_type::GlobalPaymentId, + + /// Status of the payment + #[schema(value_type = IntentStatus, example = "cancelled")] + pub status: common_enums::IntentStatus, + + /// Cancellation reason for the payment cancellation + #[schema(example = "Requested by merchant")] + pub cancellation_reason: Option<String>, + + /// Amount details related to the payment + pub amount: PaymentAmountDetailsResponse, + + /// The unique identifier for the customer associated with the payment + pub customer_id: Option<id_type::GlobalCustomerId>, + + /// The connector used for the payment + #[schema(example = "stripe")] + pub connector: Option<api_enums::Connector>, + + #[schema(example = "2022-09-10T10:11:12Z")] + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created: PrimitiveDateTime, + + /// The payment method type for this payment attempt + #[schema(value_type = Option<PaymentMethod>, example = "wallet")] + pub payment_method_type: Option<api_enums::PaymentMethod>, + + #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] + pub payment_method_subtype: Option<api_enums::PaymentMethodType>, + + /// List of payment attempts associated with payment intent + pub attempts: Option<Vec<PaymentAttemptResponse>>, + + /// The url to which user must be redirected to after completion of the purchase + #[schema(value_type = Option<String>)] + pub return_url: Option<common_utils::types::Url>, +} + #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, @@ -8210,6 +8260,7 @@ pub struct PaymentsCompleteAuthorizeRequest { pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } +#[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index d42b9d8d108..49d5ff79ab8 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -862,7 +862,7 @@ pub struct PaymentAttemptUpdateInternal { pub connector_payment_id: Option<ConnectorTransactionId>, pub connector_payment_data: Option<String>, pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, - // cancellation_reason: Option<String>, + pub cancellation_reason: Option<String>, pub modified_at: PrimitiveDateTime, pub browser_info: Option<serde_json::Value>, // payment_token: Option<String>, @@ -914,6 +914,7 @@ impl PaymentAttemptUpdateInternal { modified_at, browser_info, error_code, + cancellation_reason, connector_metadata, error_reason, amount_capturable, @@ -1404,6 +1405,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_advice_code: None, network_error_message: None, connector_request_reference_id: None, + cancellation_reason: None, } } PaymentAttemptUpdate::ErrorUpdate { @@ -1451,6 +1453,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_error_message: None, connector_request_reference_id: None, connector_response_reference_id: None, + cancellation_reason: None, } } PaymentAttemptUpdate::UnresolvedResponseUpdate { @@ -1496,6 +1499,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_advice_code: None, network_error_message: None, connector_request_reference_id: None, + cancellation_reason: None, } } PaymentAttemptUpdate::PreprocessingUpdate { @@ -1539,6 +1543,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_advice_code: None, network_error_message: None, connector_request_reference_id: None, + cancellation_reason: None, } } PaymentAttemptUpdate::ConnectorResponse { @@ -1578,6 +1583,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_error_message: None, connector_request_reference_id: None, connector_response_reference_id: None, + cancellation_reason: None, } } PaymentAttemptUpdate::ManualUpdate { @@ -1622,6 +1628,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { network_error_message: None, connector_request_reference_id: None, connector_response_reference_id: None, + cancellation_reason: None, } } } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index c8ac34f8613..20abea03b56 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -991,6 +991,17 @@ where pub payment_attempt: PaymentAttempt, } +#[cfg(feature = "v2")] +#[derive(Clone)] +pub struct PaymentCancelData<F> +where + F: Clone, +{ + pub flow: PhantomData<F>, + pub payment_intent: PaymentIntent, + pub payment_attempt: PaymentAttempt, +} + #[cfg(feature = "v2")] impl<F> PaymentStatusData<F> where diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 7f8b9020618..7eba77e6294 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -2044,6 +2044,11 @@ pub enum PaymentAttemptUpdate { updated_by: String, connector_payment_id: Option<String>, }, + VoidUpdate { + status: storage_enums::AttemptStatus, + cancellation_reason: Option<String>, + updated_by: String, + }, } #[cfg(feature = "v2")] @@ -2849,6 +2854,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal network_error_message: None, connector_request_reference_id, connector_response_reference_id, + cancellation_reason: None, }, PaymentAttemptUpdate::ErrorUpdate { status, @@ -2890,6 +2896,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal network_error_message: error.network_error_message, connector_request_reference_id: None, connector_response_reference_id: None, + cancellation_reason: None, } } PaymentAttemptUpdate::ConfirmIntentResponse(confirm_intent_response_update) => { @@ -2937,6 +2944,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal network_error_message: None, connector_request_reference_id: None, connector_response_reference_id, + cancellation_reason: None, } } PaymentAttemptUpdate::SyncUpdate { @@ -2970,6 +2978,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal network_error_message: None, connector_request_reference_id: None, connector_response_reference_id: None, + cancellation_reason: None, }, PaymentAttemptUpdate::CaptureUpdate { status, @@ -3002,6 +3011,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal network_error_message: None, connector_request_reference_id: None, connector_response_reference_id: None, + cancellation_reason: None, }, PaymentAttemptUpdate::PreCaptureUpdate { amount_to_capture, @@ -3033,6 +3043,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal network_error_message: None, connector_request_reference_id: None, connector_response_reference_id: None, + cancellation_reason: None, }, PaymentAttemptUpdate::ConfirmIntentTokenized { status, @@ -3068,6 +3079,40 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal network_error_message: None, connector_request_reference_id: None, connector_response_reference_id: None, + cancellation_reason: None, + }, + PaymentAttemptUpdate::VoidUpdate { + status, + cancellation_reason, + updated_by, + } => Self { + status: Some(status), + cancellation_reason, + error_message: None, + error_code: None, + modified_at: common_utils::date_time::now(), + browser_info: None, + error_reason: None, + updated_by, + merchant_connector_id: None, + unified_code: None, + unified_message: None, + connector_payment_id: None, + connector_payment_data: None, + connector: None, + redirection_data: None, + connector_metadata: None, + amount_capturable: None, + amount_to_capture: None, + connector_token_details: None, + authentication_type: None, + feature_metadata: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + connector_request_reference_id: None, + connector_response_reference_id: None, + payment_method_id: None, }, } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 8cd3be165e0..776b6e2d4cf 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -387,6 +387,11 @@ pub enum PaymentIntentUpdate { }, /// UpdateIntent UpdateIntent(Box<PaymentIntentUpdateFields>), + /// VoidUpdate for payment cancellation + VoidUpdate { + status: common_enums::IntentStatus, + updated_by: String, + }, } #[cfg(feature = "v2")] @@ -803,6 +808,45 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal force_3ds_challenge: None, is_iframe_redirection_enabled: None, }), + PaymentIntentUpdate::VoidUpdate { status, updated_by } => Ok(Self { + status: Some(status), + amount_captured: None, + active_attempt_id: None, + prerouting_algorithm: None, + modified_at: common_utils::date_time::now(), + amount: None, + currency: None, + shipping_cost: None, + tax_details: None, + skip_external_tax_calculation: None, + surcharge_applicable: None, + surcharge_amount: None, + tax_on_surcharge: None, + routing_algorithm_id: None, + capture_method: None, + authentication_type: None, + billing_address: None, + shipping_address: None, + customer_present: None, + description: None, + return_url: None, + setup_future_usage: None, + apply_mit_exemption: None, + statement_descriptor: None, + order_details: None, + allowed_payment_method_types: None, + metadata: None, + connector_metadata: None, + feature_metadata: None, + payment_link_config: None, + request_incremental_authorization: None, + session_expiry: None, + frm_metadata: None, + request_external_three_ds_authentication: None, + updated_by, + force_3ds_challenge: None, + is_iframe_redirection_enabled: None, + }), } } } diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index e975423d9ff..ad778e9aa74 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -1814,3 +1814,65 @@ impl } } } + +#[cfg(feature = "v2")] +impl + TrackerPostUpdateObjects< + router_flow_types::Void, + router_request_types::PaymentsCancelData, + payments::PaymentCancelData<router_flow_types::Void>, + > + for RouterData< + router_flow_types::Void, + router_request_types::PaymentsCancelData, + router_response_types::PaymentsResponseData, + > +{ + fn get_payment_intent_update( + &self, + _payment_data: &payments::PaymentCancelData<router_flow_types::Void>, + storage_scheme: common_enums::MerchantStorageScheme, + ) -> PaymentIntentUpdate { + let intent_status = common_enums::IntentStatus::from(self.status); + PaymentIntentUpdate::VoidUpdate { + status: intent_status, + updated_by: storage_scheme.to_string(), + } + } + + fn get_payment_attempt_update( + &self, + payment_data: &payments::PaymentCancelData<router_flow_types::Void>, + storage_scheme: common_enums::MerchantStorageScheme, + ) -> PaymentAttemptUpdate { + PaymentAttemptUpdate::VoidUpdate { + status: self.status, + cancellation_reason: payment_data.payment_attempt.cancellation_reason.clone(), + updated_by: storage_scheme.to_string(), + } + } + + fn get_amount_capturable( + &self, + _payment_data: &payments::PaymentCancelData<router_flow_types::Void>, + ) -> Option<MinorUnit> { + // For void operations, no amount is capturable + Some(MinorUnit::zero()) + } + + fn get_captured_amount( + &self, + _payment_data: &payments::PaymentCancelData<router_flow_types::Void>, + ) -> Option<MinorUnit> { + // For void operations, no amount is captured + Some(MinorUnit::zero()) + } + + fn get_attempt_status_for_db_update( + &self, + _payment_data: &payments::PaymentCancelData<router_flow_types::Void>, + ) -> common_enums::AttemptStatus { + // For void operations, return Voided status + common_enums::AttemptStatus::Voided + } +} diff --git a/crates/hyperswitch_interfaces/src/conversion_impls.rs b/crates/hyperswitch_interfaces/src/conversion_impls.rs index 32818ca5d4b..1b451692bdd 100644 --- a/crates/hyperswitch_interfaces/src/conversion_impls.rs +++ b/crates/hyperswitch_interfaces/src/conversion_impls.rs @@ -324,6 +324,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for PaymentF router_data.apple_pay_flow = apple_pay_flow; router_data.connector_response = connector_response; router_data.payment_method_status = payment_method_status; + router_data.connector_auth_type = new_router_data.connector_auth_type; Ok(router_data) } } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index f7f445d1b6a..e40830404b3 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -48,8 +48,8 @@ use futures::future::join_all; use helpers::{decrypt_paze_token, ApplePayData}; #[cfg(feature = "v2")] use hyperswitch_domain_models::payments::{ - PaymentAttemptListData, PaymentCaptureData, PaymentConfirmData, PaymentIntentData, - PaymentStatusData, + PaymentAttemptListData, PaymentCancelData, PaymentCaptureData, PaymentConfirmData, + PaymentIntentData, PaymentStatusData, }; #[cfg(feature = "v2")] use hyperswitch_domain_models::router_response_types::RedirectForm; @@ -10638,6 +10638,8 @@ pub trait OperationSessionSetters<F> { &mut self, connector_request_reference_id: String, ); + #[cfg(feature = "v2")] + fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>); } #[cfg(feature = "v1")] @@ -11290,6 +11292,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> { ) { todo!() } + + fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>) { + todo!() + } } #[cfg(feature = "v2")] @@ -11597,6 +11603,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> { ) { todo!() } + + fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>) { + todo!() + } } #[cfg(feature = "v2")] @@ -11899,6 +11909,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> { ) { todo!() } + + fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>) { + todo!() + } } #[cfg(feature = "v2")] @@ -12204,6 +12218,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> { ) { todo!() } + + fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>) { + todo!() + } } #[cfg(feature = "v2")] @@ -12371,3 +12389,311 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentAttemptListData<F> { todo!() } } + +#[cfg(feature = "v2")] +impl<F: Clone> OperationSessionGetters<F> for PaymentCancelData<F> { + #[track_caller] + fn get_payment_attempt(&self) -> &storage::PaymentAttempt { + &self.payment_attempt + } + fn list_payments_attempts(&self) -> &Vec<storage::PaymentAttempt> { + todo!() + } + fn get_client_secret(&self) -> &Option<Secret<String>> { + todo!() + } + fn get_payment_intent(&self) -> &storage::PaymentIntent { + &self.payment_intent + } + + fn get_merchant_connector_details( + &self, + ) -> Option<common_types::domain::MerchantConnectorAuthDetails> { + todo!() + } + + fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> { + todo!() + } + + fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> { + todo!() + } + + fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> { + todo!() + } + + // what is this address find out and not required remove this + fn get_address(&self) -> &PaymentAddress { + todo!() + } + + fn get_creds_identifier(&self) -> Option<&str> { + None + } + + fn get_token(&self) -> Option<&str> { + todo!() + } + + fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> { + todo!() + } + + fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> { + todo!() + } + + fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> { + todo!() + } + + fn get_setup_mandate(&self) -> Option<&MandateData> { + todo!() + } + + fn get_poll_config(&self) -> Option<router_types::PollConfig> { + todo!() + } + + fn get_authentication( + &self, + ) -> Option<&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore> + { + todo!() + } + + fn get_frm_message(&self) -> Option<FraudCheck> { + todo!() + } + + fn get_refunds(&self) -> Vec<diesel_refund::Refund> { + todo!() + } + + fn get_disputes(&self) -> Vec<storage::Dispute> { + todo!() + } + + fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> { + todo!() + } + + fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> { + todo!() + } + + fn get_recurring_details(&self) -> Option<&RecurringDetails> { + todo!() + } + + fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> { + todo!() + } + + fn get_currency(&self) -> storage_enums::Currency { + todo!() + } + + fn get_amount(&self) -> api::Amount { + todo!() + } + + fn get_payment_attempt_connector(&self) -> Option<&str> { + todo!() + } + + fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> { + todo!() + } + + fn get_connector_customer_id(&self) -> Option<String> { + todo!() + } + + fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> { + todo!() + } + + fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> { + todo!() + } + + fn get_sessions_token(&self) -> Vec<api::SessionToken> { + todo!() + } + + fn get_token_data(&self) -> Option<&storage::PaymentTokenData> { + todo!() + } + + fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> { + todo!() + } + + fn get_force_sync(&self) -> Option<bool> { + todo!() + } + + fn get_capture_method(&self) -> Option<enums::CaptureMethod> { + todo!() + } + + fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { + None + } + + fn get_pre_routing_result( + &self, + ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> { + None + } + + fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> { + todo!() + } +} + +#[cfg(feature = "v2")] +impl<F: Clone> OperationSessionSetters<F> for PaymentCancelData<F> { + fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { + self.payment_intent = payment_intent; + } + + fn set_client_secret(&mut self, _client_secret: Option<Secret<String>>) { + todo!() + } + + fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { + self.payment_attempt = payment_attempt; + } + + fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) { + todo!() + } + + fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) { + todo!() + } + + fn set_email_if_not_present(&mut self, _email: pii::Email) { + todo!() + } + + fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) { + todo!() + } + + fn set_pm_token(&mut self, _token: String) { + !todo!() + } + + fn set_connector_customer_id(&mut self, _customer_id: Option<String>) { + // TODO: handle this case. Should we add connector_customer_id in PaymentCancelData? + } + + fn push_sessions_token(&mut self, _token: api::SessionToken) { + todo!() + } + + fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) { + todo!() + } + + fn set_merchant_connector_id_in_attempt( + &mut self, + _merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, + ) { + todo!() + } + + fn set_card_network(&mut self, _card_network: enums::CardNetwork) { + todo!() + } + + fn set_co_badged_card_data( + &mut self, + _debit_routing_output: &api_models::open_router::DebitRoutingOutput, + ) { + todo!() + } + + fn set_frm_message(&mut self, _frm_message: FraudCheck) { + todo!() + } + + fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) { + self.payment_intent.status = status; + } + + fn set_authentication_type_in_attempt( + &mut self, + _authentication_type: Option<enums::AuthenticationType>, + ) { + todo!() + } + + fn set_recurring_mandate_payment_data( + &mut self, + _recurring_mandate_payment_data: + hyperswitch_domain_models::router_data::RecurringMandatePaymentData, + ) { + todo!() + } + + fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) { + todo!() + } + + fn set_setup_future_usage_in_payment_intent( + &mut self, + setup_future_usage: storage_enums::FutureUsage, + ) { + todo!() + } + + fn set_prerouting_algorithm_in_payment_intent( + &mut self, + prerouting_algorithm: storage::PaymentRoutingInfo, + ) { + self.payment_intent.prerouting_algorithm = Some(prerouting_algorithm); + } + + fn set_connector_in_payment_attempt(&mut self, _connector: Option<String>) { + todo!() + } + + fn set_connector_request_reference_id(&mut self, _reference_id: Option<String>) { + todo!() + } + + fn set_connector_response_reference_id(&mut self, _reference_id: Option<String>) { + todo!() + } + + fn set_vault_session_details( + &mut self, + _external_vault_session_details: Option<api::VaultSessionDetails>, + ) { + todo!() + } + + fn set_routing_approach_in_attempt( + &mut self, + _routing_approach: Option<enums::RoutingApproach>, + ) { + todo!() + } + + fn set_connector_request_reference_id_in_payment_attempt( + &mut self, + _connector_request_reference_id: String, + ) { + todo!() + } + + fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>) { + self.payment_attempt.cancellation_reason = cancellation_reason; + } +} diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index a452a165c7d..1190cef2441 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -10,26 +10,11 @@ use crate::{ services, types::{self, api, domain}, }; - +#[cfg(feature = "v1")] #[async_trait] impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for PaymentData<api::Void> { - #[cfg(feature = "v2")] - async fn construct_router_data<'a>( - &self, - _state: &SessionState, - _connector_id: &str, - _merchant_context: &domain::MerchantContext, - _customer: &Option<domain::Customer>, - _merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, - _merchant_recipient_data: Option<types::MerchantRecipientData>, - _header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, - ) -> RouterResult<types::PaymentsCancelRouterData> { - todo!() - } - - #[cfg(feature = "v1")] async fn construct_router_data<'a>( &self, state: &SessionState, @@ -56,6 +41,34 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym .await } } +#[cfg(feature = "v2")] +#[async_trait] +impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for hyperswitch_domain_models::payments::PaymentCancelData<api::Void> +{ + async fn construct_router_data<'a>( + &self, + state: &SessionState, + connector_id: &str, + merchant_context: &domain::MerchantContext, + customer: &Option<domain::Customer>, + merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, + merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, + ) -> RouterResult<types::PaymentsCancelRouterData> { + Box::pin(transformers::construct_router_data_for_cancel( + state, + self.clone(), + connector_id, + merchant_context, + customer, + merchant_connector_account, + merchant_recipient_data, + header_payload, + )) + .await + } +} #[async_trait] impl Feature<api::Void, types::PaymentsCancelData> diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index 2d8488ab6cc..11c26b5c54b 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -58,6 +58,9 @@ pub mod payment_get; #[cfg(feature = "v2")] pub mod payment_capture_v2; +#[cfg(feature = "v2")] +pub mod payment_cancel_v2; + use api_models::enums::FrmSuggestion; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use api_models::routing::RoutableConnectorChoice; diff --git a/crates/router/src/core/payments/operations/payment_cancel_v2.rs b/crates/router/src/core/payments/operations/payment_cancel_v2.rs new file mode 100644 index 00000000000..e54de6cb793 --- /dev/null +++ b/crates/router/src/core/payments/operations/payment_cancel_v2.rs @@ -0,0 +1,352 @@ +use std::marker::PhantomData; + +use api_models::enums::FrmSuggestion; +use async_trait::async_trait; +use common_enums; +use common_utils::{ext_traits::AsyncExt, id_type::GlobalPaymentId}; +use error_stack::ResultExt; +use router_env::{instrument, tracing}; + +use super::{ + BoxedOperation, Domain, GetTracker, Operation, OperationSessionSetters, UpdateTracker, + ValidateRequest, ValidateStatusForOperation, +}; +use crate::{ + core::{ + errors::{self, CustomResult, RouterResult, StorageErrorExt}, + payments::operations, + }, + routes::{app::ReqState, SessionState}, + types::{ + self, + api::{self, ConnectorCallType, PaymentIdTypeExt}, + domain, + storage::{self, enums}, + PaymentsCancelData, + }, + utils::OptionExt, +}; + +#[derive(Debug, Clone, Copy)] +pub struct PaymentsCancel; + +type BoxedCancelOperation<'b, F> = BoxedOperation< + 'b, + F, + api::PaymentsCancelRequest, + hyperswitch_domain_models::payments::PaymentCancelData<F>, +>; + +// Manual Operation trait implementation for V2 +impl<F: Send + Clone + Sync> Operation<F, api::PaymentsCancelRequest> for &PaymentsCancel { + type Data = hyperswitch_domain_models::payments::PaymentCancelData<F>; + + fn to_validate_request( + &self, + ) -> RouterResult<&(dyn ValidateRequest<F, api::PaymentsCancelRequest, Self::Data> + Send + Sync)> + { + Ok(*self) + } + + fn to_get_tracker( + &self, + ) -> RouterResult<&(dyn GetTracker<F, Self::Data, api::PaymentsCancelRequest> + Send + Sync)> + { + Ok(*self) + } + + fn to_domain(&self) -> RouterResult<&(dyn Domain<F, api::PaymentsCancelRequest, Self::Data>)> { + Ok(*self) + } + + fn to_update_tracker( + &self, + ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, api::PaymentsCancelRequest> + Send + Sync)> + { + Ok(*self) + } +} + +#[automatically_derived] +impl<F: Send + Clone + Sync> Operation<F, api::PaymentsCancelRequest> for PaymentsCancel { + type Data = hyperswitch_domain_models::payments::PaymentCancelData<F>; + + fn to_validate_request( + &self, + ) -> RouterResult<&(dyn ValidateRequest<F, api::PaymentsCancelRequest, Self::Data> + Send + Sync)> + { + Ok(self) + } + + fn to_get_tracker( + &self, + ) -> RouterResult<&(dyn GetTracker<F, Self::Data, api::PaymentsCancelRequest> + Send + Sync)> + { + Ok(self) + } + + fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsCancelRequest, Self::Data>> { + Ok(self) + } + + fn to_update_tracker( + &self, + ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, api::PaymentsCancelRequest> + Send + Sync)> + { + Ok(self) + } +} + +#[cfg(feature = "v2")] +impl<F: Send + Clone + Sync> + ValidateRequest< + F, + api::PaymentsCancelRequest, + hyperswitch_domain_models::payments::PaymentCancelData<F>, + > for PaymentsCancel +{ + #[instrument(skip_all)] + fn validate_request( + &self, + _request: &api::PaymentsCancelRequest, + merchant_context: &domain::MerchantContext, + ) -> RouterResult<operations::ValidateResult> { + Ok(operations::ValidateResult { + merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), + storage_scheme: merchant_context.get_merchant_account().storage_scheme, + requeue: false, + }) + } +} + +#[cfg(feature = "v2")] +#[async_trait] +impl<F: Send + Clone + Sync> + GetTracker< + F, + hyperswitch_domain_models::payments::PaymentCancelData<F>, + api::PaymentsCancelRequest, + > for PaymentsCancel +{ + #[instrument(skip_all)] + async fn get_trackers<'a>( + &'a self, + state: &'a SessionState, + payment_id: &common_utils::id_type::GlobalPaymentId, + request: &api::PaymentsCancelRequest, + merchant_context: &domain::MerchantContext, + profile: &domain::Profile, + _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + ) -> RouterResult< + operations::GetTrackerResponse<hyperswitch_domain_models::payments::PaymentCancelData<F>>, + > { + let db = &*state.store; + let key_manager_state = &state.into(); + + let merchant_id = merchant_context.get_merchant_account().get_id(); + let storage_scheme = merchant_context.get_merchant_account().storage_scheme; + let payment_intent = db + .find_payment_intent_by_id( + key_manager_state, + payment_id, + merchant_context.get_merchant_key_store(), + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) + .attach_printable("Failed to find payment intent for cancellation")?; + + self.validate_status_for_operation(payment_intent.status)?; + + let active_attempt_id = payment_intent.active_attempt_id.as_ref().ok_or_else(|| { + errors::ApiErrorResponse::InvalidRequestData { + message: "Payment cancellation not possible - no active payment attempt found" + .to_string(), + } + })?; + + let payment_attempt = db + .find_payment_attempt_by_id( + key_manager_state, + merchant_context.get_merchant_key_store(), + active_attempt_id, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) + .attach_printable("Failed to find payment attempt for cancellation")?; + + let mut payment_data = hyperswitch_domain_models::payments::PaymentCancelData { + flow: PhantomData, + payment_intent, + payment_attempt, + }; + + payment_data.set_cancellation_reason(request.cancellation_reason.clone()); + + let get_trackers_response = operations::GetTrackerResponse { payment_data }; + + Ok(get_trackers_response) + } +} + +#[cfg(feature = "v2")] +#[async_trait] +impl<F: Clone + Send + Sync> + UpdateTracker< + F, + hyperswitch_domain_models::payments::PaymentCancelData<F>, + api::PaymentsCancelRequest, + > for PaymentsCancel +{ + #[instrument(skip_all)] + async fn update_trackers<'b>( + &'b self, + state: &'b SessionState, + req_state: ReqState, + mut payment_data: hyperswitch_domain_models::payments::PaymentCancelData<F>, + _customer: Option<domain::Customer>, + storage_scheme: enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, + merchant_key_store: &domain::MerchantKeyStore, + _frm_suggestion: Option<FrmSuggestion>, + _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + ) -> RouterResult<( + BoxedCancelOperation<'b, F>, + hyperswitch_domain_models::payments::PaymentCancelData<F>, + )> + where + F: 'b + Send, + { + let db = &*state.store; + let key_manager_state = &state.into(); + + let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::VoidUpdate { + status: enums::AttemptStatus::VoidInitiated, + cancellation_reason: payment_data.payment_attempt.cancellation_reason.clone(), + updated_by: storage_scheme.to_string(), + }; + + let updated_payment_attempt = db + .update_payment_attempt( + key_manager_state, + merchant_key_store, + payment_data.payment_attempt.clone(), + payment_attempt_update, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) + .attach_printable("Failed to update payment attempt for cancellation")?; + payment_data.set_payment_attempt(updated_payment_attempt); + + Ok((Box::new(self), payment_data)) + } +} + +#[cfg(feature = "v2")] +#[async_trait] +impl<F: Send + Clone + Sync> + Domain<F, api::PaymentsCancelRequest, hyperswitch_domain_models::payments::PaymentCancelData<F>> + for PaymentsCancel +{ + async fn get_customer_details<'a>( + &'a self, + _state: &SessionState, + _payment_data: &mut hyperswitch_domain_models::payments::PaymentCancelData<F>, + _merchant_key_store: &domain::MerchantKeyStore, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<(BoxedCancelOperation<'a, F>, Option<domain::Customer>), errors::StorageError> + { + Ok((Box::new(*self), None)) + } + + async fn make_pm_data<'a>( + &'a self, + _state: &'a SessionState, + _payment_data: &mut hyperswitch_domain_models::payments::PaymentCancelData<F>, + _storage_scheme: enums::MerchantStorageScheme, + _merchant_key_store: &domain::MerchantKeyStore, + _customer: &Option<domain::Customer>, + _business_profile: &domain::Profile, + _should_retry_with_pan: bool, + ) -> RouterResult<( + BoxedCancelOperation<'a, F>, + Option<domain::PaymentMethodData>, + Option<String>, + )> { + Ok((Box::new(*self), None, None)) + } + + async fn perform_routing<'a>( + &'a self, + _merchant_context: &domain::MerchantContext, + _business_profile: &domain::Profile, + state: &SessionState, + payment_data: &mut hyperswitch_domain_models::payments::PaymentCancelData<F>, + ) -> RouterResult<api::ConnectorCallType> { + let payment_attempt = &payment_data.payment_attempt; + let connector = payment_attempt + .connector + .as_ref() + .get_required_value("connector") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Connector not found for payment cancellation")?; + + let merchant_connector_id = payment_attempt + .merchant_connector_id + .as_ref() + .get_required_value("merchant_connector_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Merchant connector ID not found for payment cancellation")?; + + let connector_data = api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + connector, + api::GetToken::Connector, + Some(merchant_connector_id.to_owned()), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received")?; + + Ok(api::ConnectorCallType::PreDetermined(connector_data.into())) + } +} + +impl ValidateStatusForOperation for PaymentsCancel { + fn validate_status_for_operation( + &self, + intent_status: common_enums::IntentStatus, + ) -> Result<(), errors::ApiErrorResponse> { + match intent_status { + common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture + | common_enums::IntentStatus::PartiallyCapturedAndCapturable + | common_enums::IntentStatus::RequiresCapture => Ok(()), + common_enums::IntentStatus::Succeeded + | common_enums::IntentStatus::Failed + | common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture + | common_enums::IntentStatus::Processing + | common_enums::IntentStatus::RequiresCustomerAction + | common_enums::IntentStatus::RequiresMerchantAction + | common_enums::IntentStatus::RequiresPaymentMethod + | common_enums::IntentStatus::RequiresConfirmation + | common_enums::IntentStatus::PartiallyCaptured + | common_enums::IntentStatus::Conflicted + | common_enums::IntentStatus::Expired => { + Err(errors::ApiErrorResponse::PaymentUnexpectedState { + current_flow: format!("{self:?}"), + field_name: "status".to_string(), + current_value: intent_status.to_string(), + states: [ + common_enums::IntentStatus::RequiresCapture, + common_enums::IntentStatus::PartiallyCapturedAndCapturable, + common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture, + ] + .map(|enum_value| enum_value.to_string()) + .join(", "), + }) + } + } + } +} diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 2b1d1024e76..410c546eeda 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -3232,3 +3232,83 @@ fn get_total_amount_captured<F: Clone, T: types::Capturable>( } } } + +#[cfg(feature = "v2")] +impl<F: Send + Clone + Sync> Operation<F, types::PaymentsCancelData> for PaymentResponse { + type Data = hyperswitch_domain_models::payments::PaymentCancelData<F>; + fn to_post_update_tracker( + &self, + ) -> RouterResult< + &(dyn PostUpdateTracker<F, Self::Data, types::PaymentsCancelData> + Send + Sync), + > { + Ok(self) + } +} + +#[cfg(feature = "v2")] +#[async_trait] +impl<F: Clone + Send + Sync> + PostUpdateTracker< + F, + hyperswitch_domain_models::payments::PaymentCancelData<F>, + types::PaymentsCancelData, + > for PaymentResponse +{ + async fn update_tracker<'b>( + &'b self, + state: &'b SessionState, + mut payment_data: hyperswitch_domain_models::payments::PaymentCancelData<F>, + router_data: types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>, + key_store: &domain::MerchantKeyStore, + storage_scheme: enums::MerchantStorageScheme, + ) -> RouterResult<hyperswitch_domain_models::payments::PaymentCancelData<F>> + where + F: 'b + Send + Sync, + types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>: + hyperswitch_domain_models::router_data::TrackerPostUpdateObjects< + F, + types::PaymentsCancelData, + hyperswitch_domain_models::payments::PaymentCancelData<F>, + >, + { + let db = &*state.store; + let key_manager_state = &state.into(); + + use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects; + + let payment_intent_update = + router_data.get_payment_intent_update(&payment_data, storage_scheme); + + let updated_payment_intent = db + .update_payment_intent( + key_manager_state, + payment_data.payment_intent.clone(), + payment_intent_update, + key_store, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) + .attach_printable("Error while updating the payment_intent")?; + + let payment_attempt_update = + router_data.get_payment_attempt_update(&payment_data, storage_scheme); + + let updated_payment_attempt = db + .update_payment_attempt( + key_manager_state, + key_store, + payment_data.payment_attempt.clone(), + payment_attempt_update, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) + .attach_printable("Error while updating the payment_attempt")?; + + payment_data.set_payment_intent(updated_payment_intent); + payment_data.set_payment_attempt(updated_payment_attempt); + + Ok(payment_data) + } +} diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index f799fdebbfe..47733f64e36 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1,5 +1,7 @@ use std::{fmt::Debug, marker::PhantomData, str::FromStr}; +#[cfg(feature = "v2")] +use api_models::enums as api_enums; use api_models::payments::{ Address, ConnectorMandateReferenceId, CustomerDetails, CustomerDetailsResponse, FrmMessage, MandateIds, NetworkDetails, RequestSurchargeDetails, @@ -21,16 +23,19 @@ use diesel_models::{ }, }; use error_stack::{report, ResultExt}; -#[cfg(feature = "v2")] -use hyperswitch_domain_models::ApiModelToDieselModelConvertor; use hyperswitch_domain_models::{payments::payment_intent::CustomerData, router_request_types}; #[cfg(feature = "v2")] +use hyperswitch_domain_models::{ + router_data_v2::{flow_common_types, RouterDataV2}, + ApiModelToDieselModelConvertor, +}; +#[cfg(feature = "v2")] use hyperswitch_interfaces::api::ConnectorSpecifications; #[cfg(feature = "v2")] use hyperswitch_interfaces::connector_integration_interface::RouterDataConversion; -#[cfg(feature = "v2")] -use masking::PeekInterface; use masking::{ExposeInterface, Maskable, Secret}; +#[cfg(feature = "v2")] +use masking::{ExposeOptionInterface, PeekInterface}; use router_env::{instrument, tracing}; use super::{flows::Feature, types::AuthenticationData, OperationSessionGetters, PaymentData}; @@ -200,7 +205,7 @@ pub async fn construct_external_vault_proxy_router_data_v2<'a>( customer_id: Option<common_utils::id_type::CustomerId>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult< - hyperswitch_domain_models::router_data_v2::RouterDataV2< + RouterDataV2< api::ExternalVaultProxy, hyperswitch_domain_models::router_data_v2::ExternalVaultProxyFlowData, types::ExternalVaultProxyPaymentsData, @@ -685,11 +690,12 @@ pub async fn construct_external_vault_proxy_payment_router_data<'a>( .await?; // Convert RouterDataV2 to old RouterData (v1) using the existing RouterDataConversion trait - let router_data = hyperswitch_domain_models::router_data_v2::flow_common_types::ExternalVaultProxyFlowData::to_old_router_data(router_data_v2) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "Cannot construct router data for making the unified connector service call", - )?; + let router_data = + flow_common_types::ExternalVaultProxyFlowData::to_old_router_data(router_data_v2) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Cannot construct router data for making the unified connector service call", + )?; Ok(router_data) } @@ -991,6 +997,163 @@ pub async fn construct_router_data_for_psync<'a>( Ok(router_data) } +#[cfg(feature = "v2")] +#[instrument(skip_all)] +#[allow(clippy::too_many_arguments)] +pub async fn construct_cancel_router_data_v2<'a>( + state: &'a SessionState, + merchant_account: &domain::MerchantAccount, + merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, + payment_data: &hyperswitch_domain_models::payments::PaymentCancelData<api::Void>, + request: types::PaymentsCancelData, + connector_request_reference_id: String, + customer_id: Option<common_utils::id_type::CustomerId>, + header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, +) -> RouterResult< + RouterDataV2< + api::Void, + flow_common_types::PaymentFlowData, + types::PaymentsCancelData, + types::PaymentsResponseData, + >, +> { + let auth_type: types::ConnectorAuthType = merchant_connector_account + .get_connector_account_details() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while parsing value for ConnectorAuthType")?; + + let payment_cancel_data = flow_common_types::PaymentFlowData { + merchant_id: merchant_account.get_id().clone(), + customer_id, + connector_customer: None, + payment_id: payment_data + .payment_attempt + .payment_id + .get_string_repr() + .to_owned(), + attempt_id: payment_data + .payment_attempt + .get_id() + .get_string_repr() + .to_owned(), + status: payment_data.payment_attempt.status, + payment_method: payment_data.payment_attempt.payment_method_type, + description: payment_data + .payment_intent + .description + .as_ref() + .map(|description| description.get_string_repr()) + .map(ToOwned::to_owned), + address: hyperswitch_domain_models::payment_address::PaymentAddress::default(), + auth_type: payment_data.payment_attempt.authentication_type, + connector_meta_data: merchant_connector_account.get_metadata(), + amount_captured: None, + minor_amount_captured: None, + access_token: None, + session_token: None, + reference_id: None, + payment_method_token: None, + recurring_mandate_payment_data: None, + preprocessing_id: payment_data.payment_attempt.preprocessing_step_id.clone(), + payment_method_balance: None, + connector_api_version: None, + connector_request_reference_id, + test_mode: Some(true), + connector_http_status_code: None, + external_latency: None, + apple_pay_flow: None, + connector_response: None, + payment_method_status: None, + }; + + let router_data_v2 = RouterDataV2 { + flow: PhantomData, + tenant_id: state.tenant.tenant_id.clone(), + resource_common_data: payment_cancel_data, + connector_auth_type: auth_type, + request, + response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), + }; + + Ok(router_data_v2) +} + +#[cfg(feature = "v2")] +#[instrument(skip_all)] +#[allow(clippy::too_many_arguments)] +pub async fn construct_router_data_for_cancel<'a>( + state: &'a SessionState, + payment_data: hyperswitch_domain_models::payments::PaymentCancelData< + hyperswitch_domain_models::router_flow_types::Void, + >, + connector_id: &str, + merchant_context: &domain::MerchantContext, + customer: &'a Option<domain::Customer>, + merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, + _merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, +) -> RouterResult<types::PaymentsCancelRouterData> { + fp_utils::when(merchant_connector_account.is_disabled(), || { + Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) + })?; + + // TODO: Take Globalid and convert to connector reference id + let customer_id = customer + .to_owned() + .map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone())) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Invalid global customer generated, not able to convert to reference id", + )?; + let payment_intent = payment_data.get_payment_intent(); + let attempt = payment_data.get_payment_attempt(); + let connector_request_reference_id = payment_data + .payment_attempt + .connector_request_reference_id + .clone() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("connector_request_reference_id not found in payment_attempt")?; + + let request = types::PaymentsCancelData { + amount: Some(attempt.amount_details.get_net_amount().get_amount_as_i64()), + currency: Some(payment_intent.amount_details.currency), + connector_transaction_id: attempt + .get_connector_payment_id() + .unwrap_or_default() + .to_string(), + cancellation_reason: attempt.cancellation_reason.clone(), + connector_meta: attempt.connector_metadata.clone().expose_option(), + browser_info: None, + metadata: None, + minor_amount: Some(attempt.amount_details.get_net_amount()), + webhook_url: None, + capture_method: Some(payment_intent.capture_method), + }; + + // Construct RouterDataV2 for cancel operation + let router_data_v2 = construct_cancel_router_data_v2( + state, + merchant_context.get_merchant_account(), + merchant_connector_account, + &payment_data, + request, + connector_request_reference_id.clone(), + customer_id.clone(), + header_payload.clone(), + ) + .await?; + + // Convert RouterDataV2 to old RouterData (v1) using the existing RouterDataConversion trait + let router_data = flow_common_types::PaymentFlowData::to_old_router_data(router_data_v2) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Cannot construct router data for making the unified connector service call", + )?; + + Ok(router_data) +} + #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] @@ -1978,6 +2141,63 @@ where } } +#[cfg(feature = "v2")] +impl<F> GenerateResponse<api_models::payments::PaymentsCancelResponse> + for hyperswitch_domain_models::payments::PaymentCancelData<F> +where + F: Clone, +{ + fn generate_response( + self, + state: &SessionState, + connector_http_status_code: Option<u16>, + external_latency: Option<u128>, + is_latency_header_enabled: Option<bool>, + merchant_context: &domain::MerchantContext, + profile: &domain::Profile, + _connector_response_data: Option<common_types::domain::ConnectorResponseData>, + ) -> RouterResponse<api_models::payments::PaymentsCancelResponse> { + let payment_intent = &self.payment_intent; + let payment_attempt = &self.payment_attempt; + + let amount = api_models::payments::PaymentAmountDetailsResponse::foreign_from(( + &payment_intent.amount_details, + &payment_attempt.amount_details, + )); + + let connector = payment_attempt + .connector + .as_ref() + .and_then(|conn| api_enums::Connector::from_str(conn).ok()); + let response = api_models::payments::PaymentsCancelResponse { + id: payment_intent.id.clone(), + status: payment_intent.status, + cancellation_reason: payment_attempt.cancellation_reason.clone(), + amount, + customer_id: payment_intent.customer_id.clone(), + connector, + created: payment_intent.created_at, + payment_method_type: Some(payment_attempt.payment_method_type), + payment_method_subtype: Some(payment_attempt.payment_method_subtype), + attempts: None, + return_url: payment_intent.return_url.clone(), + }; + + let headers = connector_http_status_code + .map(|status_code| { + vec![( + X_CONNECTOR_HTTP_STATUS_CODE.to_string(), + Maskable::new_normal(status_code.to_string()), + )] + }) + .unwrap_or_default(); + + Ok(services::ApplicationResponse::JsonWithHeaders(( + response, headers, + ))) + } +} + #[cfg(feature = "v1")] impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsResponse where @@ -4550,7 +4770,55 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelDa type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { - todo!() + let payment_data = additional_data.payment_data; + let connector = api::ConnectorData::get_connector_by_name( + &additional_data.state.conf.connectors, + &additional_data.connector_name, + api::GetToken::Connector, + payment_data.payment_attempt.merchant_connector_id.clone(), + )?; + let browser_info: Option<types::BrowserInformation> = payment_data + .payment_attempt + .browser_info + .clone() + .map(types::BrowserInformation::from); + + let amount = payment_data.payment_attempt.amount_details.get_net_amount(); + + let router_base_url = &additional_data.router_base_url; + let attempt = &payment_data.payment_attempt; + + let merchant_connector_account_id = payment_data + .payment_attempt + .merchant_connector_id + .as_ref() + .map(|mca_id| mca_id.get_string_repr()) + .ok_or(errors::ApiErrorResponse::MerchantAccountNotFound)?; + let webhook_url: Option<_> = Some(helpers::create_webhook_url( + router_base_url, + &attempt.merchant_id, + merchant_connector_account_id, + )); + let capture_method = payment_data.payment_intent.capture_method; + Ok(Self { + amount: Some(amount.get_amount_as_i64()), // This should be removed once we start moving to connector module + minor_amount: Some(amount), + currency: Some(payment_data.payment_intent.amount_details.currency), + connector_transaction_id: connector + .connector + .connector_transaction_id(&payment_data.payment_attempt)? + .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, + cancellation_reason: payment_data.payment_attempt.cancellation_reason, + connector_meta: payment_data + .payment_attempt + .connector_metadata + .clone() + .expose_option(), + browser_info, + metadata: payment_data.payment_intent.metadata.expose_option(), + webhook_url, + capture_method: Some(capture_method), + }) } } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index d52dc1570ce..dd4bb55c3e4 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -741,7 +741,8 @@ impl Payments { .service( web::resource("/check-gift-card-balance") .route(web::post().to(payments::payment_check_gift_card_balance)), - ), + ) + .service(web::resource("/cancel").route(web::post().to(payments::payments_cancel))), ); route diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 6f29b4cb5d9..c1970b64c28 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -1529,6 +1529,84 @@ pub async fn payments_cancel( .await } +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::PaymentsCancel, payment_id))] +pub async fn payments_cancel( + state: web::Data<app::AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<payment_types::PaymentsCancelRequest>, + path: web::Path<common_utils::id_type::GlobalPaymentId>, +) -> impl Responder { + let flow = Flow::PaymentsCancel; + let global_payment_id = path.into_inner(); + + 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.clone(), + payload: json_payload.into_inner(), + }; + + let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { + Ok(headers) => headers, + Err(err) => { + return api::log_and_return_error_response(err); + } + }; + + let locking_action = internal_payload.get_locking_input(flow.clone()); + + Box::pin(api::server_wrap( + flow, + state, + &req, + internal_payload, + |state, auth: auth::AuthenticationData, req, req_state| async { + let payment_id = req.global_payment_id; + let request = req.payload; + + let operation = payments::operations::payment_cancel_v2::PaymentsCancel; + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( + domain::Context(auth.merchant_account, auth.key_store), + )); + + Box::pin(payments::payments_core::< + hyperswitch_domain_models::router_flow_types::Void, + api_models::payments::PaymentsCancelResponse, + _, + _, + _, + hyperswitch_domain_models::payments::PaymentCancelData< + hyperswitch_domain_models::router_flow_types::Void, + >, + >( + state, + req_state, + merchant_context, + auth.profile, + operation, + request, + payment_id, + payments::CallConnectorAction::Trigger, + header_payload.clone(), + )) + .await + }, + auth::auth_type( + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + &auth::JWTAuth { + permission: Permission::ProfilePaymentWrite, + }, + req.headers(), + ), + locking_action, + )) + .await +} + #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCancelPostCapture, payment_id))] pub async fn payments_cancel_post_capture(
2025-08-29T06:04:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add V2 payments_cancel flow by endpoint `{{baseUrl}}/v2/payments/:payment_id/cancel`.A payment can be cancelled when the status is RequiresCapture, PartiallyAuthorizedAndRequiresCapture, or PartiallyCapturedAndCapturable. ### 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)? --> Request: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0199568c7d307cb093a2f9d517fec5cc/cancel' \ --header 'X-Profile-Id: pro_ICrZFKL8QL6GlxNOuGiT' \ --header 'Authorization: api-key=dev_lLeDL7DZk8Vf8vF7PTd53ces09iGYEerHYDBQzle5s1N1QPpzj3pKViOnv7VsQd5' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_lLeDL7DZk8Vf8vF7PTd53ces09iGYEerHYDBQzle5s1N1QPpzj3pKViOnv7VsQd5' \ --data '{ "cancellation_reason": "Requested by Merchant" }' ``` Response: ``` { "id": "12345_pay_019956bfbb0472f28d713b8190b897b7", "status": "cancelled", "cancellation_reason": "Requested by Merchant", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 100, "amount_captured": 0 }, "customer_id": "12345_cus_0199568c731e77d2960fde597ad801ac", "connector": "authorizedotnet", "created": "2025-09-17T08:17:09.937Z", "payment_method_type": "card", "payment_method_subtype": "credit", "attempts": null, "return_url": null } ``` <img width="1314" height="1037" alt="image" src="https://github.com/user-attachments/assets/3e72e0fe-b0a5-46d8-9102-d8431518773d" /> <img width="3600" height="2508" alt="image" src="https://github.com/user-attachments/assets/fe1e4fbe-454a-4684-b009-820c9281b1b1" /> <img width="1228" height="426" alt="image" src="https://github.com/user-attachments/assets/73117c2d-600a-4ee4-bcbd-a43c5b7c55cd" /> closes #9082 ## 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.117.0
213165968462168a59d5c56423a7c10aa04fc186
213165968462168a59d5c56423a7c10aa04fc186
juspay/hyperswitch
juspay__hyperswitch-9056
Bug: Create Subscription with autocollection off Request to Subscription Povider to create subscription curl --location 'https://site/api/v2/customers/AzyUM7UusAXA7mMT/subscription_for_items' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --header 'Authorization: Basic =' \ --data-urlencode 'billing_address%5Bline1%5D=PO Box 9999' \ --data-urlencode 'billing_address%5Bcity%5D=Walnut' \ --data-urlencode 'billing_address%5Bzip%5D=91789' \ --data-urlencode 'billing_address%5Bcountry%5D=US' \ --data-urlencode 'subscription_items%5Bitem_price_id%5D%5B0%5D=cbdemo_enterprise-suite-monthly' \ --data-urlencode 'auto_collection=off' Response from Subscription Provider ``` { "subscription": { "id": "AzyvCyUut31wPEoY", "billing_period": 1, "billing_period_unit": "month", "auto_collection": "off", "customer_id": "AzyUM7UusAXA7mMT", "status": "active", "current_term_start": 1756123927, "current_term_end": 1758802327, "next_billing_at": 1758802327, "created_at": 1756123927, "started_at": 1756123927, "activated_at": 1756123927, "updated_at": 1756123927, "has_scheduled_changes": false, "channel": "web", "resource_version": 1756123927399, "deleted": false, "object": "subscription", "currency_code": "INR", "subscription_items": [ { "item_price_id": "cbdemo_enterprise-suite-monthly", "item_type": "plan", "quantity": 1, "unit_price": 14100, "amount": 14100, "free_quantity": 0, "object": "subscription_item" } ], "due_invoices_count": 1, "due_since": 1756123927, "total_dues": 14100, "mrr": 0, "has_scheduled_advance_invoices": false }, "customer": { "id": "AzyUM7UusAXA7mMT", "first_name": "John", "last_name": "Doe", "email": "john@test.com", "auto_collection": "on", "net_term_days": 0, "allow_direct_debit": false, "created_at": 1756110939, "taxability": "taxable", "updated_at": 1756110939, "locale": "fr-CA", "pii_cleared": "active", "channel": "web", "resource_version": 1756110939077, "deleted": false, "object": "customer", "billing_address": { "first_name": "John", "last_name": "Doe", "line1": "PO Box 9999", "city": "Walnut", "state_code": "CA", "state": "California", "country": "US", "zip": "91789", "validation_status": "not_validated", "object": "billing_address" }, "card_status": "no_card", "promotional_credits": 0, "refundable_credits": 0, "excess_payments": 0, "unbilled_charges": 0, "preferred_currency_code": "INR", "mrr": 0 }, "invoice": { "id": "48", "customer_id": "AzyUM7UusAXA7mMT", "subscription_id": "AzyvCyUut31wPEoY", "recurring": true, "status": "payment_due", "date": 1756123927, "due_date": 1756123927, "net_term_days": 0, "price_type": "tax_exclusive", "exchange_rate": 1.0, "total": 14100, "amount_due": 14100, "amount_adjusted": 0, "amount_paid": 0, "write_off_amount": 0, "credits_applied": 0, "updated_at": 1756123927, "resource_version": 1756123927364, "deleted": false, "object": "invoice", "first_invoice": true, "amount_to_collect": 14100, "round_off_amount": 0, "new_sales_amount": 14100, "has_advance_charges": false, "currency_code": "INR", "base_currency_code": "INR", "generated_at": 1756123927, "is_gifted": false, "term_finalized": true, "channel": "web", "tax": 0, "line_items": [ { "id": "li_AzyvCyUut31yqEoa", "date_from": 1756123927, "date_to": 1758802327, "unit_amount": 14100, "quantity": 1, "amount": 14100, "pricing_model": "flat_fee", "is_taxed": false, "tax_amount": 0, "object": "line_item", "subscription_id": "AzyvCyUut31wPEoY", "customer_id": "AzyUM7UusAXA7mMT", "description": "Enterprise Suite Monthly", "entity_type": "plan_item_price", "entity_id": "cbdemo_enterprise-suite-monthly", "tax_exempt_reason": "tax_not_configured", "discount_amount": 0, "item_level_discount_amount": 0 } ], "sub_total": 14100, "linked_payments": [], "applied_credits": [], "adjustment_credit_notes": [], "issued_credit_notes": [], "linked_orders": [], "dunning_attempts": [], "billing_address": { "first_name": "John", "last_name": "Doe", "line1": "PO Box 9999", "city": "Walnut", "state_code": "CA", "state": "California", "country": "US", "zip": "91789", "validation_status": "not_validated", "object": "billing_address" }, "site_details_at_creation": { "timezone": "Asia/Calcutta" } } } ``` Common Status for Chargebee Recurly and Stripe Billing ``` Common Status Chargebee Recurly Stripe Billing Pending Future - incomplete, Trial InTrial - trialing Active Active ACTIVE active Paused Paused PAUSED paused unpaid - - unpaid Onetime NonRenewing - - Canceled Cancelled, CANCELLED, canceled, Transferred EXPIRED Failed - FAILED incomplete_expired ```
diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee.rs b/crates/hyperswitch_connectors/src/connectors/chargebee.rs index b9006f9e82e..bf6f3fe637d 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee.rs @@ -16,30 +16,38 @@ use error_stack::ResultExt; use hyperswitch_domain_models::{revenue_recovery, router_data_v2::RouterDataV2}; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_data_v2::flow_common_types::SubscriptionCreateData, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, revenue_recovery::InvoiceRecordBack, - subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans}, + subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate}, CreateConnectorCustomer, }, router_request_types::{ revenue_recovery::InvoiceRecordBackRequest, - subscriptions::{GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest}, + subscriptions::{ + GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, + SubscriptionCreateRequest, + }, AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ revenue_recovery::InvoiceRecordBackResponse, - subscriptions::{GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse}, + subscriptions::{ + GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, + SubscriptionCreateResponse, + }, ConnectorInfo, PaymentsResponseData, RefundsResponseData, }, types::{ ConnectorCustomerRouterData, GetSubscriptionPlanPricesRouterData, GetSubscriptionPlansRouterData, InvoiceRecordBackRouterData, PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, + SubscriptionCreateRouterData, }, }; use hyperswitch_interfaces::{ @@ -94,10 +102,117 @@ impl api::Refund for Chargebee {} impl api::RefundExecute for Chargebee {} impl api::RefundSync for Chargebee {} impl api::PaymentToken for Chargebee {} +impl api::subscriptions::Subscriptions for Chargebee {} #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl api::revenue_recovery::RevenueRecoveryRecordBack for Chargebee {} +impl api::subscriptions::SubscriptionCreate for Chargebee {} + +impl ConnectorIntegration<SubscriptionCreate, SubscriptionCreateRequest, SubscriptionCreateResponse> + for Chargebee +{ + fn get_headers( + &self, + req: &SubscriptionCreateRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_url( + &self, + req: &SubscriptionCreateRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let metadata: chargebee::ChargebeeMetadata = + utils::to_connector_meta_from_secret(req.connector_meta_data.clone())?; + let url = self + .base_url(connectors) + .to_string() + .replace("{{merchant_endpoint_prefix}}", metadata.site.peek()); + let customer_id = &req.request.customer_id.get_string_repr().to_string(); + Ok(format!( + "{url}v2/customers/{customer_id}/subscription_for_items" + )) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_request_body( + &self, + req: &SubscriptionCreateRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = chargebee::ChargebeeRouterData::from((MinorUnit::new(0), req)); + let connector_req = + chargebee::ChargebeeSubscriptionCreateRequest::try_from(&connector_router_data)?; + Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &SubscriptionCreateRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::SubscriptionCreateType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::SubscriptionCreateType::get_headers( + self, req, connectors, + )?) + .set_body(types::SubscriptionCreateType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &SubscriptionCreateRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<SubscriptionCreateRouterData, errors::ConnectorError> { + let response: chargebee::ChargebeeSubscriptionCreateResponse = res + .response + .parse_struct("chargebee ChargebeeSubscriptionCreateResponse") + .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 + ConnectorIntegrationV2< + SubscriptionCreate, + SubscriptionCreateData, + SubscriptionCreateRequest, + SubscriptionCreateResponse, + > for Chargebee +{ + // Not Implemented (R) +} + impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Chargebee { @@ -689,7 +804,6 @@ fn get_chargebee_plans_query_params( Ok(param) } -impl api::subscriptions::Subscriptions for Chargebee {} impl api::subscriptions::GetSubscriptionPlansFlow for Chargebee {} impl diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index 7d76b869912..5f16d054890 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -5,7 +5,7 @@ use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::ByteSliceExt, - id_type::CustomerId, + id_type::{CustomerId, SubscriptionId}, pii::{self, Email}, types::MinorUnit, }; @@ -17,14 +17,20 @@ use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, RouterData}, router_flow_types::{ refunds::{Execute, RSync}, + subscriptions::SubscriptionCreate, CreateConnectorCustomer, InvoiceRecordBack, }, router_request_types::{ - revenue_recovery::InvoiceRecordBackRequest, ConnectorCustomerData, ResponseId, + revenue_recovery::InvoiceRecordBackRequest, + subscriptions::{SubscriptionAutoCollection, SubscriptionCreateRequest}, + ConnectorCustomerData, ResponseId, }, router_response_types::{ revenue_recovery::InvoiceRecordBackResponse, - subscriptions::{self, GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse}, + subscriptions::{ + self, GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, + SubscriptionCreateResponse, SubscriptionStatus, + }, ConnectorCustomerResponseData, PaymentsResponseData, RefundsResponseData, }, types::{InvoiceRecordBackRouterData, PaymentsAuthorizeRouterData, RefundsRouterData}, @@ -36,9 +42,158 @@ use time::PrimitiveDateTime; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, - utils::{self, PaymentsAuthorizeRequestData}, + utils::{self, PaymentsAuthorizeRequestData, RouterData as OtherRouterData}, }; +// SubscriptionCreate structures +#[derive(Debug, Serialize)] +pub struct ChargebeeSubscriptionCreateRequest { + #[serde(rename = "id")] + pub subscription_id: SubscriptionId, + #[serde(rename = "subscription_items[item_price_id][0]")] + pub item_price_id: String, + #[serde(rename = "subscription_items[quantity][0]")] + pub quantity: Option<u32>, + #[serde(rename = "billing_address[line1]")] + pub billing_address_line1: Option<Secret<String>>, + #[serde(rename = "billing_address[city]")] + pub billing_address_city: Option<String>, + #[serde(rename = "billing_address[state]")] + pub billing_address_state: Option<Secret<String>>, + #[serde(rename = "billing_address[zip]")] + pub billing_address_zip: Option<Secret<String>>, + #[serde(rename = "billing_address[country]")] + pub billing_address_country: Option<common_enums::CountryAlpha2>, + pub auto_collection: ChargebeeAutoCollection, +} + +#[derive(Debug, Deserialize, Serialize, Clone)] +#[serde(rename_all = "snake_case")] +pub enum ChargebeeAutoCollection { + On, + Off, +} + +impl From<SubscriptionAutoCollection> for ChargebeeAutoCollection { + fn from(auto_collection: SubscriptionAutoCollection) -> Self { + match auto_collection { + SubscriptionAutoCollection::On => Self::On, + SubscriptionAutoCollection::Off => Self::Off, + } + } +} + +impl TryFrom<&ChargebeeRouterData<&hyperswitch_domain_models::types::SubscriptionCreateRouterData>> + for ChargebeeSubscriptionCreateRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &ChargebeeRouterData<&hyperswitch_domain_models::types::SubscriptionCreateRouterData>, + ) -> Result<Self, Self::Error> { + let req = &item.router_data.request; + + let first_item = + req.subscription_items + .first() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "subscription_items", + })?; + + Ok(Self { + subscription_id: req.subscription_id.clone(), + item_price_id: first_item.item_price_id.clone(), + quantity: first_item.quantity, + billing_address_line1: item.router_data.get_optional_billing_line1(), + billing_address_city: item.router_data.get_optional_billing_city(), + billing_address_state: item.router_data.get_optional_billing_state(), + billing_address_zip: item.router_data.get_optional_billing_zip(), + billing_address_country: item.router_data.get_optional_billing_country(), + auto_collection: req.auto_collection.clone().into(), + }) + } +} + +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct ChargebeeSubscriptionCreateResponse { + pub subscription: ChargebeeSubscriptionDetails, +} + +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct ChargebeeSubscriptionDetails { + pub id: SubscriptionId, + pub status: ChargebeeSubscriptionStatus, + pub customer_id: CustomerId, + pub currency_code: enums::Currency, + pub total_dues: Option<MinorUnit>, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub next_billing_at: Option<PrimitiveDateTime>, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub created_at: Option<PrimitiveDateTime>, +} + +#[derive(Debug, Deserialize, Serialize, Clone)] +#[serde(rename_all = "snake_case")] +pub enum ChargebeeSubscriptionStatus { + Future, + #[serde(rename = "in_trial")] + InTrial, + Active, + #[serde(rename = "non_renewing")] + NonRenewing, + Paused, + Cancelled, + Transferred, +} + +impl From<ChargebeeSubscriptionStatus> for SubscriptionStatus { + fn from(status: ChargebeeSubscriptionStatus) -> Self { + match status { + ChargebeeSubscriptionStatus::Future => Self::Pending, + ChargebeeSubscriptionStatus::InTrial => Self::Trial, + ChargebeeSubscriptionStatus::Active => Self::Active, + ChargebeeSubscriptionStatus::NonRenewing => Self::Onetime, + ChargebeeSubscriptionStatus::Paused => Self::Paused, + ChargebeeSubscriptionStatus::Cancelled => Self::Cancelled, + ChargebeeSubscriptionStatus::Transferred => Self::Cancelled, + } + } +} + +impl + TryFrom< + ResponseRouterData< + SubscriptionCreate, + ChargebeeSubscriptionCreateResponse, + SubscriptionCreateRequest, + SubscriptionCreateResponse, + >, + > for hyperswitch_domain_models::types::SubscriptionCreateRouterData +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + SubscriptionCreate, + ChargebeeSubscriptionCreateResponse, + SubscriptionCreateRequest, + SubscriptionCreateResponse, + >, + ) -> Result<Self, Self::Error> { + let subscription = &item.response.subscription; + Ok(Self { + response: Ok(SubscriptionCreateResponse { + subscription_id: subscription.id.clone(), + status: subscription.status.clone().into(), + customer_id: subscription.customer_id.clone(), + currency_code: subscription.currency_code, + total_amount: subscription.total_dues.unwrap_or(MinorUnit::new(0)), + next_billing_at: subscription.next_billing_at, + created_at: subscription.created_at, + }), + ..item.data + }) + } +} + //TODO: Fill the struct with respective fields pub struct ChargebeeRouterData<T> { pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. diff --git a/crates/hyperswitch_connectors/src/connectors/recurly.rs b/crates/hyperswitch_connectors/src/connectors/recurly.rs index abadb7cb199..5bac349e886 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly.rs @@ -10,17 +10,22 @@ use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, ErrorResponse}, router_data_v2::{ - flow_common_types::{GetSubscriptionPlanPricesData, GetSubscriptionPlansData}, + flow_common_types::{ + GetSubscriptionPlanPricesData, GetSubscriptionPlansData, SubscriptionCreateData, + }, UasFlowData, }, router_flow_types::{ - subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans}, + subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate}, unified_authentication_service::{ Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, }, }, router_request_types::{ - subscriptions::{GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest}, + subscriptions::{ + GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, + SubscriptionCreateRequest, + }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, @@ -28,7 +33,7 @@ use hyperswitch_domain_models::{ }, }, router_response_types::subscriptions::{ - GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, + GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, }; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] @@ -168,6 +173,16 @@ impl > for Recurly { } +impl api::subscriptions_v2::SubscriptionsCreateV2 for Recurly {} +impl + ConnectorIntegrationV2< + SubscriptionCreate, + SubscriptionCreateData, + SubscriptionCreateRequest, + SubscriptionCreateResponse, + > for Recurly +{ +} #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl api::revenue_recovery_v2::RevenueRecoveryRecordBackV2 for Recurly {} #[cfg(all(feature = "v2", feature = "revenue_recovery"))] diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 96fbfb6b311..f109ea3fb2f 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -44,10 +44,14 @@ use hyperswitch_domain_models::{ AccessTokenAuthentication, Authenticate, AuthenticationConfirmation, ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow, ExternalVaultProxy, ExternalVaultRetrieveFlow, PostAuthenticate, PreAuthenticate, + SubscriptionCreate as SubscriptionCreateFlow, }, router_request_types::{ authentication, - subscriptions::{GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest}, + subscriptions::{ + GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, + SubscriptionCreateRequest, + }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, @@ -66,7 +70,10 @@ use hyperswitch_domain_models::{ VerifyWebhookSourceRequestData, }, router_response_types::{ - subscriptions::{GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse}, + subscriptions::{ + GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, + SubscriptionCreateResponse, + }, AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData, RetrieveFileResponse, @@ -130,7 +137,10 @@ use hyperswitch_interfaces::{ PaymentsPreAuthenticate, PaymentsPreProcessing, TaxCalculation, }, revenue_recovery::RevenueRecovery, - subscriptions::{GetSubscriptionPlanPricesFlow, GetSubscriptionPlansFlow, Subscriptions}, + subscriptions::{ + GetSubscriptionPlanPricesFlow, GetSubscriptionPlansFlow, SubscriptionCreate, + Subscriptions, + }, vault::{ ExternalVault, ExternalVaultCreate, ExternalVaultDelete, ExternalVaultInsert, ExternalVaultRetrieve, @@ -6941,6 +6951,7 @@ macro_rules! default_imp_for_subscriptions { ($($path:ident::$connector:ident),*) => { $( impl Subscriptions for $path::$connector {} impl GetSubscriptionPlansFlow for $path::$connector {} + impl SubscriptionCreate for $path::$connector {} impl ConnectorIntegration< GetSubscriptionPlans, @@ -6956,6 +6967,12 @@ macro_rules! default_imp_for_subscriptions { GetSubscriptionPlanPricesResponse > for $path::$connector {} + impl + ConnectorIntegration< + SubscriptionCreateFlow, + SubscriptionCreateRequest, + SubscriptionCreateResponse, + > for $path::$connector {} )* }; } @@ -9253,3 +9270,16 @@ impl<const T: u8> > for connectors::DummyConnector<T> { } + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> SubscriptionCreate for connectors::DummyConnector<T> {} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration< + SubscriptionCreateFlow, + SubscriptionCreateRequest, + SubscriptionCreateResponse, + > for connectors::DummyConnector<T> +{ +} diff --git a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs index 759e2f9943b..0d89445b6a3 100644 --- a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs +++ b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs @@ -150,6 +150,9 @@ pub struct FilesFlowData { #[derive(Debug, Clone)] pub struct InvoiceRecordBackData; +#[derive(Debug, Clone)] +pub struct SubscriptionCreateData; + #[derive(Debug, Clone)] pub struct GetSubscriptionPlansData; diff --git a/crates/hyperswitch_domain_models/src/router_flow_types.rs b/crates/hyperswitch_domain_models/src/router_flow_types.rs index dc5418ac8cf..18cf7a53fa6 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types.rs @@ -20,6 +20,7 @@ pub use payments::*; pub use payouts::*; pub use refunds::*; pub use revenue_recovery::*; +pub use subscriptions::*; pub use unified_authentication_service::*; pub use vault::*; pub use webhooks::*; diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs b/crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs index 4f277c07678..28c78e94393 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs @@ -1,4 +1,6 @@ #[derive(Debug, Clone)] +pub struct SubscriptionCreate; +#[derive(Debug, Clone)] pub struct GetSubscriptionPlans; #[derive(Debug, Clone)] diff --git a/crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs b/crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs index bc9049d10f9..832140e1690 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs @@ -1,3 +1,28 @@ +use api_models::payments::Address; +use common_utils::id_type; + +use crate::connector_endpoints; + +#[derive(Debug, Clone)] +pub struct SubscriptionItem { + pub item_price_id: String, + pub quantity: Option<u32>, +} + +#[derive(Debug, Clone)] +pub struct SubscriptionCreateRequest { + pub customer_id: id_type::CustomerId, + pub subscription_id: id_type::SubscriptionId, + pub subscription_items: Vec<SubscriptionItem>, + pub billing_address: Address, + pub auto_collection: SubscriptionAutoCollection, + pub connector_params: connector_endpoints::ConnectorParams, +} +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SubscriptionAutoCollection { + On, + Off, +} #[derive(Debug, Clone)] pub struct GetSubscriptionPlansRequest { pub limit: Option<u32>, diff --git a/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs b/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs index 0b06a6aa269..c61f9fd7ff4 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs @@ -1,4 +1,29 @@ use common_enums::Currency; +use common_utils::{id_type, types::MinorUnit}; +use time::PrimitiveDateTime; + +#[derive(Debug, Clone)] +pub struct SubscriptionCreateResponse { + pub subscription_id: id_type::SubscriptionId, + pub status: SubscriptionStatus, + pub customer_id: id_type::CustomerId, + pub currency_code: Currency, + pub total_amount: MinorUnit, + pub next_billing_at: Option<PrimitiveDateTime>, + pub created_at: Option<PrimitiveDateTime>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SubscriptionStatus { + Pending, + Trial, + Active, + Paused, + Unpaid, + Onetime, + Cancelled, + Failed, +} #[derive(Debug, Clone)] pub struct GetSubscriptionPlansResponse { @@ -21,7 +46,7 @@ pub struct GetSubscriptionPlanPricesResponse { pub struct SubscriptionPlanPrices { pub price_id: String, pub plan_id: Option<String>, - pub amount: common_utils::types::MinorUnit, + pub amount: MinorUnit, pub currency: Currency, pub interval: PeriodUnit, pub interval_count: i64, diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs index cc57f7f82f0..06fbeb267d3 100644 --- a/crates/hyperswitch_domain_models/src/types.rs +++ b/crates/hyperswitch_domain_models/src/types.rs @@ -6,7 +6,7 @@ use crate::{ router_flow_types::{ mandate_revoke::MandateRevoke, revenue_recovery::InvoiceRecordBack, - subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans}, + subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate}, AccessTokenAuth, AccessTokenAuthentication, Authenticate, AuthenticationConfirmation, Authorize, AuthorizeSessionToken, BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, CalculateTax, Capture, CompleteAuthorize, @@ -20,7 +20,10 @@ use crate::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, - subscriptions::{GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest}, + subscriptions::{ + GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, + SubscriptionCreateRequest, + }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, @@ -42,7 +45,10 @@ use crate::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, - subscriptions::{GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse}, + subscriptions::{ + GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, + SubscriptionCreateResponse, + }, GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData, TaxCalculationResponseData, VaultResponseData, VerifyWebhookSourceResponseData, @@ -195,3 +201,6 @@ pub type ExternalVaultProxyPaymentsRouterDataV2 = RouterDataV2< ExternalVaultProxyPaymentsData, PaymentsResponseData, >; + +pub type SubscriptionCreateRouterData = + RouterData<SubscriptionCreate, SubscriptionCreateRequest, SubscriptionCreateResponse>; diff --git a/crates/hyperswitch_interfaces/src/api/subscriptions.rs b/crates/hyperswitch_interfaces/src/api/subscriptions.rs index 7e710c63d13..1d15a7f2b64 100644 --- a/crates/hyperswitch_interfaces/src/api/subscriptions.rs +++ b/crates/hyperswitch_interfaces/src/api/subscriptions.rs @@ -1,12 +1,13 @@ //! Subscriptions Interface for V1 #[cfg(feature = "v1")] use hyperswitch_domain_models::{ + router_flow_types::subscriptions::SubscriptionCreate as SubscriptionCreateFlow, router_flow_types::subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans}, router_request_types::subscriptions::{ - GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, + GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, router_response_types::subscriptions::{ - GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, + GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, }; @@ -37,12 +38,20 @@ pub trait GetSubscriptionPlanPricesFlow: { } +#[cfg(feature = "v1")] +/// trait SubscriptionCreate +pub trait SubscriptionCreate: + ConnectorIntegration<SubscriptionCreateFlow, SubscriptionCreateRequest, SubscriptionCreateResponse> +{ +} + /// trait Subscriptions #[cfg(feature = "v1")] pub trait Subscriptions: ConnectorCommon + GetSubscriptionPlansFlow + GetSubscriptionPlanPricesFlow + + SubscriptionCreate + PaymentsConnectorCustomer { } @@ -62,3 +71,7 @@ pub trait GetSubscriptionPlanPricesFlow {} #[cfg(not(feature = "v1"))] /// trait CreateCustomer (disabled when not V1) pub trait ConnectorCustomer {} + +/// trait SubscriptionCreate +#[cfg(not(feature = "v1"))] +pub trait SubscriptionCreate {} diff --git a/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs b/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs index 609ab2dbc3f..f14d8439e2c 100644 --- a/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs +++ b/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs @@ -1,12 +1,16 @@ //! SubscriptionsV2 use hyperswitch_domain_models::{ - router_data_v2::flow_common_types::{GetSubscriptionPlanPricesData, GetSubscriptionPlansData}, - router_flow_types::subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans}, + router_data_v2::flow_common_types::{ + GetSubscriptionPlanPricesData, GetSubscriptionPlansData, SubscriptionCreateData, + }, + router_flow_types::subscriptions::{ + GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate, + }, router_request_types::subscriptions::{ - GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, + GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, router_response_types::subscriptions::{ - GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, + GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, }; @@ -15,7 +19,7 @@ use crate::connector_integration_v2::ConnectorIntegrationV2; /// trait SubscriptionsV2 pub trait SubscriptionsV2: - GetSubscriptionPlansV2 + ConnectorCustomerV2 + GetSubscriptionPlanPricesV2 + GetSubscriptionPlansV2 + SubscriptionsCreateV2 + ConnectorCustomerV2 + GetSubscriptionPlanPricesV2 { } @@ -40,3 +44,14 @@ pub trait GetSubscriptionPlanPricesV2: > { } + +/// trait SubscriptionsCreateV2 +pub trait SubscriptionsCreateV2: + ConnectorIntegrationV2< + SubscriptionCreate, + SubscriptionCreateData, + SubscriptionCreateRequest, + SubscriptionCreateResponse, +> +{ +} diff --git a/crates/hyperswitch_interfaces/src/conversion_impls.rs b/crates/hyperswitch_interfaces/src/conversion_impls.rs index d119cf332e1..a9d4a1bcd62 100644 --- a/crates/hyperswitch_interfaces/src/conversion_impls.rs +++ b/crates/hyperswitch_interfaces/src/conversion_impls.rs @@ -13,8 +13,8 @@ use hyperswitch_domain_models::{ BillingConnectorPaymentsSyncFlowData, DisputesFlowData, ExternalAuthenticationFlowData, ExternalVaultProxyFlowData, FilesFlowData, GetSubscriptionPlanPricesData, GetSubscriptionPlansData, GiftCardBalanceCheckFlowData, InvoiceRecordBackData, - MandateRevokeFlowData, PaymentFlowData, RefundFlowData, UasFlowData, - VaultConnectorFlowData, WebhookSourceVerifyData, + MandateRevokeFlowData, PaymentFlowData, RefundFlowData, SubscriptionCreateData, + UasFlowData, VaultConnectorFlowData, WebhookSourceVerifyData, }, RouterDataV2, }, @@ -878,6 +878,7 @@ macro_rules! default_router_data_conversion { } default_router_data_conversion!(GetSubscriptionPlansData); default_router_data_conversion!(GetSubscriptionPlanPricesData); +default_router_data_conversion!(SubscriptionCreateData); impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for UasFlowData { fn from_old_router_data( diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs index dbb9ddf8869..d9975a8c058 100644 --- a/crates/hyperswitch_interfaces/src/types.rs +++ b/crates/hyperswitch_interfaces/src/types.rs @@ -16,7 +16,7 @@ use hyperswitch_domain_models::{ }, refunds::{Execute, RSync}, revenue_recovery::{BillingConnectorPaymentsSync, InvoiceRecordBack}, - subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans}, + subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate}, unified_authentication_service::{ Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, }, @@ -32,7 +32,10 @@ use hyperswitch_domain_models::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, - subscriptions::{GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest}, + subscriptions::{ + GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, + SubscriptionCreateRequest, + }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, @@ -57,7 +60,10 @@ use hyperswitch_domain_models::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, - subscriptions::{GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse}, + subscriptions::{ + GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, + SubscriptionCreateResponse, + }, AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, @@ -303,6 +309,13 @@ pub type InvoiceRecordBackType = dyn ConnectorIntegration< InvoiceRecordBackResponse, >; +/// Type alias for `ConnectorIntegration<SubscriptionCreate, SubscriptionCreateRequest, SubscriptionCreateResponse>` +pub type SubscriptionCreateType = dyn ConnectorIntegration< + SubscriptionCreate, + SubscriptionCreateRequest, + SubscriptionCreateResponse, +>; + /// Type alias for `ConnectorIntegration<BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse>` pub type BillingConnectorPaymentsSyncType = dyn ConnectorIntegration< BillingConnectorPaymentsSync, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 4e8970d9309..0fd012e9f7a 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -211,6 +211,9 @@ where Ok(()) } +pub type BoxedSubscriptionConnectorIntegrationInterface<T, Req, Res> = + BoxedConnectorIntegrationInterface<T, common_types::SubscriptionCreateData, Req, Res>; + /// Handle the flow by interacting with connector module /// `connector_request` is applicable only in case if the `CallConnectorAction` is `Trigger` /// In other cases, It will be created if required, even if it is not passed
2025-09-08T10:23:30Z
## 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 Chargebee subscription creation request/response structures. - Implemented conversion traits for Chargebee subscription data. - Enhanced Recurly connector to support subscription creation flows. - Introduced new router flow types and request/response types for subscriptions. - Updated default implementations to include subscription-related traits and integrations. - Added new traits for subscription management in the hyperswitch interfaces. - Implemented conversion logic for subscription data between old and new router data formats. - Updated API service to handle subscription connector integration. Common Status for Chargebee, Recurly and Stripe Billing ``` Common Status Chargebee Recurly Stripe Billing Pending Future - incomplete, Trial InTrial - trialing Active Active ACTIVE active Paused Paused PAUSED paused unpaid - - unpaid Onetime NonRenewing - - Cancelled Cancelled, CANCELLED, canceled, Transferred EXPIRED Failed - FAILED incomplete_expired ``` ### 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 [9056](https://github.com/juspay/hyperswitch/issues/9056) ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Since the API handler is being implemented in a separate PR, this connector integration code cannot be called directly and was tested only by successful compilation of code <img width="996" height="805" alt="image" src="https://github.com/user-attachments/assets/2849b14f-c922-4f63-8ba0-68f5b3e21d29" /> <img width="981" height="623" alt="image" src="https://github.com/user-attachments/assets/b5f2524b-8e46-4c9a-be91-3730d9335865" /> ## 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.117.0
e2f1a456a17645b9ccac771d3608794c4956277d
e2f1a456a17645b9ccac771d3608794c4956277d
juspay/hyperswitch
juspay__hyperswitch-9065
Bug: [FEATURE] Add payment type to Get Intent Response (v2) ### Feature Description We need to return `payment_type` in `Get Intent`. Required by SDK ### Possible Implementation Add a field `payment_type` to Get Intent Response ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 2d9164f8cb5..bfa65cddc9b 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -19157,7 +19157,8 @@ "payment_link_enabled", "request_incremental_authorization", "expires_on", - "request_external_three_ds_authentication" + "request_external_three_ds_authentication", + "payment_type" ], "properties": { "id": { @@ -19318,6 +19319,9 @@ }, "request_external_three_ds_authentication": { "$ref": "#/components/schemas/External3dsAuthenticationRequest" + }, + "payment_type": { + "$ref": "#/components/schemas/PaymentType" } }, "additionalProperties": false diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 5660819cea8..fefbbed0f03 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -654,6 +654,10 @@ pub struct PaymentsIntentResponse { /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, + + /// The type of the payment that differentiates between normal and various types of mandate payments + #[schema(value_type = PaymentType)] + pub payment_type: api_enums::PaymentType, } #[cfg(feature = "v2")] diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index cdd552da14c..4e27e75470b 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -2146,6 +2146,24 @@ where ) -> RouterResponse<Self> { let payment_intent = payment_data.get_payment_intent(); let client_secret = payment_data.get_client_secret(); + + let is_cit_transaction = payment_intent.setup_future_usage.is_off_session(); + + let mandate_type = if payment_intent.customer_present + == common_enums::PresenceOfCustomerDuringPayment::Absent + { + Some(api::MandateTransactionType::RecurringMandateTransaction) + } else if is_cit_transaction { + Some(api::MandateTransactionType::NewMandateTransaction) + } else { + None + }; + + let payment_type = helpers::infer_payment_type( + payment_intent.amount_details.order_amount.into(), + mandate_type.as_ref(), + ); + Ok(services::ApplicationResponse::JsonWithHeaders(( Self { id: payment_intent.id.clone(), @@ -2199,6 +2217,7 @@ where frm_metadata: payment_intent.frm_metadata.clone(), request_external_three_ds_authentication: payment_intent .request_external_three_ds_authentication, + payment_type, }, vec![], )))
2025-08-26T11:00:47Z
## 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 `payment_type` to Payments Get Intent response ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with 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 #9065 ## 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/payments/create-intent' \ --header 'api-key: dev_5DkqRwXafcKhIFXyzwGtSjrnqsQuFWELuWJsepMgoRrjY1AxF7lhtNGeeja9BEHt' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_RAH6QGkLhuQfmi97QhPZ' \ --header 'Authorization: api-key=dev_5DkqRwXafcKhIFXyzwGtSjrnqsQuFWELuWJsepMgoRrjY1AxF7lhtNGeeja9BEHt' \ --data-raw '{ "amount_details": { "order_amount": 1000, "currency": "USD" }, "capture_method": "automatic", "authentication_type": "three_ds", "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 1000 } ], "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": "123456789", "country_code": "+1" }, "email": "user@gmail.com" }, "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "571201", "state": "California", "country": "US" }, "email": "example@example.com", "phone": { "number": "123456789", "country_code": "+1" } }, "customer_id": "12345_cus_0198e5ff10ea7622abbf89f383110c99" }' ``` Response: ```json { "id": "12345_pay_0198e5ff18b77a63ab0e91be36d6f9b7", "status": "requires_payment_method", "amount_details": { "order_amount": 1000, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": "cs_0198e5ff18c57d729ec8fbbb03141331", "profile_id": "pro_RAH6QGkLhuQfmi97QhPZ", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "automatic", "authentication_type": "three_ds", "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", "origin_zip": null }, "phone": { "number": "123456789", "country_code": "+1" }, "email": "user@gmail.com" }, "shipping": { "address": { "city": "Karwar", "country": "US", "line1": null, "line2": null, "line3": null, "zip": "571201", "state": "California", "first_name": "John", "last_name": "Dough", "origin_zip": null }, "phone": { "number": "123456789", "country_code": "+1" }, "email": "example@example.com" }, "customer_id": "12345_cus_0198e5ff10ea7622abbf89f383110c99", "customer_present": "present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 1000, "tax_rate": null, "total_tax_amount": null, "requires_shipping": null, "product_img_link": null, "product_id": null, "category": null, "sub_category": null, "brand": null, "product_type": null, "product_tax_code": null, "description": null, "sku": null, "upc": null, "commodity_code": null, "unit_of_measure": null, "total_amount": null, "unit_discount_amount": null } ], "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "false", "expires_on": "2025-08-26T11:04:17.247Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip", "payment_type": "normal" } ``` ## 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.116.0
30925ca5dd51be93e33ac4492b85c2322263b3fc
30925ca5dd51be93e33ac4492b85c2322263b3fc
juspay/hyperswitch
juspay__hyperswitch-9067
Bug: Use SignatureKey as auth_type for VGS connector We need to collect a 3rd key (vault_id) apart from `username` and `password` in case of VGS for SDK use case
diff --git a/crates/hyperswitch_connectors/src/connectors/vgs/transformers.rs b/crates/hyperswitch_connectors/src/connectors/vgs/transformers.rs index 4915e2da400..4f996c2ffbe 100644 --- a/crates/hyperswitch_connectors/src/connectors/vgs/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/vgs/transformers.rs @@ -74,15 +74,22 @@ impl<F> TryFrom<&VaultRouterData<F>> for VgsInsertRequest { pub struct VgsAuthType { pub(super) username: Secret<String>, pub(super) password: Secret<String>, + // vault_id is used in sessions API + pub(super) _vault_id: Secret<String>, } impl TryFrom<&ConnectorAuthType> for VgsAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { + ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } => Ok(Self { username: api_key.to_owned(), password: key1.to_owned(), + _vault_id: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), }
2025-08-26T11:35:27Z
## 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 --> - Change VGS auth type from BodyKey to SignatureKey ### 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 #9067 ## 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/connector-accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: cloth_seller_v2_WmQmWko8QabakxqCypsz' \ --header 'x-profile-id: pro_vnTuyThRZPNGRWjIHrIt' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "vault_processor", "connector_name": "vgs", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "[REDACTED]", "key1": "[REDACTED]", "api_secret": "[REDACTED]" }, "frm_configs": null, "connector_webhook_details": { "merchant_secret": "" }, "profile_id": "pro_vnTuyThRZPNGRWjIHrIt" }' Response: ```json { "connector_type": "vault_processor", "connector_name": "vgs", "connector_label": "vgs_businesss", "id": "mca_VsS4aBqNwMcPptFn4ZPL", "profile_id": "pro_vnTuyThRZPNGRWjIHrIt", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "US********************q4", "key1": "ca********************************07", "api_secret": "st*ff" }, "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 } ``` ## 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.116.0
30925ca5dd51be93e33ac4492b85c2322263b3fc
30925ca5dd51be93e33ac4492b85c2322263b3fc
juspay/hyperswitch
juspay__hyperswitch-9063
Bug: Change Underscore(_) to hyphen(-) in payment link locale. Change Underscore(_) to hyphen(-) in payment link locale.
diff --git a/crates/router/src/core/payment_link/locale.js b/crates/router/src/core/payment_link/locale.js index 1b2d5c4108b..46103ea9fc5 100644 --- a/crates/router/src/core/payment_link/locale.js +++ b/crates/router/src/core/payment_link/locale.js @@ -3,11 +3,11 @@ The languages supported by locale.js are: 1) English (en) 2) Hebrew (he) 3) French (fr) - 4) British English (en_gb) + 4) British English (en-gb) 5) Arabic (ar) 6) Japanese (ja) 7) German (de) - 8) Belgian French (fr_be) + 8) Belgian French (fr-be) 9) Spanish (es) 10) Catalan (ca) 11) Portuguese (pt) @@ -17,7 +17,7 @@ The languages supported by locale.js are: 15) Swedish (sv) 16) Russian (ru) 17) Chinese (zh) - 19) Traditional Chinese (zh_hant) + 19) Traditional Chinese (zh-hant) */ const locales = { en: { @@ -119,7 +119,7 @@ const locales = { errorCode: "Code d'erreur", errorMessage: "Message d'erreur" }, - en_gb: { + "en-gb": { expiresOn: "Link expires on: ", refId: "Ref Id: ", requestedBy: "Requested by ", @@ -151,7 +151,6 @@ const locales = { notAllowed: "You are not allowed to view this content.", errorCode: "Error code", errorMessage: "Error Message" - }, ar: { expiresOn: "Ψ§Ω„Ψ±Ψ§Ψ¨Ψ· ΩŠΩ†ΨͺΩ‡ΩŠ في: ", @@ -252,7 +251,7 @@ const locales = { errorCode: "Fehlercode", errorMessage: "Fehlermeldung" }, - fr_be: { + "fr-be": { expiresOn: "Le lien expire le: ", refId: "ID de rΓ©fΓ©rence: ", requestedBy: "DemandΓ© par ", @@ -284,7 +283,6 @@ const locales = { notAllowed: "Vous n'Γͺtes pas autorisΓ© Γ  voir ce contenu.", errorCode: "Code d'erreur", errorMessage: "Message d'erreur" - }, es: { expiresOn: "El enlace expira el: ", @@ -384,7 +382,6 @@ const locales = { notAllowed: "VocΓͺ nΓ£o tem permissΓ£o para ver este conteΓΊdo.", errorCode: "CΓ³digo de erro", errorMessage: "Mensagem de erro" - }, it: { expiresOn: "Link scade il: ", @@ -584,7 +581,7 @@ const locales = { errorCode: "错误代码", errorMessage: "错误俑息" }, - zh_hant: { + "zh-hant": { expiresOn: "ι€£η΅εˆ°ζœŸζ—₯期:", refId: "εƒθ€ƒη·¨θ™ŸοΌš", requestedBy: "請求者 ", @@ -628,10 +625,11 @@ function getLanguage(localeStr) { var language = parts[0]; var country = parts.length > 1 ? parts[1] : null; - var key = `${language}_${country}`; + var key = language + '-' + country; switch (key) { - case 'en_gb': return 'en_gb'; - case 'fr_be': return 'fr_be'; + case 'en-gb': return 'en-gb'; + case 'fr-be': return 'fr-be'; + case 'zh-hant': return 'zh-hant'; default: return language; } }
2025-08-26T10:04:02Z
## 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 --> Change Underscore(_) to hyphen(-) in payment link locale according to ISO standards. ### 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). --> We need to follow ISO standards when accepting the locale for payment links. ## 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/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: **' \ --header 'Accept-Language: zh-hant' \ --data '{ "amount": 10, "setup_future_usage": "off_session", "currency": "EUR", "payment_link": true, "session_expiry": 60, "return_url": "https://google.com", "payment_link_config": { "theme": "#14356f", "logo": "https://logo.com/wp-content/uploads/2020/08/zurich.svg", "seller_name": "Zurich Inc." } }' ``` ``` zh-hant - should see traditional chinese zh_hant - english zh-hant-abcdef - traditional chinese zh - simplified chinese Zh - simplified chinese ZH-HANT - traditional chinese zh-abcdef - simplified chinese ``` <img width="2560" height="1440" alt="image" src="https://github.com/user-attachments/assets/a1c25820-6e50-480f-96f6-5a831a856bfd" /> <img width="2560" height="1440" alt="image" src="https://github.com/user-attachments/assets/1db9322d-601e-49df-bf2f-6e5f1911d4cd" /> <img width="2560" height="1440" alt="image" src="https://github.com/user-attachments/assets/d934116c-a24a-479d-86e6-9f0b25028400" /> ## 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.116.0
8446ffbf5992a97d79d129cade997effc60fcd85
8446ffbf5992a97d79d129cade997effc60fcd85
juspay/hyperswitch
juspay__hyperswitch-9062
Bug: [FEATURE] Implement comprehensive event logging for UCS (Unified Connector Service) operations Currently, UCS operations lack proper event logging and observability, making it difficult to debug issues, monitor performance, and track payment flows through the unified connector service.
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 1c689943d73..b9d9b9aa27e 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -20,7 +20,7 @@ use crate::{ unified_connector_service::{ build_unified_connector_service_auth_metadata, handle_unified_connector_service_response_for_payment_authorize, - handle_unified_connector_service_response_for_payment_repeat, + handle_unified_connector_service_response_for_payment_repeat, ucs_logging_wrapper, }, }, logger, @@ -523,20 +523,20 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu merchant_context: &domain::MerchantContext, ) -> RouterResult<()> { if self.request.mandate_id.is_some() { - call_unified_connector_service_repeat_payment( + Box::pin(call_unified_connector_service_repeat_payment( self, state, merchant_connector_account, merchant_context, - ) + )) .await } else { - call_unified_connector_service_authorize( + Box::pin(call_unified_connector_service_authorize( self, state, merchant_connector_account, merchant_context, - ) + )) .await } } @@ -854,33 +854,46 @@ async fn call_unified_connector_service_authorize( .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct request metadata")?; - let response = client - .payment_authorize( - payment_authorize_request, - connector_auth_metadata, - None, - state.get_grpc_headers(), - ) - .await - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to authorize payment")?; - - let payment_authorize_response = response.into_inner(); - - let (status, router_data_response, status_code) = - handle_unified_connector_service_response_for_payment_authorize( - payment_authorize_response.clone(), - ) - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to deserialize UCS response")?; - - router_data.status = status; - router_data.response = router_data_response; - router_data.raw_connector_response = payment_authorize_response - .raw_connector_response - .map(Secret::new); - router_data.connector_http_status_code = Some(status_code); + let updated_router_data = Box::pin(ucs_logging_wrapper( + router_data.clone(), + state, + payment_authorize_request, + |mut router_data, payment_authorize_request| async move { + let response = client + .payment_authorize( + payment_authorize_request, + connector_auth_metadata, + None, + state.get_grpc_headers(), + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to authorize payment")?; + + let payment_authorize_response = response.into_inner(); + + let (status, router_data_response, status_code) = + handle_unified_connector_service_response_for_payment_authorize( + payment_authorize_response.clone(), + ) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize UCS response")?; + + router_data.status = status; + router_data.response = router_data_response; + router_data.raw_connector_response = payment_authorize_response + .raw_connector_response + .clone() + .map(Secret::new); + router_data.connector_http_status_code = Some(status_code); + + Ok((router_data, payment_authorize_response)) + }, + )) + .await?; + // Copy back the updated data + *router_data = updated_router_data; Ok(()) } @@ -903,40 +916,53 @@ async fn call_unified_connector_service_repeat_payment( .attach_printable("Failed to fetch Unified Connector Service client")?; let payment_repeat_request = - payments_grpc::PaymentServiceRepeatEverythingRequest::foreign_try_from(router_data) + payments_grpc::PaymentServiceRepeatEverythingRequest::foreign_try_from(&*router_data) .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to construct Payment Authorize Request")?; + .attach_printable("Failed to construct Payment Repeat Request")?; let connector_auth_metadata = build_unified_connector_service_auth_metadata(merchant_connector_account, merchant_context) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct request metadata")?; - let response = client - .payment_repeat( - payment_repeat_request, - connector_auth_metadata, - state.get_grpc_headers(), - ) - .await - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to authorize payment")?; - - let payment_repeat_response = response.into_inner(); - - let (status, router_data_response, status_code) = - handle_unified_connector_service_response_for_payment_repeat( - payment_repeat_response.clone(), - ) - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to deserialize UCS response")?; - - router_data.status = status; - router_data.response = router_data_response; - router_data.raw_connector_response = payment_repeat_response - .raw_connector_response - .map(Secret::new); - router_data.connector_http_status_code = Some(status_code); + let updated_router_data = Box::pin(ucs_logging_wrapper( + router_data.clone(), + state, + payment_repeat_request, + |mut router_data, payment_repeat_request| async move { + let response = client + .payment_repeat( + payment_repeat_request, + connector_auth_metadata.clone(), + state.get_grpc_headers(), + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to repeat payment")?; + + let payment_repeat_response = response.into_inner(); + + let (status, router_data_response, status_code) = + handle_unified_connector_service_response_for_payment_repeat( + payment_repeat_response.clone(), + ) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize UCS response")?; + + router_data.status = status; + router_data.response = router_data_response; + router_data.raw_connector_response = payment_repeat_response + .raw_connector_response + .clone() + .map(Secret::new); + router_data.connector_http_status_code = Some(status_code); + + Ok((router_data, payment_repeat_response)) + }, + )) + .await?; + // Copy back the updated data + *router_data = updated_router_data; Ok(()) } diff --git a/crates/router/src/core/payments/flows/external_proxy_flow.rs b/crates/router/src/core/payments/flows/external_proxy_flow.rs index ac491685b5d..b184aa60d5e 100644 --- a/crates/router/src/core/payments/flows/external_proxy_flow.rs +++ b/crates/router/src/core/payments/flows/external_proxy_flow.rs @@ -15,7 +15,7 @@ use crate::{ payments::{ self, access_token, customers, helpers, tokenization, transformers, PaymentData, }, - unified_connector_service, + unified_connector_service::{self, ucs_logging_wrapper}, }, logger, routes::{metrics, SessionState}, @@ -394,33 +394,45 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData> .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct external vault proxy metadata")?; - let response = client - .payment_authorize( - payment_authorize_request, - connector_auth_metadata, - Some(external_vault_proxy_metadata), - state.get_grpc_headers(), - ) - .await - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to authorize payment")?; - - let payment_authorize_response = response.into_inner(); + let updated_router_data = Box::pin(ucs_logging_wrapper( + self.clone(), + state, + payment_authorize_request.clone(), + |mut router_data, payment_authorize_request| async move { + let response = client + .payment_authorize( + payment_authorize_request, + connector_auth_metadata, + Some(external_vault_proxy_metadata), + state.get_grpc_headers(), + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to authorize payment")?; - let (status, router_data_response, status_code) = - unified_connector_service::handle_unified_connector_service_response_for_payment_authorize( - payment_authorize_response.clone(), - ) - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to deserialize UCS response")?; + let payment_authorize_response = response.into_inner(); - self.status = status; - self.response = router_data_response; - self.raw_connector_response = payment_authorize_response - .raw_connector_response - .map(masking::Secret::new); - self.connector_http_status_code = Some(status_code); + let (status, router_data_response, status_code) = + unified_connector_service::handle_unified_connector_service_response_for_payment_authorize( + payment_authorize_response.clone(), + ) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize UCS response")?; + + router_data.status = status; + router_data.response = router_data_response; + router_data.raw_connector_response = payment_authorize_response + .raw_connector_response + .clone() + .map(masking::Secret::new); + router_data.connector_http_status_code = Some(status_code); + + Ok((router_data, payment_authorize_response)) + } + )).await?; + // Copy back the updated data + *self = updated_router_data; Ok(()) } } diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index 93a2c1ecd48..802bd3d5bcf 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -13,7 +13,7 @@ use crate::{ payments::{self, access_token, helpers, transformers, PaymentData}, unified_connector_service::{ build_unified_connector_service_auth_metadata, - handle_unified_connector_service_response_for_payment_get, + handle_unified_connector_service_response_for_payment_get, ucs_logging_wrapper, }, }, routes::SessionState, @@ -233,7 +233,7 @@ impl Feature<api::PSync, types::PaymentsSyncData> .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch Unified Connector Service client")?; - let payment_get_request = payments_grpc::PaymentServiceGetRequest::foreign_try_from(self) + let payment_get_request = payments_grpc::PaymentServiceGetRequest::foreign_try_from(&*self) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct Payment Get Request")?; @@ -244,28 +244,45 @@ impl Feature<api::PSync, types::PaymentsSyncData> .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct request metadata")?; - let response = client - .payment_get( - payment_get_request, - connector_auth_metadata, - state.get_grpc_headers(), - ) - .await - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to get payment")?; + let updated_router_data = Box::pin(ucs_logging_wrapper( + self.clone(), + state, + payment_get_request, + |mut router_data, payment_get_request| async move { + let response = client + .payment_get( + payment_get_request, + connector_auth_metadata, + state.get_grpc_headers(), + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get payment")?; + + let payment_get_response = response.into_inner(); - let payment_get_response = response.into_inner(); + let (status, router_data_response, status_code) = + handle_unified_connector_service_response_for_payment_get( + payment_get_response.clone(), + ) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize UCS response")?; - let (status, router_data_response, status_code) = - handle_unified_connector_service_response_for_payment_get(payment_get_response.clone()) - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to deserialize UCS response")?; + router_data.status = status; + router_data.response = router_data_response; + router_data.raw_connector_response = payment_get_response + .raw_connector_response + .clone() + .map(Secret::new); + router_data.connector_http_status_code = Some(status_code); - self.status = status; - self.response = router_data_response; - self.raw_connector_response = payment_get_response.raw_connector_response.map(Secret::new); - self.connector_http_status_code = Some(status_code); + Ok((router_data, payment_get_response)) + }, + )) + .await?; + // Copy back the updated data + *self = updated_router_data; Ok(()) } } diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 035937808c4..6cd1cd1dedc 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -14,7 +14,7 @@ use crate::{ }, unified_connector_service::{ build_unified_connector_service_auth_metadata, - handle_unified_connector_service_response_for_payment_register, + handle_unified_connector_service_response_for_payment_register, ucs_logging_wrapper, }, }, routes::SessionState, @@ -272,7 +272,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup .attach_printable("Failed to fetch Unified Connector Service client")?; let payment_register_request = - payments_grpc::PaymentServiceRegisterRequest::foreign_try_from(self) + payments_grpc::PaymentServiceRegisterRequest::foreign_try_from(&*self) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct Payment Setup Mandate Request")?; @@ -283,33 +283,41 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct request metadata")?; - let response = client - .payment_setup_mandate( - payment_register_request, - connector_auth_metadata, - state.get_grpc_headers(), - ) - .await - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to Setup Mandate payment")?; - - let payment_register_response = response.into_inner(); - - let (status, router_data_response, status_code) = - handle_unified_connector_service_response_for_payment_register( - payment_register_response.clone(), - ) - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to deserialize UCS response")?; - - self.status = status; - self.response = router_data_response; - self.connector_http_status_code = Some(status_code); - // UCS does not return raw connector response for setup mandate right now - // self.raw_connector_response = payment_register_response - // .raw_connector_response - // .map(Secret::new); + let updated_router_data = Box::pin(ucs_logging_wrapper( + self.clone(), + state, + payment_register_request, + |mut router_data, payment_register_request| async move { + let response = client + .payment_setup_mandate( + payment_register_request, + connector_auth_metadata, + state.get_grpc_headers(), + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to Setup Mandate payment")?; + + let payment_register_response = response.into_inner(); + + let (status, router_data_response, status_code) = + handle_unified_connector_service_response_for_payment_register( + payment_register_response.clone(), + ) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize UCS response")?; + + router_data.status = status; + router_data.response = router_data_response; + router_data.connector_http_status_code = Some(status_code); + + Ok((router_data, payment_register_response)) + }, + )) + .await?; + // Copy back the updated data + *self = updated_router_data; Ok(()) } } diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs index 9722f36ae41..e473482b57b 100644 --- a/crates/router/src/core/unified_connector_service.rs +++ b/crates/router/src/core/unified_connector_service.rs @@ -1,4 +1,4 @@ -use std::str::FromStr; +use std::{str::FromStr, time::Instant}; use api_models::admin; #[cfg(feature = "v2")] @@ -23,7 +23,7 @@ use hyperswitch_domain_models::{ router_response_types::PaymentsResponseData, }; use masking::{ExposeInterface, PeekInterface, Secret}; -use router_env::logger; +use router_env::{instrument, logger, tracing}; use unified_connector_service_cards::CardNumber; use unified_connector_service_client::payments::{ self as payments_grpc, payment_method::PaymentMethod, CardDetails, CardPaymentMethodType, @@ -44,6 +44,7 @@ use crate::{ }, utils::get_flow_name, }, + events::connector_api_logs::ConnectorEvent, routes::SessionState, types::transformers::ForeignTryFrom, utils, @@ -804,3 +805,120 @@ pub fn extract_webhook_content_from_ucs_response( ) -> Option<&unified_connector_service_client::payments::WebhookResponseContent> { transform_data.webhook_content.as_ref() } + +/// UCS Event Logging Wrapper Function +/// This function wraps UCS calls with comprehensive event logging. +/// It logs the actual gRPC request/response data, timing, and error information. +#[instrument(skip_all, fields(connector_name, flow_type, payment_id))] +pub async fn ucs_logging_wrapper<T, F, Fut, Req, Resp, GrpcReq, GrpcResp>( + router_data: RouterData<T, Req, Resp>, + state: &SessionState, + grpc_request: GrpcReq, + handler: F, +) -> RouterResult<RouterData<T, Req, Resp>> +where + T: std::fmt::Debug + Clone + Send + 'static, + Req: std::fmt::Debug + Clone + Send + Sync + 'static, + Resp: std::fmt::Debug + Clone + Send + Sync + 'static, + GrpcReq: serde::Serialize, + GrpcResp: serde::Serialize, + F: FnOnce(RouterData<T, Req, Resp>, GrpcReq) -> Fut + Send, + Fut: std::future::Future<Output = RouterResult<(RouterData<T, Req, Resp>, GrpcResp)>> + Send, +{ + tracing::Span::current().record("connector_name", &router_data.connector); + tracing::Span::current().record("flow_type", std::any::type_name::<T>()); + tracing::Span::current().record("payment_id", &router_data.payment_id); + + // Capture request data for logging + let connector_name = router_data.connector.clone(); + let payment_id = router_data.payment_id.clone(); + let merchant_id = router_data.merchant_id.clone(); + let refund_id = router_data.refund_id.clone(); + let dispute_id = router_data.dispute_id.clone(); + + // Log the actual gRPC request with masking + let grpc_request_body = masking::masked_serialize(&grpc_request) + .unwrap_or_else(|_| serde_json::json!({"error": "failed_to_serialize_grpc_request"})); + + // Update connector call count metrics for UCS operations + crate::routes::metrics::CONNECTOR_CALL_COUNT.add( + 1, + router_env::metric_attributes!( + ("connector", connector_name.clone()), + ( + "flow", + std::any::type_name::<T>() + .split("::") + .last() + .unwrap_or_default() + ), + ), + ); + + // Execute UCS function and measure timing + let start_time = Instant::now(); + let result = handler(router_data, grpc_request).await; + let external_latency = start_time.elapsed().as_millis(); + + // Create and emit connector event after UCS call + let (status_code, response_body, router_result) = match result { + Ok((updated_router_data, grpc_response)) => { + let status = updated_router_data + .connector_http_status_code + .unwrap_or(200); + + // Log the actual gRPC response + let grpc_response_body = serde_json::to_value(&grpc_response).unwrap_or_else( + |_| serde_json::json!({"error": "failed_to_serialize_grpc_response"}), + ); + + (status, Some(grpc_response_body), Ok(updated_router_data)) + } + Err(error) => { + // Update error metrics for UCS calls + crate::routes::metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add( + 1, + router_env::metric_attributes!(("connector", connector_name.clone(),)), + ); + + let error_body = serde_json::json!({ + "error": error.to_string(), + "error_type": "ucs_call_failed" + }); + (500, Some(error_body), Err(error)) + } + }; + + let mut connector_event = ConnectorEvent::new( + state.tenant.tenant_id.clone(), + connector_name, + std::any::type_name::<T>(), + grpc_request_body, + "grpc://unified-connector-service".to_string(), + common_utils::request::Method::Post, + payment_id, + merchant_id, + state.request_id.as_ref(), + external_latency, + refund_id, + dispute_id, + status_code, + ); + + // Set response body based on status code + if let Some(body) = response_body { + match status_code { + 400..=599 => { + connector_event.set_error_response_body(&body); + } + _ => { + connector_event.set_response_body(&body); + } + } + } + + // Emit event + state.event_handler.log_event(&connector_event); + + router_result +}
2025-08-25T13:37:59Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Added comprehensive event logging for UCS operations to improve debugging and monitoring. The changes wrap UCS calls with structured logging that captures request/response data, timing, and errors across all payment flows. ### 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)? --> Enable UCS ``` curl --location 'http://localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data ' { "key": "ucs_enabled", "value": "true" }' ``` Enable UCS authorize ```curl --location 'http://localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_ya18hWOxWbhNjQWEacOVLAFiqOuhSsU3k53o5iyEK6IcxQohWPAMpCWGURyRSRYc' \ --data '{ "key": "ucs_rollout_config_merchant_1756126931_razorpay_upi_Authorize", "value": "1.0" }' ``` Payments - Create ```curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Qaanra9EEOfvCZtfveDCXQbYgnzJF7vgwIqBiERdn510eGS9M49jmIZweYS5zC7y' \ --data-raw '{ "amount": 100, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "IatapayCustomer", "email": "[guest@example.com](mailto:guest@example.com)", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com/", "payment_method": "upi", "payment_method_type": "upi_collect", "payment_method_data": { "upi": { "upi_collect": { "vpa_id": "success@razorpay" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "Swangi", "last_name": "Kumari" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[swangi.kumari@juspay.in](mailto:swangi.kumari@juspay.in)" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "all_keys_required": true }' ``` Logs (Success) <img width="1253" height="411" alt="Screenshot 2025-08-28 at 2 46 00β€―PM" src="https://github.com/user-attachments/assets/4fff5e2e-233a-4e42-a3f9-e13c66594808" /> Logs(Failure) <img width="1207" height="503" alt="Screenshot 2025-08-25 at 6 37 32β€―PM" src="https://github.com/user-attachments/assets/6b6f8596-a879-41d4-98ea-2e945376cbe2" /> ## 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.116.0
c02d8b9ba9e204fa163b61c419811eaa65fdbcb4
c02d8b9ba9e204fa163b61c419811eaa65fdbcb4
juspay/hyperswitch
juspay__hyperswitch-9048
Bug: Error for successive config activation
diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index c2e6bc76c06..94d31a73787 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -251,7 +251,7 @@ pub struct DecisionEngineConfigSetupRequest { #[derive(Debug, Serialize, Deserialize, Clone)] pub struct GetDecisionEngineConfigRequest { pub merchant_id: String, - pub config: DecisionEngineDynamicAlgorithmType, + pub algorithm: DecisionEngineDynamicAlgorithmType, } #[derive(Debug, Serialize, Deserialize, Clone)] diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 6094c9826a1..0078bfcea0b 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -28,7 +28,9 @@ use external_services::grpc_client::dynamic_routing::{ success_rate_client::SuccessBasedDynamicRouting, }; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use helpers::update_decision_engine_dynamic_routing_setup; +use helpers::{ + enable_decision_engine_dynamic_routing_setup, update_decision_engine_dynamic_routing_setup, +}; use hyperswitch_domain_models::{mandates, payment_address}; use payment_methods::helpers::StorageErrorExt; use rustc_hash::FxHashSet; @@ -694,7 +696,15 @@ pub async fn link_routing_config( #[cfg(all(feature = "dynamic_routing", feature = "v1"))] { if state.conf.open_router.dynamic_routing_enabled { - update_decision_engine_dynamic_routing_setup( + let existing_config = helpers::get_decision_engine_active_dynamic_routing_algorithm( + &state, + business_profile.get_id(), + api_models::open_router::DecisionEngineDynamicAlgorithmType::SuccessRate, + ) + .await; + + if let Ok(Some(_config)) = existing_config { + update_decision_engine_dynamic_routing_setup( &state, business_profile.get_id(), routing_algorithm.algorithm_data.clone(), @@ -706,6 +716,27 @@ pub async fn link_routing_config( .attach_printable( "Failed to update the success rate routing config in Decision Engine", )?; + } else { + let data: routing_types::SuccessBasedRoutingConfig = + routing_algorithm.algorithm_data + .clone() + .parse_value("SuccessBasedRoutingConfig") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to deserialize SuccessBasedRoutingConfig from routing algorithm data", + )?; + + enable_decision_engine_dynamic_routing_setup( + &state, + business_profile.get_id(), + routing_types::DynamicRoutingType::SuccessRateBasedRouting, + &mut dynamic_routing_ref, + Some(routing_types::DynamicRoutingPayload::SuccessBasedRoutingPayload(data)), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to setup decision engine dynamic routing")?; + } } } } else if routing_algorithm.name == helpers::ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM @@ -725,18 +756,51 @@ pub async fn link_routing_config( #[cfg(all(feature = "dynamic_routing", feature = "v1"))] { if state.conf.open_router.dynamic_routing_enabled { - update_decision_engine_dynamic_routing_setup( + let existing_config = helpers::get_decision_engine_active_dynamic_routing_algorithm( &state, business_profile.get_id(), - routing_algorithm.algorithm_data.clone(), - routing_types::DynamicRoutingType::EliminationRouting, - &mut dynamic_routing_ref, + api_models::open_router::DecisionEngineDynamicAlgorithmType::Elimination, ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "Failed to update the elimination routing config in Decision Engine", - )?; + .await; + + if let Ok(Some(_config)) = existing_config { + update_decision_engine_dynamic_routing_setup( + &state, + business_profile.get_id(), + routing_algorithm.algorithm_data.clone(), + routing_types::DynamicRoutingType::EliminationRouting, + &mut dynamic_routing_ref, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed to update the elimination routing config in Decision Engine", + )?; + } else { + let data: routing_types::EliminationRoutingConfig = + routing_algorithm.algorithm_data + .clone() + .parse_value("EliminationRoutingConfig") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to deserialize EliminationRoutingConfig from routing algorithm data", + )?; + + enable_decision_engine_dynamic_routing_setup( + &state, + business_profile.get_id(), + routing_types::DynamicRoutingType::EliminationRouting, + &mut dynamic_routing_ref, + Some( + routing_types::DynamicRoutingPayload::EliminationRoutingPayload( + data, + ), + ), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to setup decision engine dynamic routing")?; + } } } } else if routing_algorithm.name == helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM { diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 290feb9e306..0b1395ed4ba 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -2307,19 +2307,6 @@ pub async fn create_specific_dynamic_routing_setup( } }; - if state.conf.open_router.dynamic_routing_enabled { - enable_decision_engine_dynamic_routing_setup( - state, - business_profile.get_id(), - dynamic_routing_type, - &mut dynamic_routing_algo_ref, - Some(payload), - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to setup decision engine dynamic routing")?; - } - let record = db .insert_routing_algorithm(algo) .await @@ -2599,7 +2586,7 @@ pub async fn get_decision_engine_active_dynamic_routing_algorithm( ); let request = open_router::GetDecisionEngineConfigRequest { merchant_id: profile_id.get_string_repr().to_owned(), - config: dynamic_routing_type, + algorithm: dynamic_routing_type, }; let response: Option<open_router::DecisionEngineConfigSetupRequest> = routing_utils::ConfigApiClient::send_decision_engine_request(
2025-08-22T11:56:58Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Taged Issue https://github.com/juspay/hyperswitch-cloud/issues/10731 ### Summary This PR refactors **Decision Engine dynamic routing setup** handling inside `link_routing_config` and `create_specific_dynamic_routing_setup` to improve reliability when updating dynamic routing configs. ### Key Changes 1. **Added `enable_decision_engine_dynamic_routing_setup` import** * Alongside `update_decision_engine_dynamic_routing_setup` in `helpers.rs`. 2. **Enhanced error handling for SuccessRate & Elimination routing configs** * Now, we first attempt to update the DE config via `update_decision_engine_dynamic_routing_setup`. * If the update fails, we gracefully fallback to **enabling** the config using `enable_decision_engine_dynamic_routing_setup` with parsed payloads: * `SuccessBasedRoutingConfig` * `EliminationRoutingConfig` 3. **Improved error messages & traceability** * Distinct error messages for update vs. enable flow. * Clearer attachable printables for debugging. 4. **Removed redundant `enable_decision_engine_dynamic_routing_setup` call** in `create_specific_dynamic_routing_setup` to avoid duplicate execution, since setup is now properly handled within `link_routing_config`. ### Why this change? * Previously, DE config updates could silently fail without retry/fallback. * This introduces a safer mechanism: * Try **update** β†’ fallback to **enable** with correct payload. * Ensures merchant routing configs remain in sync with Decision Engine even if updates fail. ### Impact * More reliable DE config synchronization. * Clearer error logs. * Slight increase in control-flow complexity inside `link_routing_config`, but safer handling overall. **Screenshots <img width="1282" height="897" alt="Screenshot 2025-08-25 at 3 18 05β€―PM" src="https://github.com/user-attachments/assets/1c96fefe-edd7-40a3-ba0d-84ea48f56bcb" /> <img width="1282" height="777" alt="Screenshot 2025-08-25 at 3 18 47β€―PM" src="https://github.com/user-attachments/assets/270cb13f-6dd4-41cb-88dc-317004d60a79" /> <img width="1288" height="816" alt="Screenshot 2025-08-25 at 3 19 12β€―PM" src="https://github.com/user-attachments/assets/781ac691-50dc-466d-a272-d5350fa2fbd1" /> <img width="1299" height="849" alt="Screenshot 2025-08-25 at 3 19 37β€―PM" src="https://github.com/user-attachments/assets/862be21c-c330-49a7-8bad-34dc91904fec" /> **Curls and Responses create ``` curl --location 'http://localhost:8080/account/merchant_1756108708/business_profile/pro_hawNVdPoyuXr2njSINGY/dynamic_routing/success_based/create?enable=dynamic_connector_selection' \ --header 'Content-Type: application/json' \ --header 'api-key:*****' \ --data '{ "decision_engine_configs": { "defaultLatencyThreshold": 90, "defaultBucketSize": 200, "defaultHedgingPercent": 5, "subLevelInputConfig": [ { "paymentMethodType": "card", "paymentMethod": "credit", "bucketSize": 250, "hedgingPercent": 1 } ] } }' ``` response ``` { "id": "routing_tVG4bP14dqo4TP7UVPV9", "profile_id": "pro_hawNVdPoyuXr2njSINGY", "name": "Success rate based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1756115463, "modified_at": 1756115463, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` activate ``` curl --location 'http://localhost:8080/routing/routing_tVG4bP14dqo4TP7UVPV9/activate' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_oxFyweqWmRlpg3ZXpKnr5nRQp4JJbrB4uDs85G3mWdCN9F0ZOAtSIvAnfNPhqV1q' \ --data '{}' ``` response ``` { "id": "routing_tVG4bP14dqo4TP7UVPV9", "profile_id": "pro_hawNVdPoyuXr2njSINGY", "name": "Success rate based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1756115463, "modified_at": 1756115463, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` create(new) ``` curl --location 'http://localhost:8080/account/merchant_1756108708/business_profile/pro_hawNVdPoyuXr2njSINGY/dynamic_routing/success_based/create?enable=dynamic_connector_selection' \ --header 'Content-Type: application/json' \ --header 'api-key:****' \ --data '{ "decision_engine_configs": { "defaultLatencyThreshold": 90, "defaultBucketSize": 200, "defaultHedgingPercent": 5, "subLevelInputConfig": [ { "paymentMethodType": "card", "paymentMethod": "credit", "bucketSize": 250, "hedgingPercent": 1 } ] } }' ``` response ``` { "id": "routing_Jhz8tJy37C12jH19m90F", "profile_id": "pro_hawNVdPoyuXr2njSINGY", "name": "Success rate based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1756115557, "modified_at": 1756115557, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` activate(new) ``` curl --location 'http://localhost:8080/routing/routing_Jhz8tJy37C12jH19m90F/activate' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_oxFyweqWmRlpg3ZXpKnr5nRQp4JJbrB4uDs85G3mWdCN9F0ZOAtSIvAnfNPhqV1q' \ --data '{}' ``` response ``` { "id": "routing_Jhz8tJy37C12jH19m90F", "profile_id": "pro_hawNVdPoyuXr2njSINGY", "name": "Success rate based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1756115557, "modified_at": 1756115557, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` activate(old) ``` curl --location 'http://localhost:8080/routing/routing_tVG4bP14dqo4TP7UVPV9/activate' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_oxFyweqWmRlpg3ZXpKnr5nRQp4JJbrB4uDs85G3mWdCN9F0ZOAtSIvAnfNPhqV1q' \ --data '{}' ``` response ``` { "id": "routing_tVG4bP14dqo4TP7UVPV9", "profile_id": "pro_hawNVdPoyuXr2njSINGY", "name": "Success rate based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1756115463, "modified_at": 1756115463, "algorithm_for": "payment", "decision_engine_routing_id": null } ```
v1.116.0
cb34ec51e0f2b4ba071602f5fe974429de542b80
cb34ec51e0f2b4ba071602f5fe974429de542b80
juspay/hyperswitch
juspay__hyperswitch-9055
Bug: Get Estimate for a plan price **Request to Subscription Povider to get estimate** curl --location '/api/v2/estimates/create_subscription_for_items' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --header 'Authorization: Basic =' \ --data-urlencode 'billing_address%5Bline1%5D=PO Box 9999' \ --data-urlencode 'billing_address%5Bcity%5D=Walnut' \ --data-urlencode 'billing_address%5Bzip%5D=91789' \ --data-urlencode 'billing_address%5Bcountry%5D=US' \ --data-urlencode 'subscription_items%5Bitem_price_id%5D%5B0%5D=cbdemo_enterprise-suite-monthly' **Response from Subscription Provider** ``` { "estimate": { "created_at": 1756113388, "object": "estimate", "subscription_estimate": { "status": "active", "next_billing_at": 1758791788, "object": "subscription_estimate", "currency_code": "INR" }, "invoice_estimate": { "recurring": true, "date": 1756113388, "price_type": "tax_exclusive", "sub_total": 14100, "total": 14100, "credits_applied": 0, "amount_paid": 0, "amount_due": 14100, "object": "invoice_estimate", "customer_id": "16BaasUusKoPc107J", "line_items": [ { "id": "li_16BaasUusKoQ8107O", "date_from": 1756113388, "date_to": 1758791788, "unit_amount": 14100, "quantity": 1, "amount": 14100, "pricing_model": "flat_fee", "is_taxed": false, "tax_amount": 0, "object": "line_item", "customer_id": "16BaasUusKoPc107J", "description": "Enterprise Suite Monthly", "entity_type": "plan_item_price", "entity_id": "cbdemo_enterprise-suite-monthly", "discount_amount": 0, "item_level_discount_amount": 0 } ], "taxes": [], "line_item_taxes": [], "line_item_credits": [], "currency_code": "INR", "round_off_amount": 0, "line_item_discounts": [] } } } ```
diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee.rs b/crates/hyperswitch_connectors/src/connectors/chargebee.rs index bf6f3fe637d..b761dc9ebbf 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee.rs @@ -22,14 +22,17 @@ use hyperswitch_domain_models::{ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, revenue_recovery::InvoiceRecordBack, - subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate}, + subscriptions::{ + GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, + SubscriptionCreate, + }, CreateConnectorCustomer, }, router_request_types::{ revenue_recovery::InvoiceRecordBackRequest, subscriptions::{ - GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, - SubscriptionCreateRequest, + GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, + GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, @@ -38,15 +41,16 @@ use hyperswitch_domain_models::{ router_response_types::{ revenue_recovery::InvoiceRecordBackResponse, subscriptions::{ - GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, - SubscriptionCreateResponse, + GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, + GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, ConnectorInfo, PaymentsResponseData, RefundsResponseData, }, types::{ - ConnectorCustomerRouterData, GetSubscriptionPlanPricesRouterData, - GetSubscriptionPlansRouterData, InvoiceRecordBackRouterData, PaymentsAuthorizeRouterData, - PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, + ConnectorCustomerRouterData, GetSubscriptionEstimateRouterData, + GetSubscriptionPlanPricesRouterData, GetSubscriptionPlansRouterData, + InvoiceRecordBackRouterData, PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SubscriptionCreateRouterData, }, }; @@ -1139,6 +1143,94 @@ impl // TODO: implement functions when support enabled } +impl api::subscriptions::GetSubscriptionEstimateFlow for Chargebee {} + +impl + ConnectorIntegration< + GetSubscriptionEstimate, + GetSubscriptionEstimateRequest, + GetSubscriptionEstimateResponse, + > for Chargebee +{ + fn get_headers( + &self, + req: &GetSubscriptionEstimateRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + fn get_url( + &self, + req: &GetSubscriptionEstimateRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let metadata: chargebee::ChargebeeMetadata = + utils::to_connector_meta_from_secret(req.connector_meta_data.clone())?; + let url = self + .base_url(connectors) + .to_string() + .replace("{{merchant_endpoint_prefix}}", metadata.site.peek()); + Ok(format!("{url}v2/estimates/create_subscription_for_items")) + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_request_body( + &self, + req: &GetSubscriptionEstimateRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = chargebee::ChargebeeSubscriptionEstimateRequest::try_from(req)?; + Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) + } + fn build_request( + &self, + req: &GetSubscriptionEstimateRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::GetSubscriptionEstimateType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::GetSubscriptionEstimateType::get_headers( + self, req, connectors, + )?) + .set_body(types::GetSubscriptionEstimateType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + fn handle_response( + &self, + data: &GetSubscriptionEstimateRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<GetSubscriptionEstimateRouterData, errors::ConnectorError> { + let response: chargebee::SubscriptionEstimateResponse = res + .response + .parse_struct("chargebee SubscriptionEstimateResponse") + .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 Chargebee { fn get_webhook_source_verification_signature( diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index 5f16d054890..572cb082a45 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -28,12 +28,16 @@ use hyperswitch_domain_models::{ router_response_types::{ revenue_recovery::InvoiceRecordBackResponse, subscriptions::{ - self, GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, - SubscriptionCreateResponse, SubscriptionStatus, + self, GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, + GetSubscriptionPlansResponse, SubscriptionCreateResponse, SubscriptionLineItem, + SubscriptionStatus, }, ConnectorCustomerResponseData, PaymentsResponseData, RefundsResponseData, }, - types::{InvoiceRecordBackRouterData, PaymentsAuthorizeRouterData, RefundsRouterData}, + types::{ + GetSubscriptionEstimateRouterData, InvoiceRecordBackRouterData, + PaymentsAuthorizeRouterData, RefundsRouterData, + }, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, Secret}; @@ -959,6 +963,50 @@ pub struct ChargebeeItem { pub description: Option<String>, } +impl<F, T> + TryFrom<ResponseRouterData<F, SubscriptionEstimateResponse, T, GetSubscriptionEstimateResponse>> + for RouterData<F, T, GetSubscriptionEstimateResponse> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + F, + SubscriptionEstimateResponse, + T, + GetSubscriptionEstimateResponse, + >, + ) -> Result<Self, Self::Error> { + let estimate = item.response.estimate; + Ok(Self { + response: Ok(GetSubscriptionEstimateResponse { + sub_total: estimate.invoice_estimate.sub_total, + total: estimate.invoice_estimate.total, + amount_paid: Some(estimate.invoice_estimate.amount_paid), + amount_due: Some(estimate.invoice_estimate.amount_due), + currency: estimate.subscription_estimate.currency_code, + next_billing_at: estimate.subscription_estimate.next_billing_at, + credits_applied: Some(estimate.invoice_estimate.credits_applied), + line_items: estimate + .invoice_estimate + .line_items + .into_iter() + .map(|line_item| SubscriptionLineItem { + item_id: line_item.entity_id, + item_type: line_item.entity_type, + description: line_item.description, + amount: line_item.amount, + currency: estimate.invoice_estimate.currency_code, + unit_amount: Some(line_item.unit_amount), + quantity: line_item.quantity, + pricing_model: Some(line_item.pricing_model), + }) + .collect(), + }), + ..item.data + }) + } +} + impl<F, T> TryFrom<ResponseRouterData<F, ChargebeeListPlansResponse, T, GetSubscriptionPlansResponse>> for RouterData<F, T, GetSubscriptionPlansResponse> @@ -1075,6 +1123,18 @@ impl } } +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ChargebeeSubscriptionEstimateRequest { + pub price_id: String, +} + +impl TryFrom<&GetSubscriptionEstimateRouterData> for ChargebeeSubscriptionEstimateRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &GetSubscriptionEstimateRouterData) -> Result<Self, Self::Error> { + let price_id = item.request.price_id.to_owned(); + Ok(Self { price_id }) + } +} #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ChargebeeGetPlanPricesResponse { pub list: Vec<ChargebeeGetPlanPriceList>, @@ -1169,3 +1229,69 @@ impl<F, T> }) } } + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SubscriptionEstimateResponse { + pub estimate: ChargebeeEstimate, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ChargebeeEstimate { + pub created_at: i64, + /// type of the object will be `estimate` + pub object: String, + pub subscription_estimate: SubscriptionEstimate, + pub invoice_estimate: InvoiceEstimate, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SubscriptionEstimate { + pub status: String, + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub next_billing_at: Option<PrimitiveDateTime>, + /// type of the object will be `subscription_estimate` + pub object: String, + pub currency_code: enums::Currency, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct InvoiceEstimate { + pub recurring: bool, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub date: PrimitiveDateTime, + pub price_type: String, + pub sub_total: MinorUnit, + pub total: MinorUnit, + pub credits_applied: MinorUnit, + pub amount_paid: MinorUnit, + pub amount_due: MinorUnit, + /// type of the object will be `invoice_estimate` + pub object: String, + pub customer_id: String, + pub line_items: Vec<LineItem>, + pub currency_code: enums::Currency, + pub round_off_amount: MinorUnit, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LineItem { + pub id: String, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub date_from: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub date_to: PrimitiveDateTime, + pub unit_amount: MinorUnit, + pub quantity: i64, + pub amount: MinorUnit, + pub pricing_model: String, + pub is_taxed: bool, + pub tax_amount: MinorUnit, + /// type of the object will be `line_item` + pub object: String, + pub customer_id: String, + pub description: String, + pub entity_type: String, + pub entity_id: String, + pub discount_amount: MinorUnit, + pub item_level_discount_amount: MinorUnit, +} diff --git a/crates/hyperswitch_connectors/src/connectors/recurly.rs b/crates/hyperswitch_connectors/src/connectors/recurly.rs index 5bac349e886..738a7026c8d 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly.rs @@ -11,20 +11,24 @@ use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, ErrorResponse}, router_data_v2::{ flow_common_types::{ - GetSubscriptionPlanPricesData, GetSubscriptionPlansData, SubscriptionCreateData, + GetSubscriptionEstimateData, GetSubscriptionPlanPricesData, GetSubscriptionPlansData, + SubscriptionCreateData, }, UasFlowData, }, router_flow_types::{ - subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate}, + subscriptions::{ + GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, + SubscriptionCreate, + }, unified_authentication_service::{ Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, }, }, router_request_types::{ subscriptions::{ - GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, - SubscriptionCreateRequest, + GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, + GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, @@ -33,7 +37,8 @@ use hyperswitch_domain_models::{ }, }, router_response_types::subscriptions::{ - GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, + GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, + GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, }; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] @@ -183,6 +188,18 @@ impl > for Recurly { } + +impl api::subscriptions_v2::GetSubscriptionEstimateV2 for Recurly {} +impl + ConnectorIntegrationV2< + GetSubscriptionEstimate, + GetSubscriptionEstimateData, + GetSubscriptionEstimateRequest, + GetSubscriptionEstimateResponse, + > for Recurly +{ +} + #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl api::revenue_recovery_v2::RevenueRecoveryRecordBackV2 for Recurly {} #[cfg(all(feature = "v2", feature = "revenue_recovery"))] diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 057aca866f4..2ed56495797 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -39,7 +39,7 @@ use hyperswitch_domain_models::{ PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, UpdateMetadata, }, - subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans}, + subscriptions::{GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans}, webhooks::VerifyWebhookSource, AccessTokenAuthentication, Authenticate, AuthenticationConfirmation, ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow, @@ -49,8 +49,8 @@ use hyperswitch_domain_models::{ router_request_types::{ authentication, subscriptions::{ - GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, - SubscriptionCreateRequest, + GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, + GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, @@ -71,8 +71,8 @@ use hyperswitch_domain_models::{ }, router_response_types::{ subscriptions::{ - GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, - SubscriptionCreateResponse, + GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, + GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, GiftCardBalanceCheckResponseData, @@ -138,8 +138,8 @@ use hyperswitch_interfaces::{ }, revenue_recovery::RevenueRecovery, subscriptions::{ - GetSubscriptionPlanPricesFlow, GetSubscriptionPlansFlow, SubscriptionCreate, - Subscriptions, + GetSubscriptionEstimateFlow, GetSubscriptionPlanPricesFlow, GetSubscriptionPlansFlow, + SubscriptionCreate, Subscriptions, }, vault::{ ExternalVault, ExternalVaultCreate, ExternalVaultDelete, ExternalVaultInsert, @@ -7069,6 +7069,14 @@ macro_rules! default_imp_for_subscriptions { SubscriptionCreateRequest, SubscriptionCreateResponse, > for $path::$connector {} + impl GetSubscriptionEstimateFlow for $path::$connector {} + impl + ConnectorIntegration< + GetSubscriptionEstimate, + GetSubscriptionEstimateRequest, + GetSubscriptionEstimateResponse + > for $path::$connector + {} )* }; } @@ -9403,3 +9411,15 @@ impl<const T: u8> > for connectors::DummyConnector<T> { } + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> GetSubscriptionEstimateFlow for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration< + GetSubscriptionEstimate, + GetSubscriptionEstimateRequest, + GetSubscriptionEstimateResponse, + > for connectors::DummyConnector<T> +{ +} diff --git a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs index 0d89445b6a3..40be24722a5 100644 --- a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs +++ b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs @@ -159,6 +159,9 @@ pub struct GetSubscriptionPlansData; #[derive(Debug, Clone)] pub struct GetSubscriptionPlanPricesData; +#[derive(Debug, Clone)] +pub struct GetSubscriptionEstimateData; + #[derive(Debug, Clone)] pub struct UasFlowData { pub authenticate_by: String, diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs b/crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs index 28c78e94393..ac4e8388956 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs @@ -5,3 +5,6 @@ pub struct GetSubscriptionPlans; #[derive(Debug, Clone)] pub struct GetSubscriptionPlanPrices; + +#[derive(Debug, Clone)] +pub struct GetSubscriptionEstimate; diff --git a/crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs b/crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs index 832140e1690..8599116e8f4 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs @@ -33,3 +33,8 @@ pub struct GetSubscriptionPlansRequest { pub struct GetSubscriptionPlanPricesRequest { pub plan_price_id: String, } + +#[derive(Debug, Clone)] +pub struct GetSubscriptionEstimateRequest { + pub price_id: String, +} diff --git a/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs b/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs index c61f9fd7ff4..f480765effa 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs @@ -61,3 +61,27 @@ pub enum PeriodUnit { Month, Year, } + +#[derive(Debug, Clone)] +pub struct GetSubscriptionEstimateResponse { + pub sub_total: MinorUnit, + pub total: MinorUnit, + pub credits_applied: Option<MinorUnit>, + pub amount_paid: Option<MinorUnit>, + pub amount_due: Option<MinorUnit>, + pub currency: Currency, + pub next_billing_at: Option<PrimitiveDateTime>, + pub line_items: Vec<SubscriptionLineItem>, +} + +#[derive(Debug, Clone)] +pub struct SubscriptionLineItem { + pub item_id: String, + pub item_type: String, + pub description: String, + pub amount: MinorUnit, + pub currency: Currency, + pub unit_amount: Option<MinorUnit>, + pub quantity: i64, + pub pricing_model: Option<String>, +} diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs index 06fbeb267d3..b170fcf6d98 100644 --- a/crates/hyperswitch_domain_models/src/types.rs +++ b/crates/hyperswitch_domain_models/src/types.rs @@ -6,7 +6,10 @@ use crate::{ router_flow_types::{ mandate_revoke::MandateRevoke, revenue_recovery::InvoiceRecordBack, - subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate}, + subscriptions::{ + GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, + SubscriptionCreate, + }, AccessTokenAuth, AccessTokenAuthentication, Authenticate, AuthenticationConfirmation, Authorize, AuthorizeSessionToken, BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, CalculateTax, Capture, CompleteAuthorize, @@ -21,8 +24,8 @@ use crate::{ InvoiceRecordBackRequest, }, subscriptions::{ - GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, - SubscriptionCreateRequest, + GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, + GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, @@ -46,8 +49,8 @@ use crate::{ InvoiceRecordBackResponse, }, subscriptions::{ - GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, - SubscriptionCreateResponse, + GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, + GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData, TaxCalculationResponseData, VaultResponseData, @@ -144,6 +147,12 @@ pub type InvoiceRecordBackRouterData = pub type GetSubscriptionPlansRouterData = RouterData<GetSubscriptionPlans, GetSubscriptionPlansRequest, GetSubscriptionPlansResponse>; +pub type GetSubscriptionEstimateRouterData = RouterData< + GetSubscriptionEstimate, + GetSubscriptionEstimateRequest, + GetSubscriptionEstimateResponse, +>; + pub type UasAuthenticationRouterData = RouterData<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>; diff --git a/crates/hyperswitch_interfaces/src/api/subscriptions.rs b/crates/hyperswitch_interfaces/src/api/subscriptions.rs index 1d15a7f2b64..bea4c4773ea 100644 --- a/crates/hyperswitch_interfaces/src/api/subscriptions.rs +++ b/crates/hyperswitch_interfaces/src/api/subscriptions.rs @@ -2,12 +2,16 @@ #[cfg(feature = "v1")] use hyperswitch_domain_models::{ router_flow_types::subscriptions::SubscriptionCreate as SubscriptionCreateFlow, - router_flow_types::subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans}, + router_flow_types::subscriptions::{ + GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, + }, router_request_types::subscriptions::{ - GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, SubscriptionCreateRequest, + GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, + GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, router_response_types::subscriptions::{ - GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, + GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, + GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, }; @@ -45,6 +49,16 @@ pub trait SubscriptionCreate: { } +#[cfg(feature = "v1")] +/// trait GetSubscriptionEstimate for V1 +pub trait GetSubscriptionEstimateFlow: + ConnectorIntegration< + GetSubscriptionEstimate, + GetSubscriptionEstimateRequest, + GetSubscriptionEstimateResponse, +> +{ +} /// trait Subscriptions #[cfg(feature = "v1")] pub trait Subscriptions: @@ -53,6 +67,7 @@ pub trait Subscriptions: + GetSubscriptionPlanPricesFlow + SubscriptionCreate + PaymentsConnectorCustomer + + GetSubscriptionEstimateFlow { } @@ -75,3 +90,7 @@ pub trait ConnectorCustomer {} /// trait SubscriptionCreate #[cfg(not(feature = "v1"))] pub trait SubscriptionCreate {} + +/// trait GetSubscriptionEstimateFlow (disabled when not V1) +#[cfg(not(feature = "v1"))] +pub trait GetSubscriptionEstimateFlow {} diff --git a/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs b/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs index f14d8439e2c..09f25918c56 100644 --- a/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs +++ b/crates/hyperswitch_interfaces/src/api/subscriptions_v2.rs @@ -1,16 +1,20 @@ //! SubscriptionsV2 use hyperswitch_domain_models::{ router_data_v2::flow_common_types::{ - GetSubscriptionPlanPricesData, GetSubscriptionPlansData, SubscriptionCreateData, + GetSubscriptionEstimateData, GetSubscriptionPlanPricesData, GetSubscriptionPlansData, + SubscriptionCreateData, }, router_flow_types::subscriptions::{ - GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate, + GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, + SubscriptionCreate, }, router_request_types::subscriptions::{ - GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, SubscriptionCreateRequest, + GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, + GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, router_response_types::subscriptions::{ - GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, + GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, + GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, }; @@ -19,7 +23,11 @@ use crate::connector_integration_v2::ConnectorIntegrationV2; /// trait SubscriptionsV2 pub trait SubscriptionsV2: - GetSubscriptionPlansV2 + SubscriptionsCreateV2 + ConnectorCustomerV2 + GetSubscriptionPlanPricesV2 + GetSubscriptionPlansV2 + + SubscriptionsCreateV2 + + ConnectorCustomerV2 + + GetSubscriptionPlanPricesV2 + + GetSubscriptionEstimateV2 { } @@ -55,3 +63,14 @@ pub trait SubscriptionsCreateV2: > { } + +/// trait GetSubscriptionEstimate for V2 +pub trait GetSubscriptionEstimateV2: + ConnectorIntegrationV2< + GetSubscriptionEstimate, + GetSubscriptionEstimateData, + GetSubscriptionEstimateRequest, + GetSubscriptionEstimateResponse, +> +{ +} diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs index d9975a8c058..5003fdba1c7 100644 --- a/crates/hyperswitch_interfaces/src/types.rs +++ b/crates/hyperswitch_interfaces/src/types.rs @@ -16,7 +16,10 @@ use hyperswitch_domain_models::{ }, refunds::{Execute, RSync}, revenue_recovery::{BillingConnectorPaymentsSync, InvoiceRecordBack}, - subscriptions::{GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate}, + subscriptions::{ + GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, + SubscriptionCreate, + }, unified_authentication_service::{ Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, }, @@ -33,8 +36,8 @@ use hyperswitch_domain_models::{ InvoiceRecordBackRequest, }, subscriptions::{ - GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, - SubscriptionCreateRequest, + GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, + GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, @@ -61,8 +64,8 @@ use hyperswitch_domain_models::{ InvoiceRecordBackResponse, }, subscriptions::{ - GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, - SubscriptionCreateResponse, + GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, + GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData, @@ -361,6 +364,13 @@ pub type GetSubscriptionPlansType = dyn ConnectorIntegration< GetSubscriptionPlansResponse, >; +/// Type alias for `ConnectorIntegration<GetSubscriptionEstimate, GetSubscriptionEstimateRequest, GetSubscriptionEstimateResponse>` +pub type GetSubscriptionEstimateType = dyn ConnectorIntegration< + GetSubscriptionEstimate, + GetSubscriptionEstimateRequest, + GetSubscriptionEstimateResponse, +>; + /// Type alias for `ConnectorIntegration<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData>` pub type ExternalVaultInsertType = dyn ConnectorIntegration<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData>; diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 0fd012e9f7a..c12afb78293 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -110,6 +110,8 @@ pub type BoxedGetSubscriptionPlansInterface<T, Req, Res> = BoxedConnectorIntegrationInterface<T, common_types::GetSubscriptionPlansData, Req, Res>; pub type BoxedGetSubscriptionPlanPricesInterface<T, Req, Res> = BoxedConnectorIntegrationInterface<T, common_types::GetSubscriptionPlanPricesData, Req, Res>; +pub type BoxedGetSubscriptionEstimateInterface<T, Req, Res> = + BoxedConnectorIntegrationInterface<T, common_types::GetSubscriptionEstimateData, Req, Res>; pub type BoxedBillingConnectorInvoiceSyncIntegrationInterface<T, Req, Res> = BoxedConnectorIntegrationInterface< T,
2025-09-10T07:59:34Z
## 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 introduces support for fetching subscription estimates from Chargebee, alongside the existing subscription plans functionality. It adds new data structures, request/response types, and integration logic to handle the "Get Subscription Estimate" flow end-to-end. The changes span the domain models, interface types, and the Chargebee connector implementation. ### 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 #9055 ## 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)? --> Compilation and PR checks are enough for now, as this is a new feature. Testing can be done after the external endpoint is added. ## 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.117.0
3bd78ac5c1ff120d6afd46e02df498a16ece6f5f
3bd78ac5c1ff120d6afd46e02df498a16ece6f5f
juspay/hyperswitch
juspay__hyperswitch-9047
Bug: Payment Intent and MCA changes for split payments - Add split_txns_enabled field in PaymentIntent - Add split_enabled field to MCA payment_method - Code changes to modify split_enabled for a payment method when creating or updating an MCA (similar to recurring_enabled) - PML changes to filter payment methods based on split_enabled in MCA and split_txns_enabled in Intent
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 2d9164f8cb5..9f74aab3a3a 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -19156,6 +19156,7 @@ "apply_mit_exemption", "payment_link_enabled", "request_incremental_authorization", + "split_txns_enabled", "expires_on", "request_external_three_ds_authentication" ], @@ -19306,6 +19307,14 @@ "request_incremental_authorization": { "$ref": "#/components/schemas/RequestIncrementalAuthorization" }, + "split_txns_enabled": { + "allOf": [ + { + "$ref": "#/components/schemas/SplitTxnsEnabled" + } + ], + "default": "skip" + }, "expires_on": { "type": "string", "format": "date-time", @@ -21914,6 +21923,15 @@ } ], "nullable": true + }, + "split_txns_enabled": { + "allOf": [ + { + "$ref": "#/components/schemas/SplitTxnsEnabled" + } + ], + "default": "skip", + "nullable": true } }, "additionalProperties": false @@ -21947,7 +21965,8 @@ "is_tax_connector_enabled", "is_network_tokenization_enabled", "is_click_to_pay_enabled", - "is_clear_pan_retries_enabled" + "is_clear_pan_retries_enabled", + "split_txns_enabled" ], "properties": { "merchant_id": { @@ -22199,6 +22218,14 @@ } ], "nullable": true + }, + "split_txns_enabled": { + "allOf": [ + { + "$ref": "#/components/schemas/SplitTxnsEnabled" + } + ], + "default": "skip" } } }, @@ -24628,6 +24655,13 @@ ], "description": "Charge specific fields for controlling the revert of funds from either platform or connected account. Check sub-fields for more details." }, + "SplitTxnsEnabled": { + "type": "string", + "enum": [ + "enable", + "skip" + ] + }, "StaticRoutingAlgorithm": { "oneOf": [ { diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 2e70e1a6c95..e7d70225884 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -2342,6 +2342,10 @@ pub struct ProfileCreate { /// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior. #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, + + /// Enable split payments, i.e., split the amount between multiple payment methods + #[schema(value_type = Option<SplitTxnsEnabled>, default = "skip")] + pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, } #[cfg(feature = "v1")] @@ -2688,6 +2692,10 @@ pub struct ProfileResponse { /// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior. #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, + + /// Enable split payments, i.e., split the amount between multiple payment methods + #[schema(value_type = SplitTxnsEnabled, default = "skip")] + pub split_txns_enabled: common_enums::SplitTxnsEnabled, } #[cfg(feature = "v1")] @@ -3006,6 +3014,10 @@ pub struct ProfileUpdate { #[schema(value_type = Option<RevenueRecoveryAlgorithmType>, example = "cascading")] pub revenue_recovery_retry_algorithm_type: Option<common_enums::enums::RevenueRecoveryAlgorithmType>, + + /// Enable split payments, i.e., split the amount between multiple payment methods + #[schema(value_type = Option<SplitTxnsEnabled>, default = "skip")] + pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 5660819cea8..c56456e4ce8 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -643,6 +643,10 @@ pub struct PaymentsIntentResponse { #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, + /// Enable split payments, i.e., split the amount between multiple payment methods + #[schema(value_type = SplitTxnsEnabled, default = "skip")] + pub split_txns_enabled: common_enums::SplitTxnsEnabled, + ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 07916214269..cbe1e3f0aab 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2859,6 +2859,29 @@ pub enum RequestIncrementalAuthorization { Default, } +#[derive( + Clone, + Debug, + Copy, + Default, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum SplitTxnsEnabled { + Enable, + #[default] + Skip, +} + #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, strum::Display, ToSchema,)] #[rustfmt::skip] pub enum CountryAlpha3 { diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 8a76b648d0d..a51887a94d6 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -412,6 +412,7 @@ pub struct Profile { pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, + pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, } impl Profile { @@ -487,6 +488,7 @@ pub struct ProfileNew { pub is_iframe_redirection_enabled: Option<bool>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, + pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, } #[cfg(feature = "v2")] @@ -546,6 +548,7 @@ pub struct ProfileUpdateInternal { pub is_iframe_redirection_enabled: Option<bool>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, + pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, } #[cfg(feature = "v2")] @@ -602,6 +605,7 @@ impl ProfileUpdateInternal { external_vault_connector_details, merchant_category_code, merchant_country_code, + split_txns_enabled, } = self; Profile { id: source.id, @@ -698,6 +702,7 @@ impl ProfileUpdateInternal { merchant_category_code: merchant_category_code.or(source.merchant_category_code), merchant_country_code: merchant_country_code.or(source.merchant_country_code), dispute_polling_interval: None, + split_txns_enabled: split_txns_enabled.or(source.split_txns_enabled), } } } diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index acc8d4b21f8..a152d4085df 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -95,6 +95,7 @@ pub struct PaymentIntent { pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>, pub id: common_utils::id_type::GlobalPaymentId, + pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, } #[cfg(feature = "v1")] @@ -355,6 +356,7 @@ pub struct PaymentIntentNew { pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub enable_partial_authorization: Option<bool>, + pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, @@ -800,6 +802,7 @@ impl PaymentIntentUpdateInternal { duty_amount: source.duty_amount, order_date: source.order_date, enable_partial_authorization: None, + split_txns_enabled: source.split_txns_enabled, } } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 4711143d32c..ea3980d942a 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -263,6 +263,8 @@ diesel::table! { revenue_recovery_retry_algorithm_data -> Nullable<Jsonb>, is_external_vault_enabled -> Nullable<Bool>, external_vault_connector_details -> Nullable<Jsonb>, + #[max_length = 16] + split_txns_enabled -> Nullable<Varchar>, } } @@ -1039,6 +1041,8 @@ diesel::table! { payment_link_config -> Nullable<Jsonb>, #[max_length = 64] id -> Varchar, + #[max_length = 16] + split_txns_enabled -> Nullable<Varchar>, } } diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index 44089872660..581754d6017 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -1074,6 +1074,7 @@ pub struct Profile { pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, + pub split_txns_enabled: common_enums::SplitTxnsEnabled, } #[cfg(feature = "v2")] @@ -1131,6 +1132,7 @@ pub struct ProfileSetter { pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, + pub split_txns_enabled: common_enums::SplitTxnsEnabled, } #[cfg(feature = "v2")] @@ -1193,6 +1195,7 @@ impl From<ProfileSetter> for Profile { external_vault_connector_details: value.external_vault_connector_details, merchant_category_code: value.merchant_category_code, merchant_country_code: value.merchant_country_code, + split_txns_enabled: value.split_txns_enabled, } } } @@ -1380,6 +1383,7 @@ pub struct ProfileGeneralUpdate { pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>, + pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, } #[cfg(feature = "v2")] @@ -1461,6 +1465,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { merchant_category_code, merchant_country_code, revenue_recovery_retry_algorithm_type, + split_txns_enabled, } = *update; Self { profile_name, @@ -1514,6 +1519,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { external_vault_connector_details, merchant_category_code, merchant_country_code, + split_txns_enabled, } } ProfileUpdate::RoutingAlgorithmUpdate { @@ -1570,6 +1576,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, + split_txns_enabled: None, }, ProfileUpdate::ExtendedCardInfoUpdate { is_extended_card_info_enabled, @@ -1624,6 +1631,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, + split_txns_enabled: None, }, ProfileUpdate::ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled, @@ -1678,6 +1686,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, + split_txns_enabled: None, }, ProfileUpdate::DefaultRoutingFallbackUpdate { default_fallback_routing, @@ -1732,6 +1741,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, + split_txns_enabled: None, }, ProfileUpdate::NetworkTokenizationUpdate { is_network_tokenization_enabled, @@ -1786,6 +1796,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, + split_txns_enabled: None, }, ProfileUpdate::CollectCvvDuringPaymentUpdate { should_collect_cvv_during_payment, @@ -1840,6 +1851,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, + split_txns_enabled: None, }, ProfileUpdate::DecisionManagerRecordUpdate { three_ds_decision_manager_config, @@ -1894,6 +1906,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, + split_txns_enabled: None, }, ProfileUpdate::CardTestingSecretKeyUpdate { card_testing_secret_key, @@ -1948,6 +1961,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, + split_txns_enabled: None, }, ProfileUpdate::RevenueRecoveryAlgorithmUpdate { revenue_recovery_retry_algorithm_type, @@ -2003,6 +2017,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { external_vault_connector_details: None, merchant_category_code: None, merchant_country_code: None, + split_txns_enabled: None, }, } } @@ -2082,6 +2097,7 @@ impl super::behaviour::Conversion for Profile { merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, dispute_polling_interval: None, + split_txns_enabled: Some(self.split_txns_enabled), }) } @@ -2177,6 +2193,7 @@ impl super::behaviour::Conversion for Profile { external_vault_connector_details: item.external_vault_connector_details, merchant_category_code: item.merchant_category_code, merchant_country_code: item.merchant_country_code, + split_txns_enabled: item.split_txns_enabled.unwrap_or_default(), }) } .await @@ -2247,6 +2264,7 @@ impl super::behaviour::Conversion for Profile { external_vault_connector_details: self.external_vault_connector_details, merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, + split_txns_enabled: Some(self.split_txns_enabled), }) } } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 36eece964f9..134f4fe7a07 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -460,6 +460,8 @@ pub struct PaymentIntent { pub updated_by: String, /// Denotes whether merchant requested for incremental authorization to be enabled for this payment. pub request_incremental_authorization: storage_enums::RequestIncrementalAuthorization, + /// Denotes whether merchant requested for split payments to be enabled for this payment + pub split_txns_enabled: storage_enums::SplitTxnsEnabled, /// Denotes the number of authorizations that have been made for the payment. pub authorization_count: Option<i32>, /// Denotes the client secret expiry for the payment. This is the time at which the client secret will expire. @@ -637,6 +639,7 @@ impl PaymentIntent { request_external_three_ds_authentication: request .request_external_three_ds_authentication .unwrap_or_default(), + split_txns_enabled: profile.split_txns_enabled, frm_metadata: request.frm_metadata, customer_details: None, merchant_reference_id: request.merchant_reference_id, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index c96209d2b4f..8dbdd1761bf 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -752,7 +752,6 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal frm_metadata, request_external_three_ds_authentication: request_external_three_ds_authentication.map(|val| val.as_bool()), - updated_by, force_3ds_challenge, is_iframe_redirection_enabled, @@ -1665,6 +1664,7 @@ impl behaviour::Conversion for PaymentIntent { frm_merchant_decision, updated_by, request_incremental_authorization, + split_txns_enabled, authorization_count, session_expiry, request_external_three_ds_authentication, @@ -1734,6 +1734,7 @@ impl behaviour::Conversion for PaymentIntent { updated_by, request_incremental_authorization: Some(request_incremental_authorization), + split_txns_enabled: Some(split_txns_enabled), authorization_count, session_expiry, request_external_three_ds_authentication: Some( @@ -1887,6 +1888,7 @@ impl behaviour::Conversion for PaymentIntent { request_incremental_authorization: storage_model .request_incremental_authorization .unwrap_or_default(), + split_txns_enabled: storage_model.split_txns_enabled.unwrap_or_default(), authorization_count: storage_model.authorization_count, session_expiry: storage_model.session_expiry, request_external_three_ds_authentication: storage_model @@ -1975,6 +1977,7 @@ impl behaviour::Conversion for PaymentIntent { updated_by: self.updated_by, request_incremental_authorization: Some(self.request_incremental_authorization), + split_txns_enabled: Some(self.split_txns_enabled), authorization_count: self.authorization_count, session_expiry: self.session_expiry, request_external_three_ds_authentication: Some( diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 1c52daa639a..59609e79057 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -644,6 +644,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::MitExemptionRequest, api_models::enums::EnablePaymentLinkRequest, api_models::enums::RequestIncrementalAuthorization, + api_models::enums::SplitTxnsEnabled, api_models::enums::External3dsAuthenticationRequest, api_models::enums::TaxCalculationOverride, api_models::enums::SurchargeCalculationOverride, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 7d625a78396..c3f0cf91dcb 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -3645,6 +3645,7 @@ impl ProfileCreateBridge for api::ProfileCreate { .map(ForeignInto::foreign_into), merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, + split_txns_enabled: self.split_txns_enabled.unwrap_or_default(), })) } } @@ -4133,6 +4134,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, revenue_recovery_retry_algorithm_type, + split_txns_enabled: self.split_txns_enabled, }, ))) } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 8a3594c310c..9aed3766546 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -2195,6 +2195,7 @@ where .clone() .map(ForeignFrom::foreign_from), request_incremental_authorization: payment_intent.request_incremental_authorization, + split_txns_enabled: payment_intent.split_txns_enabled, expires_on: payment_intent.session_expiry, frm_metadata: payment_intent.frm_metadata.clone(), request_external_three_ds_authentication: payment_intent diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs index e5caffc4a54..85cf80cd8a7 100644 --- a/crates/router/src/services/kafka/payment_intent.rs +++ b/crates/router/src/services/kafka/payment_intent.rs @@ -143,6 +143,7 @@ pub struct KafkaPaymentIntent<'a> { pub updated_by: &'a String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: RequestIncrementalAuthorization, + pub split_txns_enabled: common_enums::SplitTxnsEnabled, pub authorization_count: Option<i32>, #[serde(with = "time::serde::timestamp")] pub session_expiry: OffsetDateTime, @@ -209,6 +210,7 @@ impl<'a> KafkaPaymentIntent<'a> { frm_merchant_decision, updated_by, request_incremental_authorization, + split_txns_enabled, authorization_count, session_expiry, request_external_three_ds_authentication, @@ -265,6 +267,7 @@ impl<'a> KafkaPaymentIntent<'a> { updated_by, surcharge_applicable: None, request_incremental_authorization: *request_incremental_authorization, + split_txns_enabled: *split_txns_enabled, authorization_count: *authorization_count, session_expiry: session_expiry.assume_utc(), request_external_three_ds_authentication: *request_external_three_ds_authentication, diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs index db6de3cce1e..edfb570901a 100644 --- a/crates/router/src/services/kafka/payment_intent_event.rs +++ b/crates/router/src/services/kafka/payment_intent_event.rs @@ -96,6 +96,7 @@ pub struct KafkaPaymentIntentEvent<'a> { pub updated_by: &'a String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: RequestIncrementalAuthorization, + pub split_txns_enabled: common_enums::SplitTxnsEnabled, pub authorization_count: Option<i32>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub session_expiry: OffsetDateTime, @@ -221,6 +222,7 @@ impl<'a> KafkaPaymentIntentEvent<'a> { frm_merchant_decision, updated_by, request_incremental_authorization, + split_txns_enabled, authorization_count, session_expiry, request_external_three_ds_authentication, @@ -277,6 +279,7 @@ impl<'a> KafkaPaymentIntentEvent<'a> { updated_by, surcharge_applicable: None, request_incremental_authorization: *request_incremental_authorization, + split_txns_enabled: *split_txns_enabled, authorization_count: *authorization_count, session_expiry: session_expiry.assume_utc(), request_external_three_ds_authentication: *request_external_three_ds_authentication, diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index e0866e13eb8..8035959dd35 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -319,6 +319,7 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse { .map(ForeignInto::foreign_into), merchant_category_code: item.merchant_category_code, merchant_country_code: item.merchant_country_code, + split_txns_enabled: item.split_txns_enabled, }) } } diff --git a/v2_compatible_migrations/2025-08-25-090221_add-split-txns-enabled-in-payment-intent/down.sql b/v2_compatible_migrations/2025-08-25-090221_add-split-txns-enabled-in-payment-intent/down.sql new file mode 100644 index 00000000000..becd303be31 --- /dev/null +++ b/v2_compatible_migrations/2025-08-25-090221_add-split-txns-enabled-in-payment-intent/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_intent DROP COLUMN IF EXISTS split_txns_enabled; diff --git a/v2_compatible_migrations/2025-08-25-090221_add-split-txns-enabled-in-payment-intent/up.sql b/v2_compatible_migrations/2025-08-25-090221_add-split-txns-enabled-in-payment-intent/up.sql new file mode 100644 index 00000000000..c765ec9e037 --- /dev/null +++ b/v2_compatible_migrations/2025-08-25-090221_add-split-txns-enabled-in-payment-intent/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS split_txns_enabled VARCHAR(16); \ No newline at end of file diff --git a/v2_compatible_migrations/2025-08-29-040411_add-split-txns-enabled-in-business-profile/down.sql b/v2_compatible_migrations/2025-08-29-040411_add-split-txns-enabled-in-business-profile/down.sql new file mode 100644 index 00000000000..a0fb7698515 --- /dev/null +++ b/v2_compatible_migrations/2025-08-29-040411_add-split-txns-enabled-in-business-profile/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE business_profile DROP COLUMN IF EXISTS split_txns_enabled; \ No newline at end of file diff --git a/v2_compatible_migrations/2025-08-29-040411_add-split-txns-enabled-in-business-profile/up.sql b/v2_compatible_migrations/2025-08-29-040411_add-split-txns-enabled-in-business-profile/up.sql new file mode 100644 index 00000000000..d5cc041c284 --- /dev/null +++ b/v2_compatible_migrations/2025-08-29-040411_add-split-txns-enabled-in-business-profile/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS split_txns_enabled VARCHAR(16); \ No newline at end of file
2025-08-25T09:13:26Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Add split_txns_enabled field to business_profile DB, create+update API calls - Add split_txns_enabled field in PaymentIntent - PML changes to filter payment methods based on split_enabled in MCA and split_txns_enabled in Intent ### 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 #9047 ## 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. Business Profile Create Request (split_txns_enabled) ``` curl --location 'http://localhost:8080/v2/profiles' \ --header 'x-merchant-id: cloth_seller_v2_5WeDFMHDxeA6s3I9WReI' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "profile_name": "businesss", "return_url": "https://google.com/success", ... "split_txns_enabled": "enable" }' ``` Response: ```json { "merchant_id": "cloth_seller_v2_5WeDFMHDxeA6s3I9WReI", "id": "pro_ayVzG5Zr33W31ArJk7CK", "profile_name": "businesss", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "c94j5uGyFCAIU1N24p3mVl9DKLrSCN0xslChyzawzX1gwvSynCgpX6vS39JuA0J9", "redirect_to_merchant_with_http_post": false, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": "https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true, "payment_statuses_enabled": null, "refund_statuses_enabled": null, "payout_statuses_enabled": null }, "metadata": 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_if_required": false, "collect_billing_details_from_wallet_connector_if_required": false, "always_collect_shipping_details_from_wallet_connector": false, "always_collect_billing_details_from_wallet_connector": false, "is_connector_agnostic_mit_enabled": false, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "order_fulfillment_time": 900, "order_fulfillment_time_origin": "create", "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false, "should_collect_cvv_during_payment": null, "is_click_to_pay_enabled": false, "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, "is_debit_routing_enabled": false, "merchant_business_country": null, "is_iframe_redirection_enabled": null, "is_external_vault_enabled": null, "external_vault_connector_details": null, "merchant_category_code": null, "merchant_country_code": null, "split_txns_enabled": "enable" } ``` 2. Payment Intent Create Request ``` curl --location 'http://localhost:8080/v2/payments/create-intent' \ --header 'api-key: dev_xjdI9HLJv4OJIab8VojIjDWbXN3i4a50fzUaxgaQjtP3vwL3WmQVwNbgNmA9M5DV' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_dPNtC5bK3lNxBYt7kyk4' \ --header 'Authorization: api-key=dev_xjdI9HLJv4OJIab8VojIjDWbXN3i4a50fzUaxgaQjtP3vwL3WmQVwNbgNmA9M5DV' \ --data-raw '{ "amount_details": { "order_amount": 1000, "currency": "USD" }, "capture_method": "automatic", "authentication_type": "three_ds", "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 1000 } ], "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": "123456789", "country_code": "+1" }, "email": "user@gmail.com" }, "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "571201", "state": "California", "country": "US" }, "email": "example@example.com", "phone": { "number": "123456789", "country_code": "+1" } }, "customer_id": "12345_cus_0198e54d6c3b7871bcfde4a50ee43b88" }' ``` ```json { "id": "12345_pay_0198e54f328775408faf14fc2c47651a", "status": "requires_payment_method", "amount_details": { "order_amount": 1000, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": "cs_0198e54f32b07003a723ffba50f47fea", "profile_id": "pro_dPNtC5bK3lNxBYt7kyk4", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "automatic", "authentication_type": "three_ds", "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", "origin_zip": null }, "phone": { "number": "123456789", "country_code": "+1" }, "email": "user@gmail.com" }, "shipping": { "address": { "city": "Karwar", "country": "US", "line1": null, "line2": null, "line3": null, "zip": "571201", "state": "California", "first_name": "John", "last_name": "Dough", "origin_zip": null }, "phone": { "number": "123456789", "country_code": "+1" }, "email": "example@example.com" }, "customer_id": "12345_cus_0198e54d6c3b7871bcfde4a50ee43b88", "customer_present": "present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 1000, "tax_rate": null, "total_tax_amount": null, "requires_shipping": null, "product_img_link": null, "product_id": null, "category": null, "sub_category": null, "brand": null, "product_type": null, "product_tax_code": null, "description": null, "sku": null, "upc": null, "commodity_code": null, "unit_of_measure": null, "total_amount": null, "unit_discount_amount": null } ], "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "false", "split_txns_enabled": "true", "expires_on": "2025-08-26T07:52:09.530Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip" } ``` ## 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.116.0
9f0cd51cabb281de82b00734b532fea3cf6205fe
9f0cd51cabb281de82b00734b532fea3cf6205fe
juspay/hyperswitch
juspay__hyperswitch-9034
Bug: [BUG] CUSTOMERREQUEST refund reason not supported in Adyen ### Bug Description CUSTOMERREQUEST refund reason not supported in Adyen ### Expected Behavior CUSTOMERREQUEST refund reason should be supported in Adyen. ### Actual Behavior CUSTOMERREQUEST refund reason not supported in Adyen ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index 63c1b0d8a32..f30732173a7 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -1415,7 +1415,7 @@ impl FromStr for AdyenRefundRequestReason { fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_uppercase().as_str() { "FRAUD" => Ok(Self::FRAUD), - "CUSTOMER REQUEST" => Ok(Self::CUSTOMERREQUEST), + "CUSTOMER REQUEST" | "CUSTOMERREQUEST" => Ok(Self::CUSTOMERREQUEST), "RETURN" => Ok(Self::RETURN), "DUPLICATE" => Ok(Self::DUPLICATE), "OTHER" => Ok(Self::OTHER),
2025-08-22T11:28:33Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/9034) ## Description <!-- Describe your changes in detail --> Added Support for CUSTOMERREQUEST Refund Reason in Adyen ### 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: Refunds: Request: ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_KYKqKi3f1IgAl2wzfLwajdyMApB5XvTmX7SjYWpAcuLRnYxXToxXjDDuMoKPJ5h2' \ --data '{ "payment_id": "pay_rcvdW42PBSd2ik1tYEpA", "amount": 1000, "reason": "CustomerRequest", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response: ``` { "refund_id": "ref_3UOUCY4WziTz0iWhRGjT", "payment_id": "pay_rcvdW42PBSd2ik1tYEpA", "amount": 1000, "currency": "USD", "status": "pending", "reason": "CUSTOMER REQUEST", "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-08-06T04:02:37.782Z", "updated_at": "2025-08-06T04:02:39.280Z", "connector": "adyen", "profile_id": "pro_H4NAjXx3vY9NI4nQbXom", "merchant_connector_id": "mca_EC2PLdAi5hhl8zAKbt0G", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": 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.116.0
c90625a4ea163e03895276a04ec3a23d4117413d
c90625a4ea163e03895276a04ec3a23d4117413d
juspay/hyperswitch
juspay__hyperswitch-9023
Bug: Vault connector changes Need to implement Vault Retrieve for VGS
diff --git a/config/config.example.toml b/config/config.example.toml index ab7f0ebdef8..e9e51123925 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -309,7 +309,7 @@ trustpayments.base_url = "https://webservices.securetrading.net/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://stagegw.transnox.com/" unified_authentication_service.base_url = "http://localhost:8000" -vgs.base_url = "https://sandbox.vault-api.verygoodvault.com" +vgs.base_url = "https://api.sandbox.verygoodvault.com/" volt.base_url = "https://api.sandbox.volt.io/" wellsfargo.base_url = "https://apitest.cybersource.com/" wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index a8c1fcfd662..6f78f4ceeef 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -144,7 +144,7 @@ trustpay.base_url = "https://test-tpgw.trustpay.eu/" trustpayments.base_url = "https://webservices.securetrading.net/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://stagegw.transnox.com/" -vgs.base_url = "https://sandbox.vault-api.verygoodvault.com" +vgs.base_url = "https://api.sandbox.verygoodvault.com/" volt.base_url = "https://api.sandbox.volt.io/" wellsfargo.base_url = "https://apitest.cybersource.com/" wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 1900a06ff79..25208f9081b 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -148,7 +148,7 @@ trustpay.base_url = "https://tpgw.trustpay.eu/" trustpayments.base_url = "https://webservices.securetrading.net/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://gateway.transit-pass.com/" -vgs.base_url = "https://sandbox.vault-api.verygoodvault.com" +vgs.base_url = "https://api.live.verygoodvault.com/" volt.base_url = "https://api.volt.io/" wellsfargo.base_url = "https://api.cybersource.com/" wellsfargopayout.base_url = "https://api.wellsfargo.com/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 3c7070879e5..2eb25d54754 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -148,7 +148,7 @@ trustpay.base_url = "https://test-tpgw.trustpay.eu/" trustpayments.base_url = "https://webservices.securetrading.net/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://stagegw.transnox.com/" -vgs.base_url = "https://sandbox.vault-api.verygoodvault.com" +vgs.base_url = "https://api.sandbox.verygoodvault.com/" volt.base_url = "https://api.sandbox.volt.io/" wellsfargo.base_url = "https://apitest.cybersource.com/" wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/" diff --git a/config/development.toml b/config/development.toml index 9380fa7e6e9..32f7a9441ba 100644 --- a/config/development.toml +++ b/config/development.toml @@ -355,7 +355,7 @@ trustpay.base_url = "https://test-tpgw.trustpay.eu/" trustpayments.base_url = "https://webservices.securetrading.net/" tsys.base_url = "https://stagegw.transnox.com/" unified_authentication_service.base_url = "http://localhost:8000/" -vgs.base_url = "https://sandbox.vault-api.verygoodvault.com" +vgs.base_url = "https://api.sandbox.verygoodvault.com/" volt.base_url = "https://api.sandbox.volt.io/" wellsfargo.base_url = "https://apitest.cybersource.com/" wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index dcf86bbcfa5..6c11cc9bef9 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -235,7 +235,7 @@ trustpayments.base_url = "https://webservices.securetrading.net/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://stagegw.transnox.com/" unified_authentication_service.base_url = "http://localhost:8000" -vgs.base_url = "https://sandbox.vault-api.verygoodvault.com" +vgs.base_url = "https://api.sandbox.verygoodvault.com/" volt.base_url = "https://api.sandbox.volt.io/" wellsfargo.base_url = "https://apitest.cybersource.com/" wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/" diff --git a/crates/hyperswitch_connectors/src/connectors/vgs.rs b/crates/hyperswitch_connectors/src/connectors/vgs.rs index 68751d6e44a..d7bdf4522eb 100644 --- a/crates/hyperswitch_connectors/src/connectors/vgs.rs +++ b/crates/hyperswitch_connectors/src/connectors/vgs.rs @@ -1,10 +1,10 @@ pub mod transformers; +use base64::Engine; 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::{ @@ -13,17 +13,15 @@ use hyperswitch_domain_models::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, + ExternalVaultInsertFlow, ExternalVaultRetrieveFlow, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, - RefundsData, SetupMandateRequestData, - }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, - types::{ - PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, - RefundSyncRouterData, RefundsRouterData, + RefundsData, SetupMandateRequestData, VaultRequestData, }, + router_response_types::{PaymentsResponseData, RefundsResponseData, VaultResponseData}, + types::VaultRouterData, }; use hyperswitch_interfaces::{ api::{ @@ -36,23 +34,13 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks, }; -use masking::{ExposeInterface, Mask}; +use masking::Mask; use transformers as vgs; -use crate::{constants::headers, types::ResponseRouterData, utils}; +use crate::{constants::headers, types::ResponseRouterData}; #[derive(Clone)] -pub struct Vgs { - amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), -} - -impl Vgs { - pub fn new() -> &'static Self { - &Self { - amount_converter: &StringMinorUnitForConnector, - } - } -} +pub struct Vgs; impl api::Payment for Vgs {} impl api::PaymentSession for Vgs {} @@ -66,6 +54,9 @@ impl api::Refund for Vgs {} impl api::RefundExecute for Vgs {} impl api::RefundSync for Vgs {} impl api::PaymentToken for Vgs {} +impl api::ExternalVaultInsert for Vgs {} +impl api::ExternalVault for Vgs {} +impl api::ExternalVaultRetrieve for Vgs {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Vgs @@ -82,13 +73,21 @@ where 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) + let auth = vgs::VgsAuthType::try_from(&req.connector_auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let auth_value = auth + .username + .zip(auth.password) + .map(|(username, password)| { + format!( + "Basic {}", + common_utils::consts::BASE64_ENGINE.encode(format!("{username}:{password}")) + ) + }); + Ok(vec![( + headers::AUTHORIZATION.to_string(), + auth_value.into_masked(), + )]) } } @@ -111,14 +110,9 @@ impl ConnectorCommon for Vgs { fn get_auth_header( &self, - auth_type: &ConnectorAuthType, + _auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - let auth = vgs::VgsAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - Ok(vec![( - headers::AUTHORIZATION.to_string(), - auth.username.expose().into_masked(), - )]) + Ok(vec![]) } fn build_error_response( @@ -134,11 +128,16 @@ impl ConnectorCommon for Vgs { event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + let error = response + .errors + .first() + .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; + Ok(ErrorResponse { status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, + code: error.code.clone(), + message: error.code.clone(), + reason: error.detail.clone(), attempt_status: None, connector_transaction_id: None, network_decline_code: None, @@ -149,212 +148,68 @@ impl ConnectorCommon for Vgs { } } -impl ConnectorValidation for Vgs { - //TODO: implement functions when support enabled -} +impl ConnectorValidation for Vgs {} -impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Vgs { - //TODO: implement sessions flow -} +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Vgs {} impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Vgs {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Vgs {} -impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Vgs { - 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() - } +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Vgs {} - 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 = vgs::VgsRouterData::from((amount, req)); - let connector_req = vgs::VgsPaymentsRequest::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(), - )) - } +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Vgs {} - fn handle_response( - &self, - data: &PaymentsAuthorizeRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: vgs::VgsPaymentsResponse = res - .response - .parse_struct("Vgs 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, - }) - } +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Vgs {} - 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 Vgs {} -impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Vgs { - fn get_headers( - &self, - req: &PaymentsSyncRouterData, - connectors: &Connectors, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Vgs {} - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Vgs {} +impl ConnectorIntegration<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData> for Vgs { 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, + _req: &VaultRouterData<ExternalVaultInsertFlow>, 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: vgs::VgsPaymentsResponse = res - .response - .parse_struct("vgs 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, - }) + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}aliases", self.base_url(connectors))) } - 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 Vgs { fn get_headers( &self, - req: &PaymentsCaptureRouterData, + req: &VaultRouterData<ExternalVaultInsertFlow>, 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, + req: &VaultRouterData<ExternalVaultInsertFlow>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + let connector_req = vgs::VgsInsertRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, - req: &PaymentsCaptureRouterData, + req: &VaultRouterData<ExternalVaultInsertFlow>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) - .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .url(&types::ExternalVaultInsertType::get_url( + self, req, connectors, + )?) .attach_default_headers() - .headers(types::PaymentsCaptureType::get_headers( + .headers(types::ExternalVaultInsertType::get_headers( self, req, connectors, )?) - .set_body(types::PaymentsCaptureType::get_request_body( + .set_body(types::ExternalVaultInsertType::get_request_body( self, req, connectors, )?) .build(), @@ -363,13 +218,13 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo fn handle_response( &self, - data: &PaymentsCaptureRouterData, + data: &VaultRouterData<ExternalVaultInsertFlow>, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { - let response: vgs::VgsPaymentsResponse = res + ) -> CustomResult<VaultRouterData<ExternalVaultInsertFlow>, errors::ConnectorError> { + let response: vgs::VgsInsertResponse = res .response - .parse_struct("Vgs PaymentsCaptureResponse") + .parse_struct("VgsInsertResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -389,125 +244,46 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo } } -impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Vgs {} - -impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Vgs { - 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() - } - +impl ConnectorIntegration<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData> for Vgs { fn get_url( &self, - _req: &RefundsRouterData<Execute>, - _connectors: &Connectors, + req: &VaultRouterData<ExternalVaultRetrieveFlow>, + 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 alias = req.request.connector_vault_id.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "connector_vault_id", + }, )?; - let connector_router_data = vgs::VgsRouterData::from((refund_amount, req)); - let connector_req = vgs::VgsRefundRequest::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: vgs::RefundResponse = res - .response - .parse_struct("vgs 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) + Ok(format!("{}aliases/{alias}", self.base_url(connectors))) } -} -impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Vgs { fn get_headers( &self, - req: &RefundSyncRouterData, + req: &VaultRouterData<ExternalVaultRetrieveFlow>, 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 get_http_method(&self) -> Method { + Method::Get } fn build_request( &self, - req: &RefundSyncRouterData, + req: &VaultRouterData<ExternalVaultRetrieveFlow>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) - .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .url(&types::ExternalVaultRetrieveType::get_url( + self, req, connectors, + )?) .attach_default_headers() - .headers(types::RefundSyncType::get_headers(self, req, connectors)?) - .set_body(types::RefundSyncType::get_request_body( + .headers(types::ExternalVaultRetrieveType::get_headers( self, req, connectors, )?) .build(), @@ -516,14 +292,14 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Vgs { fn handle_response( &self, - data: &RefundSyncRouterData, + data: &VaultRouterData<ExternalVaultRetrieveFlow>, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { - let response: vgs::RefundResponse = res - .response - .parse_struct("vgs RefundSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + ) -> CustomResult<VaultRouterData<ExternalVaultRetrieveFlow>, errors::ConnectorError> { + let response: vgs::VgsRetrieveResponse = + res.response + .parse_struct("VgsRetrieveResponse") + .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 { diff --git a/crates/hyperswitch_connectors/src/connectors/vgs/transformers.rs b/crates/hyperswitch_connectors/src/connectors/vgs/transformers.rs index f30a455ef4d..4915e2da400 100644 --- a/crates/hyperswitch_connectors/src/connectors/vgs/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/vgs/transformers.rs @@ -1,23 +1,22 @@ -use common_enums::enums; -use common_utils::types::StringMinorUnit; +use common_utils::{ + ext_traits::{Encode, StringExt}, + types::StringMinorUnit, +}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ - payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, - router_flow_types::refunds::{Execute, RSync}, - router_request_types::ResponseId, - router_response_types::{PaymentsResponseData, RefundsResponseData}, - types::{PaymentsAuthorizeRouterData, RefundsRouterData}, + router_flow_types::{ExternalVaultInsertFlow, ExternalVaultRetrieveFlow}, + router_request_types::VaultRequestData, + router_response_types::VaultResponseData, + types::VaultRouterData, + vault::PaymentMethodVaultingData, }; use hyperswitch_interfaces::errors; -use masking::Secret; +use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; -use crate::{ - types::{RefundsResponseRouterData, ResponseRouterData}, - utils::PaymentsAuthorizeRequestData, -}; +use crate::types::ResponseRouterData; -//TODO: Fill the struct with respective fields pub struct VgsRouterData<T> { pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, @@ -25,7 +24,6 @@ pub struct VgsRouterData<T> { impl<T> From<(StringMinorUnit, T)> for VgsRouterData<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, @@ -33,49 +31,48 @@ impl<T> From<(StringMinorUnit, T)> for VgsRouterData<T> { } } -//TODO: Fill the struct with respective fields +const VGS_FORMAT: &str = "UUID"; +const VGS_CLASSIFIER: &str = "data"; + #[derive(Default, Debug, Serialize, PartialEq)] -pub struct VgsPaymentsRequest { - amount: StringMinorUnit, - card: VgsCard, +pub struct VgsTokenRequestItem { + value: Secret<String>, + classifiers: Vec<String>, + format: String, } -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct VgsCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, +#[derive(Default, Debug, Serialize, PartialEq)] +pub struct VgsInsertRequest { + data: Vec<VgsTokenRequestItem>, } -impl TryFrom<&VgsRouterData<&PaymentsAuthorizeRouterData>> for VgsPaymentsRequest { +impl<F> TryFrom<&VaultRouterData<F>> for VgsInsertRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &VgsRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { - match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(req_card) => { - let card = VgsCard { - 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()?, - }; + fn try_from(item: &VaultRouterData<F>) -> Result<Self, Self::Error> { + match item.request.payment_method_vaulting_data.clone() { + Some(PaymentMethodVaultingData::Card(req_card)) => { + let stringified_card = req_card + .encode_to_string_of_json() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Self { - amount: item.amount.clone(), - card, + data: vec![VgsTokenRequestItem { + value: Secret::new(stringified_card), + classifiers: vec![VGS_CLASSIFIER.to_string()], + format: VGS_FORMAT.to_string(), + }], }) } - _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + _ => Err(errors::ConnectorError::NotImplemented( + "Payment method apart from card".to_string(), + ) + .into()), } } } -//TODO: Fill the struct with respective fields -// Auth Struct pub struct VgsAuthType { pub(super) username: Secret<String>, - #[allow(dead_code)] pub(super) password: Secret<String>, } @@ -83,7 +80,7 @@ impl TryFrom<&ConnectorAuthType> for VgsAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - ConnectorAuthType::SignatureKey { api_key, key1, .. } => Ok(Self { + ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { username: api_key.to_owned(), password: key1.to_owned(), }), @@ -91,139 +88,120 @@ impl TryFrom<&ConnectorAuthType> for VgsAuthType { } } } -// PaymentsResponse -//TODO: Append the remaining status flags -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "lowercase")] -pub enum VgsPaymentStatus { - Succeeded, - Failed, - #[default] - Processing, + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct VgsAliasItem { + alias: String, + format: String, } -impl From<VgsPaymentStatus> for common_enums::AttemptStatus { - fn from(item: VgsPaymentStatus) -> Self { - match item { - VgsPaymentStatus::Succeeded => Self::Charged, - VgsPaymentStatus::Failed => Self::Failure, - VgsPaymentStatus::Processing => Self::Authorizing, - } - } +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct VgsTokenResponseItem { + value: Secret<String>, + classifiers: Vec<String>, + aliases: Vec<VgsAliasItem>, + created_at: Option<String>, + storage: String, } -//TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct VgsPaymentsResponse { - status: VgsPaymentStatus, - id: String, +pub struct VgsInsertResponse { + data: Vec<VgsTokenResponseItem>, } -impl<F, T> TryFrom<ResponseRouterData<F, VgsPaymentsResponse, T, PaymentsResponseData>> - for RouterData<F, T, PaymentsResponseData> +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct VgsRetrieveResponse { + data: Vec<VgsTokenResponseItem>, +} + +impl + TryFrom< + ResponseRouterData< + ExternalVaultInsertFlow, + VgsInsertResponse, + VaultRequestData, + VaultResponseData, + >, + > for RouterData<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: ResponseRouterData<F, VgsPaymentsResponse, T, PaymentsResponseData>, + item: ResponseRouterData< + ExternalVaultInsertFlow, + VgsInsertResponse, + VaultRequestData, + VaultResponseData, + >, ) -> Result<Self, Self::Error> { + let vgs_alias = item + .response + .data + .first() + .and_then(|val| val.aliases.first()) + .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; + 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, + status: common_enums::AttemptStatus::Started, + response: Ok(VaultResponseData::ExternalVaultInsertResponse { + connector_vault_id: vgs_alias.alias.clone(), + fingerprint_id: vgs_alias.alias.clone(), }), ..item.data }) } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] -pub struct VgsRefundRequest { - pub amount: StringMinorUnit, -} - -impl<F> TryFrom<&VgsRouterData<&RefundsRouterData<F>>> for VgsRefundRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &VgsRouterData<&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> { +impl + TryFrom< + ResponseRouterData< + ExternalVaultRetrieveFlow, + VgsRetrieveResponse, + VaultRequestData, + VaultResponseData, + >, + > for RouterData<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData> +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: RefundsResponseRouterData<Execute, RefundResponse>, + item: ResponseRouterData< + ExternalVaultRetrieveFlow, + VgsRetrieveResponse, + VaultRequestData, + VaultResponseData, + >, ) -> Result<Self, Self::Error> { + let token_response_item = item + .response + .data + .first() + .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; + + let card_detail: api_models::payment_methods::CardDetail = token_response_item + .value + .clone() + .expose() + .parse_struct("CardDetail") + .change_context(errors::ConnectorError::ParsingFailed)?; + Ok(Self { - response: Ok(RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + status: common_enums::AttemptStatus::Started, + response: Ok(VaultResponseData::ExternalVaultRetrieveResponse { + vault_data: PaymentMethodVaultingData::Card(card_detail), }), ..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 - }) - } +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct VgsErrorItem { + pub status: u16, + pub code: String, + pub detail: Option<String>, } -//TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct VgsErrorResponse { - pub status_code: u16, - pub code: String, - pub message: String, - pub reason: Option<String>, + pub errors: Vec<VgsErrorItem>, + pub trace_id: String, } diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 7d746072f67..963e233c44c 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -6977,7 +6977,6 @@ default_imp_for_external_vault!( connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, - connectors::Vgs, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -7120,7 +7119,6 @@ default_imp_for_external_vault_insert!( connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, - connectors::Vgs, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -7263,7 +7261,6 @@ default_imp_for_external_vault_retrieve!( connectors::Worldpayxml, connectors::Wellsfargo, connectors::Wellsfargopayout, - connectors::Vgs, connectors::Volt, connectors::Xendit, connectors::Zen, diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 1ea747d8101..3a072e12cc7 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -1036,11 +1036,14 @@ pub async fn create_payment_method_card_core( .await; let (response, payment_method) = match vaulting_result { - Ok(pm_types::AddVaultResponse { - vault_id, - fingerprint_id, - .. - }) => { + Ok(( + pm_types::AddVaultResponse { + vault_id, + fingerprint_id, + .. + }, + external_vault_source, + )) => { let pm_update = create_pm_additional_data_update( Some(&payment_method_data), state, @@ -1052,7 +1055,7 @@ pub async fn create_payment_method_card_core( network_tokenization_resp, Some(req.payment_method_type), Some(req.payment_method_subtype), - None, + external_vault_source, ) .await .attach_printable("unable to create payment method data")?; @@ -2395,7 +2398,10 @@ pub async fn vault_payment_method( profile: &domain::Profile, existing_vault_id: Option<domain::VaultId>, customer_id: &id_type::GlobalCustomerId, -) -> RouterResult<pm_types::AddVaultResponse> { +) -> RouterResult<( + pm_types::AddVaultResponse, + Option<id_type::MerchantConnectorAccountId>, +)> { let is_external_vault_enabled = profile.is_external_vault_enabled(); match is_external_vault_enabled { @@ -2427,17 +2433,17 @@ pub async fn vault_payment_method( merchant_connector_account, ) .await + .map(|value| (value, Some(external_vault_source))) } - false => { - vault_payment_method_internal( - state, - pmd, - merchant_context, - existing_vault_id, - customer_id, - ) - .await - } + false => vault_payment_method_internal( + state, + pmd, + merchant_context, + existing_vault_id, + customer_id, + ) + .await + .map(|value| (value, None)), } } @@ -2812,20 +2818,20 @@ pub async fn update_payment_method_core( // cannot use async map because of problems related to lifetimes // to overcome this, we will have to use a move closure and add some clones Some(ref vault_request_data) => { - Some( - vault_payment_method( - state, - vault_request_data, - merchant_context, - profile, - // using current vault_id for now, - // will have to refactor this to generate new one on each vaulting later on - current_vault_id, - &payment_method.customer_id, - ) - .await - .attach_printable("Failed to add payment method in vault")?, + let (vault_response, _) = vault_payment_method( + state, + vault_request_data, + merchant_context, + profile, + // using current vault_id for now, + // will have to refactor this to generate new one on each vaulting later on + current_vault_id, + &payment_method.customer_id, ) + .await + .attach_printable("Failed to add payment method in vault")?; + + Some(vault_response) } None => None, }; diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs index c184c9db8dd..bd9a1fedeec 100644 --- a/crates/router/src/types/api/connector_mapping.rs +++ b/crates/router/src/types/api/connector_mapping.rs @@ -429,7 +429,7 @@ impl ConnectorData { // enums::Connector::UnifiedAuthenticationService => Ok(ConnectorEnum::Old(Box::new( // connector::UnifiedAuthenticationService, // ))), - enums::Connector::Vgs => Ok(ConnectorEnum::Old(Box::new(connector::Vgs::new()))), + enums::Connector::Vgs => Ok(ConnectorEnum::Old(Box::new(&connector::Vgs))), enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(connector::Volt::new()))), enums::Connector::Wellsfargo => { Ok(ConnectorEnum::Old(Box::new(connector::Wellsfargo::new()))) diff --git a/crates/router/src/types/api/feature_matrix.rs b/crates/router/src/types/api/feature_matrix.rs index ac7754faa30..c771255dd71 100644 --- a/crates/router/src/types/api/feature_matrix.rs +++ b/crates/router/src/types/api/feature_matrix.rs @@ -349,7 +349,7 @@ impl FeatureMatrixConnectorData { // enums::Connector::UnifiedAuthenticationService => Ok(ConnectorEnum::Old(Box::new( // connector::UnifiedAuthenticationService, // ))), - enums::Connector::Vgs => Ok(ConnectorEnum::Old(Box::new(connector::Vgs::new()))), + enums::Connector::Vgs => Ok(ConnectorEnum::Old(Box::new(&connector::Vgs))), enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(connector::Volt::new()))), enums::Connector::Wellsfargo => { Ok(ConnectorEnum::Old(Box::new(connector::Wellsfargo::new()))) diff --git a/crates/router/tests/connectors/vgs.rs b/crates/router/tests/connectors/vgs.rs index fb9b6bb30be..70ce1045962 100644 --- a/crates/router/tests/connectors/vgs.rs +++ b/crates/router/tests/connectors/vgs.rs @@ -11,7 +11,7 @@ impl utils::Connector for VgsTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Vgs; utils::construct_connector_data_old( - Box::new(Vgs::new()), + Box::new(&Vgs), types::Connector::Vgs, types::api::GetToken::Connector, None, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 9b81a63e182..50a992515a7 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -202,7 +202,7 @@ trustpayments.base_url = "https://webservices.securetrading.net/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://stagegw.transnox.com/" unified_authentication_service.base_url = "http://localhost:8000" -vgs.base_url = "https://sandbox.vault-api.verygoodvault.com" +vgs.base_url = "https://api.sandbox.verygoodvault.com/" volt.base_url = "https://api.sandbox.volt.io/" wellsfargo.base_url = "https://apitest.cybersource.com/" wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/"
2025-04-30T09:54: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 --> - Added Connector changes for VGS - Implemented `ExternalVaultInsertFlow` and `ExternalVaultRetrieveFlow` for VGS - This allows Payment methods to be vaulted in VGS when `is_external_vault_enabled` is set to true in profile - Updated VGS URL in TOML files ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #9023 ## 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)? --> Confirm Request: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0198d09ccd8a77729274a5c3858e13f3/confirm-intent' \ --header 'x-profile-id: pro_TVu6gSPZXAVEa2h0JCRe' \ --header 'x-client-secret: cs_0198d09cce0774338628683873a2db9d' \ --header 'Authorization: publishable-key=pk_dev_17e15cb3538d4bd99af971ee2d4d081f,client-secret=cs_0198d09cce0774338628683873a2db9d' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_17e15cb3538d4bd99af971ee2d4d081f' \ --data '{ "payment_method_data": { "card": { "card_cvc": "123", "card_exp_month": "10", "card_exp_year": "25", "card_number": "4242424242424242", "card_holder_name": "joseph Doe" } }, "payment_method_type": "card", "payment_method_subtype": "card", "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "accept_header": "text\\/html,application\\/xhtml+xml,application\\/xml;q=0.9,image\\/webp,image\\/apng,*\\/*;q=0.8", "language": "en-GB", "color_depth": 24, "screen_height": 1440, "screen_width": 2560, "time_zone": -330, "java_enabled": true, "java_script_enabled": true, "ip_address": "0.0.0.0" }, "customer_acceptance": { "acceptance_type": "online", "accepted_at": "2022-09-10T10:11:12Z", "online": { "ip_address": "123.32.25.123", "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" } } }' ``` Insert Request: <img width="1598" height="26" alt="image" src="https://github.com/user-attachments/assets/2e2e81e1-360a-481f-a018-91d7da156d54" /> Insert Response: <img width="2364" height="38" alt="image" src="https://github.com/user-attachments/assets/aad8f89e-144c-4a0e-a6e5-9ec2c6aa957a" /> Confirm Request: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0198d09ccd8a77729274a5c3858e13f3/confirm-intent' \ --header 'x-profile-id: pro_TVu6gSPZXAVEa2h0JCRe' \ --header 'x-client-secret: cs_0198d09cce0774338628683873a2db9d' \ --header 'Authorization: publishable-key=pk_dev_17e15cb3538d4bd99af971ee2d4d081f,client-secret=cs_0198d09cce0774338628683873a2db9d' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_17e15cb3538d4bd99af971ee2d4d081f' \ --data '{ "payment_method_data": { "card_token": { "card_cvc": "123" } }, "payment_method_type": "card", "payment_method_subtype": "card", "payment_token": "token_UBCgOA3daIE4CP4pugXW" }' ``` Retrieve Request: <img width="2364" height="38" alt="image" src="https://github.com/user-attachments/assets/0eaa5d7f-19e1-4cfb-95a4-b6376f8e3c74" /> Retrieve Response: <img width="2373" height="51" alt="image" src="https://github.com/user-attachments/assets/9b81e22d-931f-4132-a8e4-2a7bd6341c02" /> ## 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.116.0
c90625a4ea163e03895276a04ec3a23d4117413d
c90625a4ea163e03895276a04ec3a23d4117413d
juspay/hyperswitch
juspay__hyperswitch-9015
Bug: [REFACTOR] propagate merchant_reference_id for PaymentsAuthorizeData propagate merchant_reference_id for PaymentsAuthorizeData in v2
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 348a364c569..cf91b2bcc36 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -406,7 +406,10 @@ pub async fn construct_payment_router_data_for_authorize<'a>( authentication_data: None, customer_acceptance: None, split_payments: None, - merchant_order_reference_id: None, + merchant_order_reference_id: payment_data + .payment_intent + .merchant_reference_id + .map(|reference_id| reference_id.get_string_repr().to_owned()), integrity_object: None, shipping_cost: payment_data.payment_intent.amount_details.shipping_cost, additional_payment_method_data: None,
2025-08-21T13:04:33Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds support for propagating merchant_reference_id for PaymentsAuthorizeData v2. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> enable UCS ``` curl --location 'http://localhost:8080/v2/configs/' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'Content-Type: application/json' \ --data '{ "key": "ucs_rollout_config_cloth_seller1756197165_9PGBS852vwot2udmMevW_razorpay_upi_Authorize", "value": "1.0" }' ``` payment create ``` curl --location 'http://localhost:8080/v2/payments' \ --header 'x-profile-id: pro_jbuydwkItzTQj5EOqLaA' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_W97mjtX47mRRBIJWGgGMLZ8vEqUGQuymwlmsD32QpNhJM6318Vs25V21U6Kr665R' \ --data-raw '{ "amount_details": { "currency": "INR", "order_amount": 100 }, "return_raw_connector_response" : true, "payment_method_data": { "upi": { "upi_collect": { "vpa_id": "success@razorpay" } }, "billing": { "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" } }, "payment_method_subtype": "upi_collect", "payment_method_type": "upi", "metadata" : { "__notes_91_txn_uuid_93_" : "frefer", "__notes_91_transaction_id_93_" : "sdfccewf" }, "browser_info": { "user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "ip_address": "128.0.0.1" }, "merchant_reference_id": "1756197223" }' ``` Response ``` { "id": "12345_pay_0198e582efb27dd19d65039d63fdee24", "status": "requires_customer_action", "amount": { "order_amount": 100, "currency": "INR", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "customer_id": null, "connector": "razorpay", "created": "2025-08-26T08:33:40.275Z", "payment_method_data": { "billing": { "address": null, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" } }, "payment_method_type": "upi", "payment_method_subtype": "upi_collect", "connector_transaction_id": "pay_R9tm9SQPe1lw99", "connector_reference_id": "order_R9tm8rO2C9Po6a", "merchant_connector_id": "mca_bYbJJ3mQjcf6SDC8cULu", "browser_info": null, "error": null, "shipping": null, "billing": null, "attempts": null, "connector_token_details": null, "payment_method_id": null, "next_action": { "type": "wait_screen_information", "display_from_timestamp": 1756197222581835000, "display_to_timestamp": 1756197522581835000, "poll_config": { "delay_in_secs": 5, "frequency": 5 } }, "return_url": "https://google.com/success", "authentication_type": null, "authentication_type_applied": "no_three_ds", "is_iframe_redirection_enabled": null, "merchant_reference_id": "1756197220", "raw_connector_response": "{\"razorpay_payment_id\":\"pay_R9tm9SQPe1lw99\"}", "feature_metadata": null } ``` check merchant_order_reference_id in UCS logs <img width="1374" height="248" alt="image" src="https://github.com/user-attachments/assets/fbc60337-6809-4727-9da7-26e0a6c83ad6" /> ## 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.116.0
a819b4639b1e4279b117f4693cb0716b08e5e2e9
a819b4639b1e4279b117f4693cb0716b08e5e2e9
juspay/hyperswitch
juspay__hyperswitch-9022
Bug: [FEATURE]: [Paysafe] add connector template code - add connector template code for Paysafe
diff --git a/config/config.example.toml b/config/config.example.toml index 0467346ec72..5fe3dbd05fa 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -276,6 +276,7 @@ payload.base_url = "https://api.payload.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/" +paysafe.base_url = "https://api.test.paysafe.com/paymenthub/" paystack.base_url = "https://api.paystack.co" paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index a7dc0f04156..21ac732394f 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -113,6 +113,7 @@ payload.base_url = "https://api.payload.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/" +paysafe.base_url = "https://api.test.paysafe.com/paymenthub/" paystack.base_url = "https://api.paystack.co" paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 07fc2b06cee..853ec279f66 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -117,6 +117,7 @@ payload.base_url = "https://api.payload.com" payme.base_url = "https://live.payme.io/" payone.base_url = "https://payment.payone.com/" paypal.base_url = "https://api-m.paypal.com/" +paysafe.base_url = "https://api.test.paysafe.com/paymenthub/" paystack.base_url = "https://api.paystack.co" paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.payu.com/api/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index dbbe67f07ff..dbd5e87e520 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -117,6 +117,7 @@ payload.base_url = "https://api.payload.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/" +paysafe.base_url = "https://api.test.paysafe.com/paymenthub/" paystack.base_url = "https://api.paystack.co" paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" diff --git a/config/development.toml b/config/development.toml index 0a2caf35505..1215c323628 100644 --- a/config/development.toml +++ b/config/development.toml @@ -315,6 +315,7 @@ payload.base_url = "https://api.payload.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/" +paysafe.base_url = "https://api.test.paysafe.com/paymenthub/" paystack.base_url = "https://api.paystack.co" paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 5c753b91568..75305234278 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -202,6 +202,7 @@ payload.base_url = "https://api.payload.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/" +paysafe.base_url = "https://api.test.paysafe.com/paymenthub/" paystack.base_url = "https://api.paystack.co" paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index c1cae71ffe1..fbdb974574a 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -270,6 +270,7 @@ pub struct ConnectorConfig { #[cfg(feature = "payouts")] pub payone_payout: Option<ConnectorTomlConfig>, pub paypal: Option<ConnectorTomlConfig>, + pub paysafe: Option<ConnectorTomlConfig>, #[cfg(feature = "payouts")] pub paypal_payout: Option<ConnectorTomlConfig>, pub paystack: Option<ConnectorTomlConfig>, diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index bdedcf9d1f7..ac14c55982f 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -6696,3 +6696,7 @@ payment_experience = "redirect_to_url" [hyperwallet.connector_auth.BodyKey] api_key = "Password" key1 = "Username" + +[paysafe] +[paysafe.connector_auth.HeaderKey] +api_key = "API Key" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 21c9f20fedc..5b14d328a68 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5366,3 +5366,7 @@ type = "Text" [hyperwallet.connector_auth.BodyKey] api_key = "Password" key1 = "Username" + +[paysafe] +[paysafe.connector_auth.HeaderKey] +api_key = "API Key" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 597c3fb7276..486af69301f 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -6679,4 +6679,8 @@ payment_experience = "redirect_to_url" [hyperwallet] [hyperwallet.connector_auth.BodyKey] api_key = "Password" -key1 = "Username" \ No newline at end of file +key1 = "Username" + +[paysafe] +[paysafe.connector_auth.HeaderKey] +api_key = "API Key" diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index e6494a5971a..60d6866beea 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -83,6 +83,7 @@ pub mod payload; pub mod payme; pub mod payone; pub mod paypal; +pub mod paysafe; pub mod paystack; pub mod paytm; pub mod payu; @@ -148,13 +149,13 @@ pub use self::{ netcetera::Netcetera, nexinets::Nexinets, nexixpay::Nexixpay, nmi::Nmi, nomupay::Nomupay, noon::Noon, nordea::Nordea, novalnet::Novalnet, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payload::Payload, payme::Payme, payone::Payone, - paypal::Paypal, paystack::Paystack, paytm::Paytm, payu::Payu, phonepe::Phonepe, - placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz, prophetpay::Prophetpay, - rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, riskified::Riskified, - santander::Santander, shift4::Shift4, sift::Sift, signifyd::Signifyd, silverflow::Silverflow, - square::Square, stax::Stax, stripe::Stripe, stripebilling::Stripebilling, taxjar::Taxjar, - threedsecureio::Threedsecureio, thunes::Thunes, tokenio::Tokenio, trustpay::Trustpay, - trustpayments::Trustpayments, tsys::Tsys, + paypal::Paypal, paysafe::Paysafe, paystack::Paystack, paytm::Paytm, payu::Payu, + phonepe::Phonepe, placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz, + prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, + riskified::Riskified, santander::Santander, shift4::Shift4, sift::Sift, signifyd::Signifyd, + silverflow::Silverflow, square::Square, stax::Stax, stripe::Stripe, + stripebilling::Stripebilling, taxjar::Taxjar, threedsecureio::Threedsecureio, thunes::Thunes, + tokenio::Tokenio, trustpay::Trustpay, trustpayments::Trustpayments, tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, vgs::Vgs, volt::Volt, wellsfargo::Wellsfargo, wellsfargopayout::Wellsfargopayout, wise::Wise, worldline::Worldline, worldpay::Worldpay, worldpayvantiv::Worldpayvantiv, worldpayxml::Worldpayxml, xendit::Xendit, diff --git a/crates/hyperswitch_connectors/src/connectors/paysafe.rs b/crates/hyperswitch_connectors/src/connectors/paysafe.rs new file mode 100644 index 00000000000..fc76cece514 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/paysafe.rs @@ -0,0 +1,621 @@ +pub mod transformers; + +use std::sync::LazyLock; + +use common_enums::enums; +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::{ + payment_method_data::PaymentMethodData, + 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::{ + ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, + }, + 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 paysafe; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Paysafe { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Paysafe { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Paysafe {} +impl api::PaymentSession for Paysafe {} +impl api::ConnectorAccessToken for Paysafe {} +impl api::MandateSetup for Paysafe {} +impl api::PaymentAuthorize for Paysafe {} +impl api::PaymentSync for Paysafe {} +impl api::PaymentCapture for Paysafe {} +impl api::PaymentVoid for Paysafe {} +impl api::Refund for Paysafe {} +impl api::RefundExecute for Paysafe {} +impl api::RefundSync for Paysafe {} +impl api::PaymentToken for Paysafe {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Paysafe +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paysafe +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 Paysafe { + fn id(&self) -> &'static str { + "paysafe" + } + + 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.paysafe.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = paysafe::PaysafeAuthType::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: paysafe::PaysafeErrorResponse = res + .response + .parse_struct("PaysafeErrorResponse") + .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, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + connector_metadata: None, + }) + } +} + +impl ConnectorValidation for Paysafe { + fn validate_mandate_payment( + &self, + _pm_type: Option<enums::PaymentMethodType>, + pm_data: PaymentMethodData, + ) -> CustomResult<(), errors::ConnectorError> { + match pm_data { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "validate_mandate_payment does not support cards".to_string(), + ) + .into()), + _ => Ok(()), + } + } + + fn validate_psync_reference_id( + &self, + _data: &PaymentsSyncData, + _is_three_ds: bool, + _status: enums::AttemptStatus, + _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, + ) -> CustomResult<(), errors::ConnectorError> { + Ok(()) + } +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Paysafe { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Paysafe {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Paysafe {} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paysafe { + 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 = paysafe::PaysafeRouterData::from((amount, req)); + let connector_req = paysafe::PaysafePaymentsRequest::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: paysafe::PaysafePaymentsResponse = res + .response + .parse_struct("Paysafe 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 Paysafe { + 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: paysafe::PaysafePaymentsResponse = res + .response + .parse_struct("paysafe 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 Paysafe { + 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: paysafe::PaysafePaymentsResponse = res + .response + .parse_struct("Paysafe 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 Paysafe {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paysafe { + 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 = paysafe::PaysafeRouterData::from((refund_amount, req)); + let connector_req = paysafe::PaysafeRefundRequest::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: paysafe::RefundResponse = res + .response + .parse_struct("paysafe 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 Paysafe { + 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: paysafe::RefundResponse = res + .response + .parse_struct("paysafe 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 Paysafe { + 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)) + } +} + +static PAYSAFE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(SupportedPaymentMethods::new); + +static PAYSAFE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Paysafe", + description: "Paysafe connector", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Sandbox, +}; + +static PAYSAFE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Paysafe { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&PAYSAFE_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*PAYSAFE_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&PAYSAFE_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs new file mode 100644 index 00000000000..f1a7dbdc237 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs @@ -0,0 +1,219 @@ +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}; + +//TODO: Fill the struct with respective fields +pub struct PaysafeRouterData<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 PaysafeRouterData<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 PaysafePaymentsRequest { + amount: StringMinorUnit, + card: PaysafeCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct PaysafeCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&PaysafeRouterData<&PaymentsAuthorizeRouterData>> for PaysafePaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &PaysafeRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "Card payment method not implemented".to_string(), + ) + .into()), + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct PaysafeAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for PaysafeAuthType { + 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, Copy, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum PaysafePaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<PaysafePaymentStatus> for common_enums::AttemptStatus { + fn from(item: PaysafePaymentStatus) -> Self { + match item { + PaysafePaymentStatus::Succeeded => Self::Charged, + PaysafePaymentStatus::Failed => Self::Failure, + PaysafePaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PaysafePaymentsResponse { + status: PaysafePaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, PaysafePaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, PaysafePaymentsResponse, 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 PaysafeRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&PaysafeRouterData<&RefundsRouterData<F>>> for PaysafeRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &PaysafeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Copy, 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 PaysafeErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, + pub network_advice_code: Option<String>, + pub network_decline_code: Option<String>, + pub network_error_message: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index f18b659184e..8b87e0c098a 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -228,6 +228,7 @@ default_imp_for_authorize_session_token!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -374,6 +375,7 @@ default_imp_for_calculate_tax!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -432,6 +434,7 @@ macro_rules! default_imp_for_session_update { } default_imp_for_session_update!( + connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyen, @@ -573,6 +576,7 @@ macro_rules! default_imp_for_post_session_tokens { } default_imp_for_post_session_tokens!( + connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyen, @@ -802,6 +806,7 @@ default_imp_for_create_order!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -908,6 +913,7 @@ default_imp_for_update_metadata!( connectors::Katapult, connectors::Klarna, connectors::Paypal, + connectors::Paysafe, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, @@ -1049,6 +1055,7 @@ default_imp_for_cancel_post_capture!( connectors::Katapult, connectors::Klarna, connectors::Paypal, + connectors::Paysafe, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, @@ -1138,6 +1145,7 @@ macro_rules! default_imp_for_complete_authorize { } default_imp_for_complete_authorize!( + connectors::Paysafe, connectors::Silverflow, connectors::Vgs, connectors::Aci, @@ -1257,6 +1265,7 @@ macro_rules! default_imp_for_incremental_authorization { } default_imp_for_incremental_authorization!( + connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyen, @@ -1473,6 +1482,7 @@ default_imp_for_create_customer!( connectors::Payload, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -1533,6 +1543,7 @@ macro_rules! default_imp_for_connector_redirect_response { } default_imp_for_connector_redirect_response!( + connectors::Paysafe, connectors::Trustpayments, connectors::Vgs, connectors::Aci, @@ -1653,6 +1664,7 @@ macro_rules! default_imp_for_pre_processing_steps{ } default_imp_for_pre_processing_steps!( + connectors::Paysafe, connectors::Trustpayments, connectors::Silverflow, connectors::Vgs, @@ -1858,6 +1870,7 @@ default_imp_for_post_processing_steps!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -1999,6 +2012,7 @@ default_imp_for_approve!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payone, @@ -2143,6 +2157,7 @@ default_imp_for_reject!( connectors::Payone, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -2208,6 +2223,7 @@ macro_rules! default_imp_for_webhook_source_verification { } default_imp_for_webhook_source_verification!( + connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyen, @@ -2427,6 +2443,7 @@ default_imp_for_accept_dispute!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -2566,6 +2583,7 @@ default_imp_for_submit_evidence!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Payone, connectors::Paystack, connectors::Paytm, @@ -2706,6 +2724,7 @@ default_imp_for_defend_dispute!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -2849,6 +2868,7 @@ default_imp_for_fetch_disputes!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Payu, connectors::Paytm, @@ -2991,6 +3011,7 @@ default_imp_for_dispute_sync!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Payu, connectors::Paytm, @@ -3140,6 +3161,7 @@ default_imp_for_file_upload!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -3196,6 +3218,7 @@ macro_rules! default_imp_for_payouts { } default_imp_for_payouts!( + connectors::Paysafe, connectors::Affirm, connectors::Vgs, connectors::Aci, @@ -3331,6 +3354,7 @@ macro_rules! default_imp_for_payouts_create { #[cfg(feature = "payouts")] default_imp_for_payouts_create!( + connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyenplatform, @@ -3470,6 +3494,7 @@ macro_rules! default_imp_for_payouts_retrieve { #[cfg(feature = "payouts")] default_imp_for_payouts_retrieve!( + connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyen, @@ -3686,6 +3711,7 @@ default_imp_for_payouts_eligibility!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payone, @@ -3753,6 +3779,7 @@ macro_rules! default_imp_for_payouts_fulfill { #[cfg(feature = "payouts")] default_imp_for_payouts_fulfill!( + connectors::Paysafe, connectors::Affirm, connectors::Vgs, connectors::Aci, @@ -3963,6 +3990,7 @@ default_imp_for_payouts_cancel!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payone, @@ -4105,6 +4133,7 @@ default_imp_for_payouts_quote!( connectors::Payone, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -4247,6 +4276,7 @@ default_imp_for_payouts_recipient!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -4389,6 +4419,7 @@ default_imp_for_payouts_recipient_account!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -4533,6 +4564,7 @@ default_imp_for_frm_sale!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -4676,6 +4708,7 @@ default_imp_for_frm_checkout!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -4819,6 +4852,7 @@ default_imp_for_frm_transaction!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -4962,6 +4996,7 @@ default_imp_for_frm_fulfillment!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -5105,6 +5140,7 @@ default_imp_for_frm_record_return!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -5242,6 +5278,7 @@ default_imp_for_revoking_mandates!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -5382,6 +5419,7 @@ default_imp_for_uas_pre_authentication!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -5522,6 +5560,7 @@ default_imp_for_uas_post_authentication!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -5675,6 +5714,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Multisafepay, connectors::Paybox, connectors::Paypal, + connectors::Paysafe, connectors::Placetopay, connectors::Plaid, connectors::Rapyd, @@ -5799,6 +5839,7 @@ default_imp_for_connector_request_id!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -5931,6 +5972,7 @@ default_imp_for_fraud_check!( connectors::Paystack, connectors::Paytm, connectors::Paypal, + connectors::Paysafe, connectors::Payu, connectors::Phonepe, connectors::Powertranz, @@ -6107,6 +6149,7 @@ default_imp_for_connector_authentication!( connectors::Paybox, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Placetopay, connectors::Plaid, connectors::Rapyd, @@ -6229,6 +6272,7 @@ default_imp_for_uas_authentication!( connectors::Payeezy, connectors::Payload, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -6370,6 +6414,7 @@ default_imp_for_revenue_recovery!( connectors::Payu, connectors::Phonepe, connectors::Paypal, + connectors::Paysafe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -6514,6 +6559,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Payu, connectors::Phonepe, connectors::Paypal, + connectors::Paysafe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -6656,6 +6702,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Payu, connectors::Phonepe, connectors::Paypal, + connectors::Paysafe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -6798,6 +6845,7 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Payu, connectors::Phonepe, connectors::Paypal, + connectors::Paysafe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -6934,6 +6982,7 @@ default_imp_for_external_vault!( connectors::Payu, connectors::Phonepe, connectors::Paypal, + connectors::Paysafe, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, @@ -7076,6 +7125,7 @@ default_imp_for_external_vault_insert!( connectors::Payu, connectors::Phonepe, connectors::Paypal, + connectors::Paysafe, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, @@ -7218,6 +7268,7 @@ default_imp_for_external_vault_retrieve!( connectors::Payu, connectors::Phonepe, connectors::Paypal, + connectors::Paysafe, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, @@ -7360,6 +7411,7 @@ default_imp_for_external_vault_delete!( connectors::Payu, connectors::Phonepe, connectors::Paypal, + connectors::Paysafe, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, @@ -7502,6 +7554,7 @@ default_imp_for_external_vault_create!( connectors::Payu, connectors::Phonepe, connectors::Paypal, + connectors::Paysafe, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, @@ -7645,6 +7698,7 @@ default_imp_for_connector_authentication_token!( connectors::Payu, connectors::Phonepe, connectors::Paypal, + connectors::Paysafe, connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, @@ -7789,6 +7843,7 @@ default_imp_for_external_vault_proxy_payments_create!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 2d346a0e7c2..5dc07ab43d4 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -338,6 +338,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -481,6 +482,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -616,6 +618,7 @@ default_imp_for_new_connector_integration_connector_authentication_token!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Payu, connectors::Placetopay, @@ -750,6 +753,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -893,6 +897,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -1041,6 +1046,7 @@ default_imp_for_new_connector_integration_fetch_disputes!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -1185,6 +1191,7 @@ default_imp_for_new_connector_integration_dispute_sync!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -1324,6 +1331,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -1466,6 +1474,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Payu, connectors::Paytm, @@ -1619,6 +1628,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -1764,6 +1774,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -1909,6 +1920,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -2054,6 +2066,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -2199,6 +2212,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -2344,6 +2358,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -2489,6 +2504,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -2634,6 +2650,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -2779,6 +2796,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -2922,6 +2940,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -3067,6 +3086,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -3212,6 +3232,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -3357,6 +3378,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -3502,6 +3524,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -3647,6 +3670,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -3711,6 +3735,7 @@ macro_rules! default_imp_for_new_connector_integration_revoking_mandates { } default_imp_for_new_connector_integration_revoking_mandates!( + connectors::Paysafe, connectors::Vgs, connectors::Aci, connectors::Adyen, @@ -3847,6 +3872,7 @@ macro_rules! default_imp_for_new_connector_integration_frm { #[cfg(feature = "frm")] default_imp_for_new_connector_integration_frm!( + connectors::Paysafe, connectors::Trustpayments, connectors::Affirm, connectors::Paytm, @@ -3989,6 +4015,7 @@ macro_rules! default_imp_for_new_connector_integration_connector_authentication } default_imp_for_new_connector_integration_connector_authentication!( + connectors::Paysafe, connectors::Trustpayments, connectors::Affirm, connectors::Paytm, @@ -4120,6 +4147,7 @@ macro_rules! default_imp_for_new_connector_integration_revenue_recovery { } default_imp_for_new_connector_integration_revenue_recovery!( + connectors::Paysafe, connectors::Trustpayments, connectors::Affirm, connectors::Paytm, @@ -4339,6 +4367,7 @@ default_imp_for_new_connector_integration_external_vault!( connectors::Payload, connectors::Payme, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, @@ -4486,6 +4515,7 @@ default_imp_for_new_connector_integration_external_vault_proxy!( connectors::Payme, connectors::Payone, connectors::Paypal, + connectors::Paysafe, connectors::Paystack, connectors::Paytm, connectors::Payu, diff --git a/crates/hyperswitch_domain_models/src/connector_endpoints.rs b/crates/hyperswitch_domain_models/src/connector_endpoints.rs index 53b17691fea..d6b62a5eb45 100644 --- a/crates/hyperswitch_domain_models/src/connector_endpoints.rs +++ b/crates/hyperswitch_domain_models/src/connector_endpoints.rs @@ -98,6 +98,7 @@ pub struct Connectors { pub payme: ConnectorParams, pub payone: ConnectorParams, pub paypal: ConnectorParams, + pub paysafe: ConnectorParams, pub paystack: ConnectorParams, pub paytm: ConnectorParams, pub payu: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 5e375593ea3..a8e859cc5b3 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -31,20 +31,20 @@ pub use hyperswitch_connectors::connectors::{ nexixpay, nexixpay::Nexixpay, nmi, nmi::Nmi, nomupay, nomupay::Nomupay, noon, noon::Noon, nordea, nordea::Nordea, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payload, - payload::Payload, payme, payme::Payme, payone, payone::Payone, paypal, paypal::Paypal, - paystack, paystack::Paystack, paytm, paytm::Paytm, payu, payu::Payu, phonepe, phonepe::Phonepe, - placetopay, placetopay::Placetopay, plaid, plaid::Plaid, powertranz, powertranz::Powertranz, - prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, - recurly::Recurly, redsys, redsys::Redsys, riskified, riskified::Riskified, santander, - santander::Santander, shift4, shift4::Shift4, sift, sift::Sift, signifyd, signifyd::Signifyd, - silverflow, silverflow::Silverflow, square, square::Square, stax, stax::Stax, stripe, - stripe::Stripe, stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, - threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, tokenio, - tokenio::Tokenio, trustpay, trustpay::Trustpay, trustpayments, trustpayments::Trustpayments, - tsys, tsys::Tsys, unified_authentication_service, - unified_authentication_service::UnifiedAuthenticationService, vgs, vgs::Vgs, volt, volt::Volt, - wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, wellsfargopayout::Wellsfargopayout, wise, - wise::Wise, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, worldpayvantiv, - worldpayvantiv::Worldpayvantiv, worldpayxml, worldpayxml::Worldpayxml, xendit, xendit::Xendit, - zen, zen::Zen, zsl, zsl::Zsl, + payload::Payload, payme, payme::Payme, payone, payone::Payone, paypal, paypal::Paypal, paysafe, + paysafe::Paysafe, paystack, paystack::Paystack, paytm, paytm::Paytm, payu, payu::Payu, phonepe, + phonepe::Phonepe, placetopay, placetopay::Placetopay, plaid, plaid::Plaid, powertranz, + powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, + razorpay::Razorpay, recurly, recurly::Recurly, redsys, redsys::Redsys, riskified, + riskified::Riskified, santander, santander::Santander, shift4, shift4::Shift4, sift, + sift::Sift, signifyd, signifyd::Signifyd, silverflow, silverflow::Silverflow, square, + square::Square, stax, stax::Stax, stripe, stripe::Stripe, stripebilling, + stripebilling::Stripebilling, taxjar, taxjar::Taxjar, threedsecureio, + threedsecureio::Threedsecureio, thunes, thunes::Thunes, tokenio, tokenio::Tokenio, trustpay, + trustpay::Trustpay, trustpayments, trustpayments::Trustpayments, tsys, tsys::Tsys, + unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, + vgs, vgs::Vgs, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, + wellsfargopayout::Wellsfargopayout, wise, wise::Wise, worldline, worldline::Worldline, + worldpay, worldpay::Worldpay, worldpayvantiv, worldpayvantiv::Worldpayvantiv, worldpayxml, + worldpayxml::Worldpayxml, xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, }; diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index ca96206e0af..87434a0e6dd 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -87,6 +87,7 @@ mod payload; mod payme; mod payone; mod paypal; +mod paysafe; mod paystack; mod paytm; mod payu; diff --git a/crates/router/tests/connectors/paysafe.rs b/crates/router/tests/connectors/paysafe.rs new file mode 100644 index 00000000000..36afbb0368c --- /dev/null +++ b/crates/router/tests/connectors/paysafe.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 PaysafeTest; +impl ConnectorActions for PaysafeTest {} +impl utils::Connector for PaysafeTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Paysafe; + utils::construct_connector_data_old( + Box::new(Paysafe::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .paysafe + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "paysafe".to_string() + } +} + +static CONNECTOR: PaysafeTest = PaysafeTest {}; + +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/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 49cb0717c76..720bdb32a61 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -94,6 +94,7 @@ pub struct ConnectorAuthentication { pub payme: Option<BodyKey>, pub payone: Option<HeaderKey>, pub paypal: Option<BodyKey>, + pub paysafe: Option<HeaderKey>, pub paystack: Option<HeaderKey>, pub paytm: Option<HeaderKey>, pub payu: Option<BodyKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 9c0a2efd561..374119bebbc 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -169,6 +169,7 @@ payload.base_url = "https://api.payload.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/" +paysafe.base_url = "https://api.test.paysafe.com/paymenthub/" paystack.base_url = "https://api.paystack.co" paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index b826b23850c..6f041b8fa01 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 affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay fiserv fiservemea fiuu flexiti forte getnet globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault hyperwallet hyperwallet iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paystack paytm payu phonepe placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 sift silverflow square stax stripe stripebilling taxjar threedsecureio thunes tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") + connectors=(aci adyen adyenplatform affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay fiserv fiservemea fiuu flexiti forte getnet globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault hyperwallet hyperwallet iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paysafe paystack paytm payu phonepe placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 sift silverflow square stax stripe stripebilling taxjar threedsecureio thunes tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
2025-08-21T12:05:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add connector template code for Paysafe ### 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? No test required as it is template PR ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.116.0
d18a94188ea93d07c4581888880088a9e676b1fd
d18a94188ea93d07c4581888880088a9e676b1fd
juspay/hyperswitch
juspay__hyperswitch-9028
Bug: [FEATURE] CELERO CIT_MIT (ALPHACONNECTOR) ### Feature Description IMPLEMENT CIT & MIT for celero ### Possible Implementation - DOCS : https://sandbox.gotnpgateway.com/docs/api/transactions#cit-mit ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/hyperswitch_connectors/src/connectors/celero/transformers.rs b/crates/hyperswitch_connectors/src/connectors/celero/transformers.rs index 2003ba59ae0..4e4c3f113cf 100644 --- a/crates/hyperswitch_connectors/src/connectors/celero/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/celero/transformers.rs @@ -1,5 +1,5 @@ use common_enums::{enums, Currency}; -use common_utils::{pii::Email, types::MinorUnit}; +use common_utils::{id_type::CustomerId, pii::Email, types::MinorUnit}; use hyperswitch_domain_models::{ address::Address as DomainAddress, payment_method_data::PaymentMethodData, @@ -12,20 +12,24 @@ use hyperswitch_domain_models::{ refunds::{Execute, RSync}, }, router_request_types::{PaymentsCaptureData, ResponseId}, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; -use hyperswitch_interfaces::{consts, errors}; +use hyperswitch_interfaces::{ + consts, + errors::{self}, +}; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ - AddressDetailsData, PaymentsAuthorizeRequestData, RefundsRequestData, RouterData as _, + get_unimplemented_payment_method_error_message, AddressDetailsData, + PaymentsAuthorizeRequestData, RefundsRequestData, RouterData as _, }, }; @@ -87,6 +91,17 @@ pub struct CeleroPaymentsRequest { shipping_address: Option<CeleroAddress>, #[serde(skip_serializing_if = "Option::is_none")] create_vault_record: Option<bool>, + // CIT/MIT fields + #[serde(skip_serializing_if = "Option::is_none")] + card_on_file_indicator: Option<CardOnFileIndicator>, + #[serde(skip_serializing_if = "Option::is_none")] + initiated_by: Option<InitiatedBy>, + #[serde(skip_serializing_if = "Option::is_none")] + initial_transaction_id: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + stored_credential_indicator: Option<StoredCredentialIndicator>, + #[serde(skip_serializing_if = "Option::is_none")] + billing_method: Option<BillingMethod>, } #[derive(Debug, Serialize, PartialEq)] @@ -135,8 +150,14 @@ impl TryFrom<&DomainAddress> for CeleroAddress { #[serde(rename_all = "lowercase")] pub enum CeleroPaymentMethod { Card(CeleroCard), + Customer(CeleroCustomer), } +#[derive(Debug, Serialize, PartialEq)] +pub struct CeleroCustomer { + id: Option<CustomerId>, + payment_method_id: Option<String>, +} #[derive(Debug, Serialize, PartialEq, Clone, Copy)] #[serde(rename_all = "lowercase")] pub enum CeleroEntryType { @@ -233,27 +254,102 @@ impl TryFrom<&CeleroRouterData<&PaymentsAuthorizeRouterData>> for CeleroPayments .get_optional_shipping() .and_then(|address| address.try_into().ok()); - // Check if 3DS is requested - let is_three_ds = item.router_data.is_three_ds(); + // Determine CIT/MIT fields based on mandate data + let (mandate_fields, payment_method) = determine_cit_mit_fields(item.router_data)?; let request = Self { idempotency_key: item.router_data.connector_request_reference_id.clone(), transaction_type, amount: item.amount, currency: item.router_data.request.currency, - payment_method: CeleroPaymentMethod::try_from(( - &item.router_data.request.payment_method_data, - is_three_ds, - ))?, + payment_method, billing_address, shipping_address, create_vault_record: Some(false), + card_on_file_indicator: mandate_fields.card_on_file_indicator, + initiated_by: mandate_fields.initiated_by, + initial_transaction_id: mandate_fields.initial_transaction_id, + stored_credential_indicator: mandate_fields.stored_credential_indicator, + billing_method: mandate_fields.billing_method, }; Ok(request) } } +// Define a struct to hold CIT/MIT fields to avoid complex tuple return type +#[derive(Debug, Default)] +pub struct CeleroMandateFields { + pub card_on_file_indicator: Option<CardOnFileIndicator>, + pub initiated_by: Option<InitiatedBy>, + pub initial_transaction_id: Option<String>, + pub stored_credential_indicator: Option<StoredCredentialIndicator>, + pub billing_method: Option<BillingMethod>, +} + +// Helper function to determine CIT/MIT fields based on mandate data +fn determine_cit_mit_fields( + router_data: &PaymentsAuthorizeRouterData, +) -> Result<(CeleroMandateFields, CeleroPaymentMethod), error_stack::Report<errors::ConnectorError>> +{ + // Default null values + let mut mandate_fields = CeleroMandateFields::default(); + + // First check if there's a mandate_id in the request + match router_data + .request + .mandate_id + .clone() + .and_then(|mandate_ids| mandate_ids.mandate_reference_id) + { + // If there's a connector mandate ID, this is a MIT (Merchant Initiated Transaction) + Some(api_models::payments::MandateReferenceId::ConnectorMandateId( + connector_mandate_id, + )) => { + mandate_fields.card_on_file_indicator = Some(CardOnFileIndicator::RecurringPayment); + mandate_fields.initiated_by = Some(InitiatedBy::Merchant); // This is a MIT + mandate_fields.stored_credential_indicator = Some(StoredCredentialIndicator::Used); + mandate_fields.billing_method = Some(BillingMethod::Recurring); + mandate_fields.initial_transaction_id = + connector_mandate_id.get_connector_mandate_request_reference_id(); + Ok(( + mandate_fields, + CeleroPaymentMethod::Customer(CeleroCustomer { + id: Some(router_data.get_customer_id()?), + payment_method_id: connector_mandate_id.get_payment_method_id(), + }), + )) + } + // For other mandate types that might not be supported + Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) + | Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_)) => { + // These might need different handling or return an error + Err(errors::ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Celero"), + ) + .into()) + } + // If no mandate ID is present, check if it's a mandate payment + None => { + if router_data.request.is_mandate_payment() { + // This is a customer-initiated transaction for a recurring payment + mandate_fields.initiated_by = Some(InitiatedBy::Customer); + mandate_fields.card_on_file_indicator = Some(CardOnFileIndicator::RecurringPayment); + mandate_fields.billing_method = Some(BillingMethod::Recurring); + mandate_fields.stored_credential_indicator = Some(StoredCredentialIndicator::Used); + } + let is_three_ds = router_data.is_three_ds(); + Ok(( + mandate_fields, + CeleroPaymentMethod::try_from(( + &router_data.request.payment_method_data, + is_three_ds, + ))?, + )) + } + } +} + // Auth Struct for CeleroCommerce API key authentication pub struct CeleroAuthType { pub(super) api_key: Secret<String>, @@ -326,6 +422,38 @@ pub enum TransactionType { Sale, Authorize, } + +// CIT/MIT related enums +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub enum CardOnFileIndicator { + #[serde(rename = "C")] + GeneralPurposeStorage, + #[serde(rename = "R")] + RecurringPayment, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum InitiatedBy { + Customer, + Merchant, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum StoredCredentialIndicator { + Used, + Stored, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum BillingMethod { + Straight, + #[serde(rename = "initial_recurring")] + InitialRecurring, + Recurring, +} #[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] #[serde_with::skip_serializing_none] pub struct CeleroTransactionResponseData { @@ -337,6 +465,26 @@ pub struct CeleroTransactionResponseData { pub response: CeleroPaymentMethodResponse, pub billing_address: Option<CeleroAddressResponse>, pub shipping_address: Option<CeleroAddressResponse>, + // Additional fields from the sample response + pub status: Option<String>, + pub response_code: Option<i32>, + pub customer_id: Option<String>, + pub payment_method_id: Option<String>, +} + +impl CeleroTransactionResponseData { + pub fn get_mandate_reference(&self) -> Box<Option<MandateReference>> { + if self.payment_method_id.is_some() { + Box::new(Some(MandateReference { + connector_mandate_id: None, + payment_method_id: self.payment_method_id.clone(), + mandate_metadata: None, + connector_mandate_request_reference_id: Some(self.id.clone()), + })) + } else { + Box::new(None) + } + } } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] @@ -411,9 +559,11 @@ impl<F, T> TryFrom<ResponseRouterData<F, CeleroPaymentsResponse, T, PaymentsResp Ok(Self { status: final_status, response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId(data.id), + resource_id: ResponseId::ConnectorTransactionId( + data.id.clone(), + ), redirection_data: Box::new(None), - mandate_reference: Box::new(None), + mandate_reference: data.get_mandate_reference(), connector_metadata: None, network_txn_id: None, connector_response_reference_id: response.auth_code.clone(), @@ -427,6 +577,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, CeleroPaymentsResponse, T, PaymentsResp } } else { // No transaction data in successful response + // We don't have a transaction ID in this case Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(hyperswitch_domain_models::router_data::ErrorResponse { @@ -450,6 +601,10 @@ impl<F, T> TryFrom<ResponseRouterData<F, CeleroPaymentsResponse, T, PaymentsResp let error_details = CeleroErrorDetails::from_top_level_error(item.response.msg.clone()); + // Extract transaction ID from the top-level data if available + let connector_transaction_id = + item.response.data.as_ref().map(|data| data.id.clone()); + Ok(Self { status: common_enums::AttemptStatus::Failure, response: Err(hyperswitch_domain_models::router_data::ErrorResponse { @@ -460,7 +615,7 @@ impl<F, T> TryFrom<ResponseRouterData<F, CeleroPaymentsResponse, T, PaymentsResp reason: error_details.decline_reason, status_code: item.http_code, attempt_status: None, - connector_transaction_id: None, + connector_transaction_id, network_decline_code: None, network_advice_code: None, network_error_message: None,
2025-08-22T07:29: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 --> CIT-MIT implementation for CELERO (alpha connector) DOCS - https://sandbox.gotnpgateway.com/docs/api/transactions#cit-mit Caviats - Connector expecting initial_transaction_id which is nothing but prev txn id - Connector not returning `payment_method_id` or `mandate_id` ### Note this is an alpha connector and we depend on alpha cypress test which ### 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` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.116.0
8446ffbf5992a97d79d129cade997effc60fcd85
8446ffbf5992a97d79d129cade997effc60fcd85
juspay/hyperswitch
juspay__hyperswitch-9016
Bug: [FEATURE] Automatic connector_payment_id hashing in v2 if length > 128 in v2 ### Feature Description Automatically hash connector_payment_id longer than 128 chars and store the original in connector_payment_data. ### Possible Implementation Implement hashing in PaymentAttemptUpdate conversion by using ConnectorTransactionId::form_id_and_data, setting connector_payment_id to the hash and preserving the original in connector_payment_data. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 0a085991815..7a1494ea923 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -743,57 +743,51 @@ pub enum PaymentAttemptUpdate { // error_message: Option<Option<String>>, // updated_by: String, // }, - // ResponseUpdate { - // status: storage_enums::AttemptStatus, - // connector: Option<String>, - // connector_transaction_id: Option<String>, - // authentication_type: Option<storage_enums::AuthenticationType>, - // payment_method_id: Option<String>, - // mandate_id: Option<String>, - // connector_metadata: Option<serde_json::Value>, - // payment_token: Option<String>, - // error_code: Option<Option<String>>, - // error_message: Option<Option<String>>, - // error_reason: Option<Option<String>>, - // connector_response_reference_id: Option<String>, - // amount_capturable: Option<MinorUnit>, - // updated_by: String, - // authentication_data: Option<serde_json::Value>, - // encoded_data: Option<String>, - // unified_code: Option<Option<String>>, - // unified_message: Option<Option<String>>, - // payment_method_data: Option<serde_json::Value>, - // charge_id: Option<String>, - // }, - // UnresolvedResponseUpdate { - // status: storage_enums::AttemptStatus, - // connector: Option<String>, - // connector_transaction_id: Option<String>, - // payment_method_id: Option<String>, - // error_code: Option<Option<String>>, - // error_message: Option<Option<String>>, - // error_reason: Option<Option<String>>, - // connector_response_reference_id: Option<String>, - // updated_by: String, - // }, + ResponseUpdate { + status: storage_enums::AttemptStatus, + connector: Option<String>, + connector_payment_id: Option<String>, + authentication_type: Option<storage_enums::AuthenticationType>, + payment_method_id: Option<id_type::GlobalPaymentMethodId>, + connector_metadata: Option<pii::SecretSerdeValue>, + payment_token: Option<String>, + error_code: Option<Option<String>>, + error_message: Option<Option<String>>, + error_reason: Option<Option<String>>, + connector_response_reference_id: Option<String>, + amount_capturable: Option<MinorUnit>, + updated_by: String, + unified_code: Option<Option<String>>, + unified_message: Option<Option<String>>, + }, + UnresolvedResponseUpdate { + status: storage_enums::AttemptStatus, + connector: Option<String>, + connector_payment_id: Option<String>, + payment_method_id: Option<id_type::GlobalPaymentMethodId>, + error_code: Option<Option<String>>, + error_message: Option<Option<String>>, + error_reason: Option<Option<String>>, + connector_response_reference_id: Option<String>, + updated_by: String, + }, // StatusUpdate { // status: storage_enums::AttemptStatus, // updated_by: String, // }, - // ErrorUpdate { - // connector: Option<String>, - // status: storage_enums::AttemptStatus, - // error_code: Option<Option<String>>, - // error_message: Option<Option<String>>, - // error_reason: Option<Option<String>>, - // amount_capturable: Option<MinorUnit>, - // updated_by: String, - // unified_code: Option<Option<String>>, - // unified_message: Option<Option<String>>, - // connector_transaction_id: Option<String>, - // payment_method_data: Option<serde_json::Value>, - // authentication_type: Option<storage_enums::AuthenticationType>, - // }, + ErrorUpdate { + connector: Option<String>, + status: storage_enums::AttemptStatus, + error_code: Option<Option<String>>, + error_message: Option<Option<String>>, + error_reason: Option<Option<String>>, + amount_capturable: Option<MinorUnit>, + updated_by: String, + unified_code: Option<Option<String>>, + unified_message: Option<Option<String>>, + connector_payment_id: Option<String>, + authentication_type: Option<storage_enums::AuthenticationType>, + }, // CaptureUpdate { // amount_to_capture: Option<MinorUnit>, // multiple_capture_count: Option<MinorUnit>, @@ -804,23 +798,20 @@ pub enum PaymentAttemptUpdate { // amount_capturable: MinorUnit, // updated_by: String, // }, - // PreprocessingUpdate { - // status: storage_enums::AttemptStatus, - // payment_method_id: Option<String>, - // connector_metadata: Option<serde_json::Value>, - // preprocessing_step_id: Option<String>, - // connector_transaction_id: Option<String>, - // connector_response_reference_id: Option<String>, - // updated_by: String, - // }, - // ConnectorResponse { - // authentication_data: Option<serde_json::Value>, - // encoded_data: Option<String>, - // connector_transaction_id: Option<String>, - // connector: Option<String>, - // charge_id: Option<String>, - // updated_by: String, - // }, + PreprocessingUpdate { + status: storage_enums::AttemptStatus, + payment_method_id: Option<id_type::GlobalPaymentMethodId>, + connector_metadata: Option<pii::SecretSerdeValue>, + preprocessing_step_id: Option<String>, + connector_payment_id: Option<String>, + connector_response_reference_id: Option<String>, + updated_by: String, + }, + ConnectorResponse { + connector_payment_id: Option<String>, + connector: Option<String>, + updated_by: String, + }, // IncrementalAuthorizationAmountUpdate { // amount: MinorUnit, // amount_capturable: MinorUnit, @@ -832,16 +823,16 @@ pub enum PaymentAttemptUpdate { // authentication_id: Option<String>, // updated_by: String, // }, - // ManualUpdate { - // status: Option<storage_enums::AttemptStatus>, - // error_code: Option<String>, - // error_message: Option<String>, - // error_reason: Option<String>, - // updated_by: String, - // unified_code: Option<String>, - // unified_message: Option<String>, - // connector_transaction_id: Option<String>, - // }, + ManualUpdate { + status: Option<storage_enums::AttemptStatus>, + error_code: Option<String>, + error_message: Option<String>, + error_reason: Option<String>, + updated_by: String, + unified_code: Option<String>, + unified_message: Option<String>, + connector_payment_id: Option<String>, + }, } // TODO: uncomment fields as and when required @@ -852,7 +843,8 @@ pub struct PaymentAttemptUpdateInternal { pub status: Option<storage_enums::AttemptStatus>, pub authentication_type: Option<storage_enums::AuthenticationType>, pub error_message: Option<String>, - pub connector_payment_id: Option<String>, + pub connector_payment_id: Option<ConnectorTransactionId>, + pub connector_payment_data: Option<String>, pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, // cancellation_reason: Option<String>, pub modified_at: PrimitiveDateTime, @@ -875,8 +867,8 @@ pub struct PaymentAttemptUpdateInternal { pub connector: Option<String>, pub redirection_data: Option<RedirectForm>, // encoded_data: Option<String>, - pub unified_code: Option<Option<String>>, - pub unified_message: Option<Option<String>>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, // external_three_ds_authentication_attempted: Option<bool>, // authentication_connector: Option<String>, // authentication_id: Option<String>, @@ -902,6 +894,7 @@ impl PaymentAttemptUpdateInternal { authentication_type, error_message, connector_payment_id, + connector_payment_data, modified_at, browser_info, error_code, @@ -958,8 +951,8 @@ impl PaymentAttemptUpdateInternal { updated_by, merchant_connector_id: merchant_connector_id.or(source.merchant_connector_id), encoded_data: source.encoded_data, - unified_code: unified_code.flatten().or(source.unified_code), - unified_message: unified_message.flatten().or(source.unified_message), + unified_code: unified_code.or(source.unified_code), + unified_message: unified_message.or(source.unified_message), net_amount: source.net_amount, external_three_ds_authentication_attempted: source .external_three_ds_authentication_attempted, @@ -983,7 +976,7 @@ impl PaymentAttemptUpdateInternal { created_by: source.created_by, payment_method_type_v2: source.payment_method_type_v2, network_transaction_id: source.network_transaction_id, - connector_payment_id: source.connector_payment_id, + connector_payment_id: connector_payment_id.or(source.connector_payment_id), payment_method_subtype: source.payment_method_subtype, routing_result: source.routing_result, authentication_applied: source.authentication_applied, @@ -991,7 +984,7 @@ impl PaymentAttemptUpdateInternal { tax_on_surcharge: source.tax_on_surcharge, payment_method_billing_address: source.payment_method_billing_address, redirection_data: redirection_data.or(source.redirection_data), - connector_payment_data: source.connector_payment_data, + connector_payment_data: connector_payment_data.or(source.connector_payment_data), connector_token_details: connector_token_details.or(source.connector_token_details), id: source.id, feature_metadata: feature_metadata.or(source.feature_metadata), @@ -1336,8 +1329,278 @@ impl PaymentAttemptUpdate { #[cfg(feature = "v2")] impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { - fn from(_payment_attempt_update: PaymentAttemptUpdate) -> Self { - todo!() + fn from(payment_attempt_update: PaymentAttemptUpdate) -> Self { + match payment_attempt_update { + PaymentAttemptUpdate::ResponseUpdate { + status, + connector, + connector_payment_id, + authentication_type, + payment_method_id, + connector_metadata, + payment_token, + error_code, + error_message, + error_reason, + connector_response_reference_id, + amount_capturable, + updated_by, + unified_code, + unified_message, + } => { + let (connector_payment_id, connector_payment_data) = connector_payment_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + + Self { + status: Some(status), + connector, + connector_payment_id, + connector_payment_data, + authentication_type, + payment_method_id, + connector_metadata, + error_code: error_code.flatten(), + error_message: error_message.flatten(), + error_reason: error_reason.flatten(), + connector_response_reference_id, + amount_capturable, + updated_by, + unified_code: unified_code.flatten(), + unified_message: unified_message.flatten(), + modified_at: common_utils::date_time::now(), + browser_info: None, + amount_to_capture: None, + merchant_connector_id: None, + redirection_data: None, + connector_token_details: None, + feature_metadata: None, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_request_reference_id: None, + } + } + PaymentAttemptUpdate::ErrorUpdate { + connector, + status, + error_code, + error_message, + error_reason, + amount_capturable, + updated_by, + unified_code, + unified_message, + connector_payment_id, + authentication_type, + } => { + let (connector_payment_id, connector_payment_data) = connector_payment_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + + Self { + connector, + status: Some(status), + error_code: error_code.flatten(), + error_message: error_message.flatten(), + error_reason: error_reason.flatten(), + amount_capturable, + updated_by, + unified_code: unified_code.flatten(), + unified_message: unified_message.flatten(), + connector_payment_id, + connector_payment_data, + authentication_type, + modified_at: common_utils::date_time::now(), + payment_method_id: None, + browser_info: None, + connector_metadata: None, + amount_to_capture: None, + merchant_connector_id: None, + redirection_data: None, + connector_token_details: None, + feature_metadata: None, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_request_reference_id: None, + connector_response_reference_id: None, + } + } + PaymentAttemptUpdate::UnresolvedResponseUpdate { + status, + connector, + connector_payment_id, + payment_method_id, + error_code, + error_message, + error_reason, + connector_response_reference_id, + updated_by, + } => { + let (connector_payment_id, connector_payment_data) = connector_payment_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + + Self { + status: Some(status), + connector, + connector_payment_id, + connector_payment_data, + payment_method_id, + error_code: error_code.flatten(), + error_message: error_message.flatten(), + error_reason: error_reason.flatten(), + connector_response_reference_id, + updated_by, + modified_at: common_utils::date_time::now(), + authentication_type: None, + browser_info: None, + connector_metadata: None, + amount_capturable: None, + amount_to_capture: None, + merchant_connector_id: None, + redirection_data: None, + unified_code: None, + unified_message: None, + connector_token_details: None, + feature_metadata: None, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_request_reference_id: None, + } + } + PaymentAttemptUpdate::PreprocessingUpdate { + status, + payment_method_id, + connector_metadata, + preprocessing_step_id, + connector_payment_id, + connector_response_reference_id, + updated_by, + } => { + let (connector_payment_id, connector_payment_data) = connector_payment_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + + Self { + status: Some(status), + payment_method_id, + connector_metadata, + connector_payment_id, + connector_payment_data, + connector_response_reference_id, + updated_by, + modified_at: common_utils::date_time::now(), + authentication_type: None, + error_message: None, + browser_info: None, + error_code: None, + error_reason: None, + amount_capturable: None, + amount_to_capture: None, + merchant_connector_id: None, + connector: None, + redirection_data: None, + unified_code: None, + unified_message: None, + connector_token_details: None, + feature_metadata: None, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_request_reference_id: None, + } + } + PaymentAttemptUpdate::ConnectorResponse { + connector_payment_id, + connector, + updated_by, + } => { + let (connector_payment_id, connector_payment_data) = connector_payment_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + + Self { + connector_payment_id, + connector_payment_data, + connector, + updated_by, + modified_at: common_utils::date_time::now(), + status: None, + authentication_type: None, + error_message: None, + payment_method_id: None, + browser_info: None, + error_code: None, + connector_metadata: None, + error_reason: None, + amount_capturable: None, + amount_to_capture: None, + merchant_connector_id: None, + redirection_data: None, + unified_code: None, + unified_message: None, + connector_token_details: None, + feature_metadata: None, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_request_reference_id: None, + connector_response_reference_id: None, + } + } + PaymentAttemptUpdate::ManualUpdate { + status, + error_code, + error_message, + error_reason, + updated_by, + unified_code, + unified_message, + connector_payment_id, + } => { + let (connector_payment_id, connector_payment_data) = connector_payment_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + + Self { + status, + error_code, + error_message, + error_reason, + updated_by, + unified_code, + unified_message, + connector_payment_id, + connector_payment_data, + modified_at: common_utils::date_time::now(), + authentication_type: None, + payment_method_id: None, + browser_info: None, + connector_metadata: None, + amount_capturable: None, + amount_to_capture: None, + merchant_connector_id: None, + connector: None, + redirection_data: None, + connector_token_details: None, + feature_metadata: None, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_request_reference_id: None, + connector_response_reference_id: None, + } + } + } // match payment_attempt_update { // PaymentAttemptUpdate::Update { // amount, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 4d1ae8bb920..ef33e561b4e 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -2805,6 +2805,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal unified_code: None, unified_message: None, connector_payment_id: None, + connector_payment_data: None, connector: Some(connector), redirection_data: None, connector_metadata: None, @@ -2825,33 +2826,42 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal connector_payment_id, amount_capturable, updated_by, - } => Self { - status: Some(status), - payment_method_id: None, - error_message: Some(error.message), - error_code: Some(error.code), - modified_at: common_utils::date_time::now(), - browser_info: None, - error_reason: error.reason, - updated_by, - merchant_connector_id: None, - unified_code: None, - unified_message: None, - connector_payment_id, - connector: None, - redirection_data: None, - connector_metadata: None, - amount_capturable, - amount_to_capture: None, - connector_token_details: None, - authentication_type: None, - feature_metadata: None, - network_advice_code: error.network_advice_code, - network_decline_code: error.network_decline_code, - network_error_message: error.network_error_message, - connector_request_reference_id: None, - connector_response_reference_id: None, - }, + } => { + // Apply automatic hashing for long connector payment IDs + let (connector_payment_id, connector_payment_data) = connector_payment_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + + Self { + status: Some(status), + payment_method_id: None, + error_message: Some(error.message), + error_code: Some(error.code), + modified_at: common_utils::date_time::now(), + browser_info: None, + error_reason: error.reason, + updated_by, + merchant_connector_id: None, + unified_code: None, + unified_message: None, + connector_payment_id, + connector_payment_data, + connector: None, + redirection_data: None, + connector_metadata: None, + amount_capturable, + amount_to_capture: None, + connector_token_details: None, + authentication_type: None, + feature_metadata: None, + network_advice_code: error.network_advice_code, + network_decline_code: error.network_decline_code, + network_error_message: error.network_error_message, + connector_request_reference_id: None, + connector_response_reference_id: None, + } + } PaymentAttemptUpdate::ConfirmIntentResponse(confirm_intent_response_update) => { let ConfirmIntentResponseUpdate { status, @@ -2863,6 +2873,12 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal connector_token_details, connector_response_reference_id, } = *confirm_intent_response_update; + + // Apply automatic hashing for long connector payment IDs + let (connector_payment_id, connector_payment_data) = connector_payment_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); Self { status: Some(status), payment_method_id: None, @@ -2877,6 +2893,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal unified_code: None, unified_message: None, connector_payment_id, + connector_payment_data, connector: None, redirection_data: redirection_data .map(diesel_models::payment_attempt::RedirectForm::from), @@ -2910,6 +2927,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal unified_code: None, unified_message: None, connector_payment_id: None, + connector_payment_data: None, connector: None, redirection_data: None, connector_metadata: None, @@ -2942,6 +2960,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal unified_code: None, unified_message: None, connector_payment_id: None, + connector_payment_data: None, connector: None, redirection_data: None, connector_metadata: None, @@ -2970,6 +2989,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal unified_code: None, unified_message: None, connector_payment_id: None, + connector_payment_data: None, connector: None, redirection_data: None, status: None, @@ -3004,6 +3024,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal unified_code: None, unified_message: None, connector_payment_id: None, + connector_payment_data: None, connector: Some(connector), redirection_data: None, connector_metadata: None,
2025-08-21T13:30:48Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Implement hashing in PaymentAttemptUpdate conversion by using ConnectorTransactionId::form_id_and_data, setting connector_payment_id to the hash and preserving the original in connector_payment_data.For worldpay connector_payment_id should be less then 128 so after this original payment_id will be stored in connector_payment_data and hased id will be stored in connector_payment_id that is less than 128. ### 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). --> If connector transaction id is more than 128 then payment intents are failing. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Request: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0198ccb7376f74a38cad615be26fa5a8/confirm-intent' \ --header 'x-profile-id: pro_ODIfdcDxqoiMbqheIsJk' \ --header 'x-client-secret: cs_0198ccb737837d90b70939489421999b' \ --header 'Authorization: api-key=dev_uf0UlpOafwdX9RSG1PcLVpW7X2QBwM9h3XQ0dYplnSaUxz19t18ylXpa7KcLMZK5' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_1c90c0f7679f4edd8544c8dfe39fc46d' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "26", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit", "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "accept_header": "text\\/html,application\\/xhtml+xml,application\\/xml;q=0.9,image\\/webp,image\\/apng,*\\/*;q=0.8", "language": "en-GB", "color_depth": 24, "screen_height": 1440, "screen_width": 2560, "time_zone": -330, "java_enabled": true, "java_script_enabled": true, "ip_address": "0.0.0.0" } }' ``` Response: ``` { "id": "12345_pay_0198ccb7376f74a38cad615be26fa5a8", "status": "succeeded", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": 100 }, "customer_id": null, "connector": "worldpay", "created": "2025-08-21T13:00:16.122Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": "eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNi4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT9TAfq0WMxFYyAoD6mMf6Crhf7XoNg6BSaRfnbGX:1Ranv7RKyexxN4UZGNvq4ZuRjjszRbCOMdf1GwWUwp05qAqWWPHGXgnjILdaJfxgAakBurvk:7t7Hx793s0jicYqEU4sbE4TxIcxVuGWepjm49witK5xZ3XDNLML2TKoEMEhI+bQbMnX8zOFyl9tDujZnveoWvbcKsU0kCH69a7ZfVd6u38N8OTvVGU+L0IvQTMgnGh5Fkg:0WwlgnJokKmtPBi4oU3Cnnm+nW8BSObf1OW7W1blA9xV3jt84HBWb3g==", "connector_reference_id": "6632a554-bf74-46cb-be9c-c03c0f6e597d", "merchant_connector_id": "mca_fRb8a8ohINpIeEdELcwq", "browser_info": null, "error": null, "shipping": null, "billing": null, "attempts": null, "connector_token_details": null, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds", "is_iframe_redirection_enabled": null, "merchant_reference_id": null, "raw_connector_response": null, "feature_metadata": null } ``` <img width="1325" height="1039" alt="image" src="https://github.com/user-attachments/assets/a4d6841d-2819-4605-b2ac-f848ecaa468a" /> <img width="1721" height="205" alt="image" src="https://github.com/user-attachments/assets/850533c8-a55f-49fb-b1a4-acc3b88d692c" /> closes #9016 ## 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.116.0
f5db00352b90e99e78b631fa8b9cde5800093a9d
f5db00352b90e99e78b631fa8b9cde5800093a9d
juspay/hyperswitch
juspay__hyperswitch-9027
Bug: [BUG] There is a bug when the webhook response comes from ucs ### Bug Description There is a bug when the webhook response comes from ucs, the code was not able to deserialize the response ### Expected Behavior webhook response form ucs should be handle using ucs logic ### Actual Behavior a webhook failed ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs index a01ca3eeeea..bb58a0dc440 100644 --- a/crates/api_models/src/webhooks.rs +++ b/crates/api_models/src/webhooks.rs @@ -68,6 +68,67 @@ pub enum IncomingWebhookEvent { RecoveryInvoiceCancel, } +impl IncomingWebhookEvent { + /// Convert UCS event type integer to IncomingWebhookEvent + /// Maps from proto WebhookEventType enum values to IncomingWebhookEvent variants + pub fn from_ucs_event_type(event_type: i32) -> Self { + match event_type { + 0 => Self::EventNotSupported, + // Payment intent events + 1 => Self::PaymentIntentFailure, + 2 => Self::PaymentIntentSuccess, + 3 => Self::PaymentIntentProcessing, + 4 => Self::PaymentIntentPartiallyFunded, + 5 => Self::PaymentIntentCancelled, + 6 => Self::PaymentIntentCancelFailure, + 7 => Self::PaymentIntentAuthorizationSuccess, + 8 => Self::PaymentIntentAuthorizationFailure, + 9 => Self::PaymentIntentCaptureSuccess, + 10 => Self::PaymentIntentCaptureFailure, + 11 => Self::PaymentIntentExpired, + 12 => Self::PaymentActionRequired, + // Source events + 13 => Self::SourceChargeable, + 14 => Self::SourceTransactionCreated, + // Refund events + 15 => Self::RefundFailure, + 16 => Self::RefundSuccess, + // Dispute events + 17 => Self::DisputeOpened, + 18 => Self::DisputeExpired, + 19 => Self::DisputeAccepted, + 20 => Self::DisputeCancelled, + 21 => Self::DisputeChallenged, + 22 => Self::DisputeWon, + 23 => Self::DisputeLost, + // Mandate events + 24 => Self::MandateActive, + 25 => Self::MandateRevoked, + // Miscellaneous events + 26 => Self::EndpointVerification, + 27 => Self::ExternalAuthenticationARes, + 28 => Self::FrmApproved, + 29 => Self::FrmRejected, + // Payout events + #[cfg(feature = "payouts")] + 30 => Self::PayoutSuccess, + #[cfg(feature = "payouts")] + 31 => Self::PayoutFailure, + #[cfg(feature = "payouts")] + 32 => Self::PayoutProcessing, + #[cfg(feature = "payouts")] + 33 => Self::PayoutCancelled, + #[cfg(feature = "payouts")] + 34 => Self::PayoutCreated, + #[cfg(feature = "payouts")] + 35 => Self::PayoutExpired, + #[cfg(feature = "payouts")] + 36 => Self::PayoutReversed, + _ => Self::EventNotSupported, + } + } +} + pub enum WebhookFlow { Payment, #[cfg(feature = "payouts")] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 07916214269..806e84ebb9c 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -573,6 +573,7 @@ pub enum CallConnectorAction { error_message: Option<String>, }, HandleResponse(Vec<u8>), + UCSHandleResponse(Vec<u8>), } /// The three-letter ISO 4217 currency code (e.g., "USD", "EUR") for the payment amount. This field is mandatory for creating a payment. diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 5008b3a68b7..da8d9321f22 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -4263,7 +4263,13 @@ where services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { record_time_taken_with(|| async { - if should_call_unified_connector_service( + if !matches!( + call_connector_action, + CallConnectorAction::UCSHandleResponse(_) + ) && !matches!( + call_connector_action, + CallConnectorAction::HandleResponse(_), + ) && should_call_unified_connector_service( state, merchant_context, &router_data, diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs index 40422e82542..dec4281e7a9 100644 --- a/crates/router/src/core/unified_connector_service/transformers.rs +++ b/crates/router/src/core/unified_connector_service/transformers.rs @@ -1220,6 +1220,7 @@ impl ForeignTryFrom<&hyperswitch_interfaces::webhooks::IncomingWebhookRequestDet } /// Webhook transform data structure containing UCS response information +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct WebhookTransformData { pub event_type: api_models::webhooks::IncomingWebhookEvent, pub source_verified: bool, @@ -1231,16 +1232,8 @@ pub struct WebhookTransformData { pub fn transform_ucs_webhook_response( response: PaymentServiceTransformResponse, ) -> Result<WebhookTransformData, error_stack::Report<errors::ApiErrorResponse>> { - let event_type = match response.event_type { - 0 => api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess, - 1 => api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure, - 2 => api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing, - 3 => api_models::webhooks::IncomingWebhookEvent::PaymentIntentCancelled, - 4 => api_models::webhooks::IncomingWebhookEvent::RefundSuccess, - 5 => api_models::webhooks::IncomingWebhookEvent::RefundFailure, - 6 => api_models::webhooks::IncomingWebhookEvent::MandateRevoked, - _ => api_models::webhooks::IncomingWebhookEvent::EventNotSupported, - }; + let event_type = + api_models::webhooks::IncomingWebhookEvent::from_ucs_event_type(response.event_type); Ok(WebhookTransformData { event_type, diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 29a6c6c8e26..4d38ce2ed02 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -695,6 +695,7 @@ async fn process_webhook_business_logic( connector, request_details, event_type, + webhook_transform_data, )) .await .attach_printable("Incoming webhook flow for payments failed"), @@ -931,9 +932,22 @@ async fn payments_incoming_webhook_flow( connector: &ConnectorEnum, request_details: &IncomingWebhookRequestDetails<'_>, event_type: webhooks::IncomingWebhookEvent, + webhook_transform_data: &Option<Box<unified_connector_service::WebhookTransformData>>, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let consume_or_trigger_flow = if source_verified { - payments::CallConnectorAction::HandleResponse(webhook_details.resource_object) + // Determine the appropriate action based on UCS availability + let resource_object = webhook_details.resource_object; + + match webhook_transform_data.as_ref() { + Some(transform_data) => { + // Serialize the transform data to pass to UCS handler + let transform_data_bytes = serde_json::to_vec(transform_data.as_ref()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to serialize UCS webhook transform data")?; + payments::CallConnectorAction::UCSHandleResponse(transform_data_bytes) + } + None => payments::CallConnectorAction::HandleResponse(resource_object), + } } else { payments::CallConnectorAction::Trigger }; diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 41a12f35576..fa8e840fdea 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -61,7 +61,7 @@ use crate::{ core::{ api_locking, errors::{self, CustomResult}, - payments, + payments, unified_connector_service, }, events::{ api_logs::{ApiEvent, ApiEventMetric, ApiEventsType}, @@ -127,6 +127,62 @@ pub type BoxedBillingConnectorPaymentsSyncIntegrationInterface<T, Req, Res> = pub type BoxedVaultConnectorIntegrationInterface<T, Req, Res> = BoxedConnectorIntegrationInterface<T, common_types::VaultConnectorFlowData, Req, Res>; +/// Handle UCS webhook response processing +fn handle_ucs_response<T, Req, Resp>( + router_data: types::RouterData<T, Req, Resp>, + transform_data_bytes: Vec<u8>, +) -> CustomResult<types::RouterData<T, Req, Resp>, errors::ConnectorError> +where + T: Clone + Debug + 'static, + Req: Debug + Clone + 'static, + Resp: Debug + Clone + 'static, +{ + let webhook_transform_data: unified_connector_service::WebhookTransformData = + serde_json::from_slice(&transform_data_bytes) + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .attach_printable("Failed to deserialize UCS webhook transform data")?; + + let webhook_content = webhook_transform_data + .webhook_content + .ok_or(errors::ConnectorError::ResponseDeserializationFailed) + .attach_printable("UCS webhook transform data missing webhook_content")?; + + let payment_get_response = match webhook_content.content { + Some(unified_connector_service_client::payments::webhook_response_content::Content::PaymentsResponse(payments_response)) => { + Ok(payments_response) + }, + Some(unified_connector_service_client::payments::webhook_response_content::Content::RefundsResponse(_)) => { + Err(errors::ConnectorError::ProcessingStepFailed(Some("UCS webhook contains refund response but payment processing was expected".to_string().into())).into()) + }, + Some(unified_connector_service_client::payments::webhook_response_content::Content::DisputesResponse(_)) => { + Err(errors::ConnectorError::ProcessingStepFailed(Some("UCS webhook contains dispute response but payment processing was expected".to_string().into())).into()) + }, + None => { + Err(errors::ConnectorError::ResponseDeserializationFailed) + .attach_printable("UCS webhook content missing payments_response") + } + }?; + + let (status, router_data_response, status_code) = + unified_connector_service::handle_unified_connector_service_response_for_payment_get( + payment_get_response.clone(), + ) + .change_context(errors::ConnectorError::ProcessingStepFailed(None)) + .attach_printable("Failed to process UCS webhook response using PSync handler")?; + + let mut updated_router_data = router_data; + updated_router_data.status = status; + + let _ = router_data_response.map_err(|error_response| { + updated_router_data.response = Err(error_response); + }); + updated_router_data.raw_connector_response = + payment_get_response.raw_connector_response.map(Secret::new); + updated_router_data.connector_http_status_code = Some(status_code); + + Ok(updated_router_data) +} + fn store_raw_connector_response_if_required<T, Req, Resp>( return_raw_connector_response: Option<bool>, router_data: &mut types::RouterData<T, Req, Resp>, @@ -186,6 +242,9 @@ where }; connector_integration.handle_response(req, None, response) } + payments::CallConnectorAction::UCSHandleResponse(transform_data_bytes) => { + handle_ucs_response(router_data, transform_data_bytes) + } payments::CallConnectorAction::Avoid => Ok(router_data), payments::CallConnectorAction::StatusUpdate { status,
2025-08-22T05:20:49Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description while handling the response of UCS for webhooks Hyperswitch used to use the existing connector code (Psync's Handle Respnse) which gave error for UCS response so fixed this issue. Closes #9027 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> testing of the webhook can be done by the step in this merged PR:https://github.com/juspay/hyperswitch/pull/8814 ## 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.116.0
a589e2246447b7096fd335d444a24b2450c3e7c2
a589e2246447b7096fd335d444a24b2450c3e7c2
juspay/hyperswitch
juspay__hyperswitch-9004
Bug: [BUG] Incremental authorization proceeds even when requested amount equals original ### Bug Description Incremental authorization proceeds even when requested amount equals original ### Expected Behavior Incremental authorization should not proceed when requested amount equals original ### Actual Behavior Incremental authorization proceeds even when requested amount equals original ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/stripe.rs b/crates/hyperswitch_connectors/src/connectors/stripe.rs index fc27effefca..b7810310369 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripe.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe.rs @@ -1086,7 +1086,7 @@ impl MinorUnit::new(req.request.total_amount), req.request.currency, )?; - let connector_req = stripe::StripeIncrementalAuthRequest { amount }; + let connector_req = stripe::StripeIncrementalAuthRequest { amount }; // Incremental authorization can be done a maximum of 10 times in Stripe Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } @@ -1162,7 +1162,8 @@ impl .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error - .code + .message + .clone() .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs index a32f89ef4d3..862fcd8ff18 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -101,7 +101,7 @@ impl<F: Send + Clone + Sync> // Incremental authorization should be performed on an amount greater than the original authorized amount (in this case, greater than the net_amount which is sent for authorization) // request.amount is the total amount that should be authorized in incremental authorization which should be greater than the original authorized amount - if payment_attempt.get_total_amount() > request.amount { + if payment_attempt.get_total_amount() >= request.amount { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Amount should be greater than original authorized amount".to_owned(), })?
2025-08-20T13:37:11Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes these issues - [Issue 1](https://github.com/juspay/hyperswitch/issues/9003) [Issue 2](https://github.com/juspay/hyperswitch/issues/9004) ## Description <!-- Describe your changes in detail --> Populated Error Message in Incremental Authorization Flow. Added check for same amount in incremental authorization requests. ### 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 1. Payments - Create Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_jVOnDLj6Q2nOHSSL8NIMQUws6P8WIRE9QNZ6toLt4gB7DqXuObIkVwPiXLJsY16n' \ --data-raw '{ "amount": 6500, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6500, "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "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": "2025-07-25T11:46:12Z" }, "request_incremental_authorization": true }' ``` Response: ``` { "payment_id": "pay_fXzLwsUeDagw7Cdyp8Sh", "merchant_id": "merchant_1755689870", "status": "requires_capture", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 6500, "amount_received": 0, "connector": "stripe", "client_secret": "pay_fXzLwsUeDagw7Cdyp8Sh_secret_Uoa82RaRfj6xcV3MnUtO", "created": "2025-08-20T12:16:31.560Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": 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": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1755692191, "expires": 1755695791, "secret": "epk_c558a24e699a4b9db808d953a8df38f5" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RyAwOE9cSvqiivY17rwXSCJ", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3RyAwOE9cSvqiivY17rwXSCJ", "payment_link": null, "profile_id": "pro_PMx2Y9TaHmSY8wUiC8kP", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_7VMxMHsmscuHwnVdYZPE", "incremental_authorization_allowed": true, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-20T12:31:31.560Z", "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_channel": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-08-20T12:16:32.579Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` 2. Payments - Incremental Authorization (with same amount) Request: ``` curl --location 'http://localhost:8080/payments/pay_fXzLwsUeDagw7Cdyp8Sh/incremental_authorization' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_jVOnDLj6Q2nOHSSL8NIMQUws6P8WIRE9QNZ6toLt4gB7DqXuObIkVwPiXLJsY16n' \ --data '{ "amount": 6500 }' ``` Response: ``` { "error": { "type": "invalid_request", "message": "Amount should be greater than original authorized amount", "code": "IR_16" } } ``` 3. Payments - Incremental Authorization (exceeding the maximum amount of time the flow can be called in Stripe) Request: ``` curl --location 'http://localhost:8080/payments/pay_gIQKmooikg2npSvaM9xZ/incremental_authorization' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_jVOnDLj6Q2nOHSSL8NIMQUws6P8WIRE9QNZ6toLt4gB7DqXuObIkVwPiXLJsY16n' \ --data '{ "amount": 6511 }' ``` Response: ``` { "payment_id": "pay_gIQKmooikg2npSvaM9xZ", "merchant_id": "merchant_1755689870", "status": "requires_capture", "amount": 6510, "net_amount": 6510, "shipping_cost": null, "amount_capturable": 6510, "amount_received": null, "connector": "stripe", "client_secret": "pay_gIQKmooikg2npSvaM9xZ_secret_cmcrBTpMQL6Prbvudezo", "created": "2025-08-20T13:28:31.692Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": 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": "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": "pi_3RyC44E9cSvqiivY14N3VxbQ", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pi_3RyC44E9cSvqiivY14N3VxbQ", "payment_link": null, "profile_id": "pro_PMx2Y9TaHmSY8wUiC8kP", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_7VMxMHsmscuHwnVdYZPE", "incremental_authorization_allowed": true, "authorization_count": 11, "incremental_authorizations": [ { "authorization_id": "auth_RI9tMBRwaju7LpkDhNrT_1", "amount": 6501, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6500 }, { "authorization_id": "auth_BoyLq9eHomflrMn5f2kD_2", "amount": 6502, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6501 }, { "authorization_id": "auth_LZZQWDEHw57lbLcqqKv2_3", "amount": 6503, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6502 }, { "authorization_id": "auth_RQeNDy0sdQnaLEW7f4Rm_4", "amount": 6504, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6503 }, { "authorization_id": "auth_2MRj0ANmGIW6BvFARHAe_5", "amount": 6505, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6504 }, { "authorization_id": "auth_egVuyLWfl6jGIZKdgLrt_6", "amount": 6506, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6505 }, { "authorization_id": "auth_M33NayFU2GQicIGYMMkU_7", "amount": 6507, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6506 }, { "authorization_id": "auth_UHtSahoOk1wVd8yacnJx_8", "amount": 6508, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6507 }, { "authorization_id": "auth_IejW3q4wdP5LcRouVvGs_9", "amount": 6509, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6508 }, { "authorization_id": "auth_sZNDStbUEPdqMMEZMlOV_10", "amount": 6510, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6509 }, { "authorization_id": "auth_33dxNtWv6DiOdu3kGC4l_11", "amount": 6511, "status": "failure", "error_code": "No error code", "error_message": "The PaymentIntent has reached the maximum number of 10 allowed increments and cannot be incremented further.", "previously_authorized_amount": 6510 } ], "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-20T13:43:31.691Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-20T13:29:27.355Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": 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.116.0
e1fc14135cc3527cfb5afeccd4934bad8386c7b1
e1fc14135cc3527cfb5afeccd4934bad8386c7b1
juspay/hyperswitch
juspay__hyperswitch-9010
Bug: [FEATURE] extend PSP token provisioning through Adyen Platform ### Feature Description Enable processing payouts using Adyen stored payment method tokens (storedPaymentMethodId) in the AdyenPlatform connector. Currently, the connector only supports raw card details for payouts. This feature will add support for tokenized card payouts, allowing merchants to process payouts using previously stored payment methods using PSP tokens. ### Possible Implementation Add support for both raw card details and tokenized payments with proper fallback logic, following Adyen's Balance Platform API specifications for payouts with tokenized card details - https://docs.adyen.com/payouts/payout-service/pay-out-to-cards/card-payout-request/?tab=recurring-payouts_3 ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs index b04ca410d39..35636889d71 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs @@ -11,7 +11,9 @@ use super::{AdyenPlatformRouterData, Error}; use crate::{ connectors::adyen::transformers as adyen, types::PayoutsResponseRouterData, - utils::{self, AddressDetailsData, PayoutsData as _, RouterData as _}, + utils::{ + self, AddressDetailsData, PayoutFulfillRequestData, PayoutsData as _, RouterData as _, + }, }; #[derive(Debug, Default, Serialize, Deserialize)] @@ -54,8 +56,6 @@ pub enum AdyenPayoutMethod { pub enum AdyenPayoutMethodDetails { BankAccount(AdyenBankAccountDetails), Card(AdyenCardDetails), - #[serde(rename = "card")] - CardToken(AdyenCardTokenDetails), } #[derive(Debug, Serialize, Deserialize)] @@ -117,9 +117,16 @@ pub struct AdyenCardDetails { card_identification: AdyenCardIdentification, } +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum AdyenCardIdentification { + Card(AdyenRawCardIdentification), + Stored(AdyenStoredCardIdentification), +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] -pub struct AdyenCardIdentification { +pub struct AdyenRawCardIdentification { #[serde(rename = "number")] card_number: cards::CardNumber, expiry_month: Secret<String>, @@ -131,14 +138,7 @@ pub struct AdyenCardIdentification { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] -pub struct AdyenCardTokenDetails { - card_holder: AdyenAccountHolder, - card_identification: AdyenCardTokenIdentification, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct AdyenCardTokenIdentification { +pub struct AdyenStoredCardIdentification { stored_payment_method_id: Secret<String>, } @@ -260,7 +260,6 @@ impl<F> TryFrom<(&PayoutsRouterData<F>, &payouts::CardPayout)> for AdyenAccountH ) -> Result<Self, Self::Error> { let billing_address = router_data.get_optional_billing(); - // Address is required for both card and bank payouts let address = billing_address .and_then(|billing| billing.address.as_ref().map(|addr| addr.try_into())) .transpose()? @@ -294,13 +293,25 @@ impl<F> TryFrom<(&PayoutsRouterData<F>, &payouts::CardPayout)> for AdyenAccountH .into()); }; + let customer_id_reference = match router_data.get_connector_customer_id() { + Ok(connector_customer_id) => connector_customer_id, + Err(_) => { + let customer_id = router_data.get_customer_id()?; + format!( + "{}_{}", + router_data.merchant_id.get_string_repr(), + customer_id.get_string_repr() + ) + } + }; + Ok(Self { address: Some(address), first_name, last_name, full_name: None, email: router_data.get_optional_billing_email(), - customer_id: Some(router_data.get_customer_id()?.get_string_repr().to_owned()), + customer_id: Some(customer_id_reference), entity_type: Some(EntityType::from(router_data.request.entity_type)), }) } @@ -314,7 +325,6 @@ impl<F> TryFrom<(&PayoutsRouterData<F>, &payouts::Bank)> for AdyenAccountHolder ) -> Result<Self, Self::Error> { let billing_address = router_data.get_optional_billing(); - // Address is required for both card and bank payouts let address = billing_address .and_then(|billing| billing.address.as_ref().map(|addr| addr.try_into())) .transpose()? @@ -324,46 +334,156 @@ impl<F> TryFrom<(&PayoutsRouterData<F>, &payouts::Bank)> for AdyenAccountHolder let full_name = router_data.get_billing_full_name()?; + let customer_id_reference = match router_data.get_connector_customer_id() { + Ok(connector_customer_id) => connector_customer_id, + Err(_) => { + let customer_id = router_data.get_customer_id()?; + format!( + "{}_{}", + router_data.merchant_id.get_string_repr(), + customer_id.get_string_repr() + ) + } + }; + Ok(Self { address: Some(address), first_name: None, last_name: None, full_name: Some(full_name), email: router_data.get_optional_billing_email(), - customer_id: Some(router_data.get_customer_id()?.get_string_repr().to_owned()), + customer_id: Some(customer_id_reference), entity_type: Some(EntityType::from(router_data.request.entity_type)), }) } } -impl<F> TryFrom<&AdyenPlatformRouterData<&PayoutsRouterData<F>>> for AdyenTransferRequest { +#[derive(Debug)] +pub struct StoredPaymentCounterparty<'a, F> { + pub item: &'a AdyenPlatformRouterData<&'a PayoutsRouterData<F>>, + pub stored_payment_method_id: String, +} + +#[derive(Debug)] +pub struct RawPaymentCounterparty<'a, F> { + pub item: &'a AdyenPlatformRouterData<&'a PayoutsRouterData<F>>, + pub raw_payout_method_data: payouts::PayoutMethodData, +} + +impl<F> TryFrom<StoredPaymentCounterparty<'_, F>> + for (AdyenPayoutMethodDetails, Option<AdyenPayoutPriority>) +{ type Error = Error; - fn try_from( - item: &AdyenPlatformRouterData<&PayoutsRouterData<F>>, - ) -> Result<Self, Self::Error> { - let request = &item.router_data.request; - let (counterparty, priority) = match item.router_data.get_payout_method_data()? { + + fn try_from(stored_payment: StoredPaymentCounterparty<'_, F>) -> Result<Self, Self::Error> { + let request = &stored_payment.item.router_data.request; + let payout_type = request.get_payout_type()?; + + match payout_type { + enums::PayoutType::Card => { + let billing_address = stored_payment.item.router_data.get_optional_billing(); + let address = billing_address + .and_then(|billing| billing.address.as_ref()) + .ok_or(ConnectorError::MissingRequiredField { + field_name: "address", + })? + .try_into()?; + + let customer_id_reference = + match stored_payment.item.router_data.get_connector_customer_id() { + Ok(connector_customer_id) => connector_customer_id, + Err(_) => { + let customer_id = stored_payment.item.router_data.get_customer_id()?; + format!( + "{}_{}", + stored_payment + .item + .router_data + .merchant_id + .get_string_repr(), + customer_id.get_string_repr() + ) + } + }; + + let card_holder = AdyenAccountHolder { + address: Some(address), + first_name: stored_payment + .item + .router_data + .get_optional_billing_first_name(), + last_name: stored_payment + .item + .router_data + .get_optional_billing_last_name(), + full_name: stored_payment + .item + .router_data + .get_optional_billing_full_name(), + email: stored_payment.item.router_data.get_optional_billing_email(), + customer_id: Some(customer_id_reference), + entity_type: Some(EntityType::from(request.entity_type)), + }; + + let card_identification = + AdyenCardIdentification::Stored(AdyenStoredCardIdentification { + stored_payment_method_id: Secret::new( + stored_payment.stored_payment_method_id, + ), + }); + + let counterparty = AdyenPayoutMethodDetails::Card(AdyenCardDetails { + card_holder, + card_identification, + }); + + Ok((counterparty, None)) + } + _ => Err(ConnectorError::NotSupported { + message: "Stored payment method is only supported for card payouts".to_string(), + connector: "Adyenplatform", + } + .into()), + } + } +} + +impl<F> TryFrom<RawPaymentCounterparty<'_, F>> + for (AdyenPayoutMethodDetails, Option<AdyenPayoutPriority>) +{ + type Error = Error; + + fn try_from(raw_payment: RawPaymentCounterparty<'_, F>) -> Result<Self, Self::Error> { + let request = &raw_payment.item.router_data.request; + + match raw_payment.raw_payout_method_data { payouts::PayoutMethodData::Wallet(_) => Err(ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Adyenplatform"), ))?, payouts::PayoutMethodData::Card(c) => { - let card_holder: AdyenAccountHolder = (item.router_data, &c).try_into()?; - let card_identification = AdyenCardIdentification { - card_number: c.card_number, - expiry_month: c.expiry_month, - expiry_year: c.expiry_year, - issue_number: None, - start_month: None, - start_year: None, - }; + let card_holder: AdyenAccountHolder = + (raw_payment.item.router_data, &c).try_into()?; + + let card_identification = + AdyenCardIdentification::Card(AdyenRawCardIdentification { + card_number: c.card_number, + expiry_month: c.expiry_month, + expiry_year: c.expiry_year, + issue_number: None, + start_month: None, + start_year: None, + }); + let counterparty = AdyenPayoutMethodDetails::Card(AdyenCardDetails { card_holder, card_identification, }); - (counterparty, None) + + Ok((counterparty, None)) } payouts::PayoutMethodData::Bank(bd) => { - let account_holder: AdyenAccountHolder = (item.router_data, &bd).try_into()?; + let account_holder: AdyenAccountHolder = + (raw_payment.item.router_data, &bd).try_into()?; let bank_details = match bd { payouts::Bank::Sepa(b) => AdyenBankAccountIdentification { bank_type: "iban".to_string(), @@ -393,9 +513,42 @@ impl<F> TryFrom<&AdyenPlatformRouterData<&PayoutsRouterData<F>>> for AdyenTransf .ok_or(ConnectorError::MissingRequiredField { field_name: "priority", })?; - (counterparty, Some(AdyenPayoutPriority::from(priority))) + + Ok((counterparty, Some(AdyenPayoutPriority::from(priority)))) } - }; + } + } +} + +impl<F> TryFrom<&AdyenPlatformRouterData<&PayoutsRouterData<F>>> for AdyenTransferRequest { + type Error = Error; + fn try_from( + item: &AdyenPlatformRouterData<&PayoutsRouterData<F>>, + ) -> Result<Self, Self::Error> { + let request = &item.router_data.request; + let stored_payment_method_result = + item.router_data.request.get_connector_transfer_method_id(); + let raw_payout_method_result = item.router_data.get_payout_method_data(); + + let (counterparty, priority) = + if let Ok(stored_payment_method_id) = stored_payment_method_result { + StoredPaymentCounterparty { + item, + stored_payment_method_id, + } + .try_into()? + } else if let Ok(raw_payout_method_data) = raw_payout_method_result { + RawPaymentCounterparty { + item, + raw_payout_method_data, + } + .try_into()? + } else { + return Err(ConnectorError::MissingRequiredField { + field_name: "payout_method_data or stored_payment_method_id", + } + .into()); + }; let adyen_connector_metadata_object = AdyenPlatformConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?; let balance_account_id = adyen_connector_metadata_object @@ -570,22 +723,11 @@ pub fn get_adyen_webhook_event( AdyenplatformWebhookStatus::Authorised | AdyenplatformWebhookStatus::Received => { webhooks::IncomingWebhookEvent::PayoutCreated } - AdyenplatformWebhookStatus::Booked => { - match category { - Some(AdyenPayoutMethod::Card) => { - // For card payouts, "booked" is the final success state - webhooks::IncomingWebhookEvent::PayoutSuccess - } - Some(AdyenPayoutMethod::Bank) => { - // For bank payouts, "booked" is intermediate - wait for final confirmation - webhooks::IncomingWebhookEvent::PayoutProcessing - } - None => { - // Default to processing if category is unknown - webhooks::IncomingWebhookEvent::PayoutProcessing - } - } - } + AdyenplatformWebhookStatus::Booked => match category { + Some(AdyenPayoutMethod::Card) => webhooks::IncomingWebhookEvent::PayoutSuccess, + Some(AdyenPayoutMethod::Bank) => webhooks::IncomingWebhookEvent::PayoutProcessing, + None => webhooks::IncomingWebhookEvent::PayoutProcessing, + }, AdyenplatformWebhookStatus::Pending => webhooks::IncomingWebhookEvent::PayoutProcessing, AdyenplatformWebhookStatus::Failed => webhooks::IncomingWebhookEvent::PayoutFailure, AdyenplatformWebhookStatus::Returned => webhooks::IncomingWebhookEvent::PayoutReversed, diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index a06b6140da4..c7784118847 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -188,7 +188,19 @@ pub fn make_dsl_input_for_payouts( payment_method_type: payout_data .payout_method_data .as_ref() - .map(api_enums::PaymentMethodType::foreign_from), + .map(api_enums::PaymentMethodType::foreign_from) + .or_else(|| { + payout_data.payment_method.as_ref().and_then(|pm| { + #[cfg(feature = "v1")] + { + pm.payment_method_type + } + #[cfg(feature = "v2")] + { + pm.payment_method_subtype + } + }) + }), card_network: None, }; Ok(dsl_inputs::BackendInput { diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 66a824fc01b..dee0d3f130a 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -58,7 +58,7 @@ use crate::{ api::{self, payments as payment_api_types, payouts}, domain, storage::{self, PaymentRoutingInfo}, - transformers::ForeignFrom, + transformers::{ForeignFrom, ForeignTryFrom}, }, utils::{self, OptionExt}, }; @@ -78,6 +78,7 @@ pub struct PayoutData { pub payout_link: Option<PayoutLink>, pub current_locale: String, pub payment_method: Option<PaymentMethod>, + pub connector_transfer_method_id: Option<String>, } // ********************************************** CORE FLOWS ********************************************** @@ -693,27 +694,8 @@ pub async fn payouts_fulfill_core( .attach_printable("Connector not found for payout fulfillment")?, }; - // Trigger fulfillment - let customer_id = payout_data - .payouts - .customer_id - .clone() - .get_required_value("customer_id")?; - payout_data.payout_method_data = Some( - helpers::make_payout_method_data( - &state, - None, - payout_attempt.payout_token.as_deref(), - &customer_id, - &payout_attempt.merchant_id, - payout_data.payouts.payout_type, - merchant_context.get_merchant_key_store(), - Some(&mut payout_data), - merchant_context.get_merchant_account().storage_scheme, - ) - .await? - .get_required_value("payout_method_data")?, - ); + helpers::fetch_payout_method_data(&state, &mut payout_data, &connector_data, &merchant_context) + .await?; Box::pin(fulfill_payout( &state, &merchant_context, @@ -1072,25 +1054,8 @@ pub async fn call_connector_payout( // Fetch / store payout_method_data if payout_data.payout_method_data.is_none() || payout_attempt.payout_token.is_none() { - let customer_id = payouts - .customer_id - .clone() - .get_required_value("customer_id")?; - payout_data.payout_method_data = Some( - helpers::make_payout_method_data( - state, - payout_data.payout_method_data.to_owned().as_ref(), - payout_attempt.payout_token.as_deref(), - &customer_id, - &payout_attempt.merchant_id, - payouts.payout_type, - merchant_context.get_merchant_key_store(), - Some(payout_data), - merchant_context.get_merchant_account().storage_scheme, - ) - .await? - .get_required_value("payout_method_data")?, - ); + helpers::fetch_payout_method_data(state, payout_data, connector_data, merchant_context) + .await?; } // Eligibility flow Box::pin(complete_payout_eligibility( @@ -2002,8 +1967,7 @@ pub async fn complete_create_recipient_disburse_account( && connector_data .connector_name .supports_vendor_disburse_account_create_for_payout() - && helpers::should_create_connector_transfer_method(&*payout_data, connector_data)? - .is_none() + && helpers::should_create_connector_transfer_method(payout_data, connector_data)?.is_none() { Box::pin(create_recipient_disburse_account( state, @@ -2706,12 +2670,29 @@ pub async fn payout_create_db_entries( .map(|pm| pm.payment_method_id.clone()), Some(api_enums::PayoutType::foreign_from(payout_method_data)), ), - None => ( - payment_method - .as_ref() - .map(|pm| pm.payment_method_id.clone()), - req.payout_type.to_owned(), - ), + None => { + ( + payment_method + .as_ref() + .map(|pm| pm.payment_method_id.clone()), + match req.payout_type { + None => payment_method + .as_ref() + .and_then(|pm| pm.payment_method) + .map(|payment_method_enum| { + api_enums::PayoutType::foreign_try_from(payment_method_enum) + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: format!( + "PaymentMethod {payment_method_enum:?} is not supported for payouts" + ), + }) + .attach_printable("Failed to convert PaymentMethod to PayoutType") + }) + .transpose()?, + payout_type => payout_type, + }, + ) + } }; let client_secret = utils::generate_id( @@ -2837,6 +2818,7 @@ pub async fn payout_create_db_entries( payout_link, current_locale: locale.to_string(), payment_method, + connector_transfer_method_id: None, }) } @@ -3031,11 +3013,10 @@ pub async fn make_payout_data( .await .transpose()?; - let payout_method_id = payouts.payout_method_id.clone(); - let mut payment_method: Option<PaymentMethod> = None; - - if let Some(pm_id) = payout_method_id { - payment_method = Some( + let payment_method = payouts + .payout_method_id + .clone() + .async_map(|pm_id| async move { db.find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), @@ -3044,9 +3025,10 @@ pub async fn make_payout_data( ) .await .change_context(errors::ApiErrorResponse::PaymentMethodNotFound) - .attach_printable("Unable to find payment method")?, - ); - } + .attach_printable("Unable to find payment method") + }) + .await + .transpose()?; Ok(PayoutData { billing_address, @@ -3061,6 +3043,7 @@ pub async fn make_payout_data( payout_link, current_locale: locale.to_string(), payment_method, + connector_transfer_method_id: None, }) } diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index d74baa2011d..8f104451be5 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -222,6 +222,49 @@ pub fn should_create_connector_transfer_method( Ok(connector_transfer_method_id) } +pub async fn fetch_payout_method_data( + state: &SessionState, + payout_data: &mut PayoutData, + connector_data: &api::ConnectorData, + merchant_context: &domain::MerchantContext, +) -> RouterResult<()> { + let connector_transfer_method_id = + should_create_connector_transfer_method(payout_data, connector_data)?; + + if connector_transfer_method_id.is_some() { + logger::info!("Using stored transfer_method_id, skipping payout_method_data fetch"); + } else { + let customer_id = payout_data + .payouts + .customer_id + .clone() + .get_required_value("customer_id")?; + + let payout_method_data_clone = payout_data.payout_method_data.clone(); + let payout_token = payout_data.payout_attempt.payout_token.clone(); + let merchant_id = payout_data.payout_attempt.merchant_id.clone(); + let payout_type = payout_data.payouts.payout_type; + + let payout_method_data = make_payout_method_data( + state, + payout_method_data_clone.as_ref(), + payout_token.as_deref(), + &customer_id, + &merchant_id, + payout_type, + merchant_context.get_merchant_key_store(), + Some(payout_data), + merchant_context.get_merchant_account().storage_scheme, + ) + .await? + .get_required_value("payout_method_data")?; + + payout_data.payout_method_data = Some(payout_method_data); + } + + Ok(()) +} + #[cfg(feature = "v1")] pub async fn save_payout_data_to_locker( state: &SessionState, diff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rs index 198caa4b893..87a0748e5f4 100644 --- a/crates/router/src/core/payouts/validator.rs +++ b/crates/router/src/core/payouts/validator.rs @@ -223,34 +223,48 @@ pub async fn validate_create_request( .await } (_, Some(_), Some(payment_method)) => { - match get_pm_list_context( - state, - payment_method - .payment_method - .as_ref() - .get_required_value("payment_method_id")?, - merchant_context.get_merchant_key_store(), - payment_method, - None, - false, - true, - merchant_context, - ) - .await? + // Check if we have a stored transfer_method_id first + if payment_method + .get_common_mandate_reference() + .ok() + .and_then(|common_mandate_ref| common_mandate_ref.payouts) + .map(|payouts_mandate_ref| !payouts_mandate_ref.0.is_empty()) + .unwrap_or(false) { - Some(pm) => match (pm.card_details, pm.bank_transfer_details) { - (Some(card), _) => Ok(Some(payouts::PayoutMethodData::Card( - api_models::payouts::CardPayout { - card_number: card.card_number.get_required_value("card_number")?, - card_holder_name: card.card_holder_name, - expiry_month: card.expiry_month.get_required_value("expiry_month")?, - expiry_year: card.expiry_year.get_required_value("expiry_year")?, - }, - ))), - (_, Some(bank)) => Ok(Some(payouts::PayoutMethodData::Bank(bank))), - _ => Ok(None), - }, - None => Ok(None), + Ok(None) + } else { + // No transfer_method_id available, proceed with vault fetch for raw card details + match get_pm_list_context( + state, + payment_method + .payment_method + .as_ref() + .get_required_value("payment_method_id")?, + merchant_context.get_merchant_key_store(), + payment_method, + None, + false, + true, + merchant_context, + ) + .await? + { + Some(pm) => match (pm.card_details, pm.bank_transfer_details) { + (Some(card), _) => Ok(Some(payouts::PayoutMethodData::Card( + api_models::payouts::CardPayout { + card_number: card.card_number.get_required_value("card_number")?, + card_holder_name: card.card_holder_name, + expiry_month: card + .expiry_month + .get_required_value("expiry_month")?, + expiry_year: card.expiry_year.get_required_value("expiry_year")?, + }, + ))), + (_, Some(bank)) => Ok(Some(payouts::PayoutMethodData::Bank(bank))), + _ => Ok(None), + }, + None => Ok(None), + } } } _ => Ok(None), diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 8109df07554..81d72101fe4 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1251,6 +1251,24 @@ impl ForeignFrom<api_models::enums::PayoutType> for api_enums::PaymentMethod { } } +#[cfg(feature = "payouts")] +impl ForeignTryFrom<api_enums::PaymentMethod> for api_models::enums::PayoutType { + type Error = error_stack::Report<errors::ApiErrorResponse>; + + fn foreign_try_from(value: api_enums::PaymentMethod) -> Result<Self, Self::Error> { + match value { + api_enums::PaymentMethod::Card => Ok(Self::Card), + api_enums::PaymentMethod::BankTransfer => Ok(Self::Bank), + api_enums::PaymentMethod::Wallet => Ok(Self::Wallet), + _ => Err(errors::ApiErrorResponse::InvalidRequestData { + message: format!("PaymentMethod {value:?} is not supported for payouts"), + }) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to convert PaymentMethod to PayoutType"), + } + } +} + #[cfg(feature = "v1")] impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderPayload { type Error = error_stack::Report<errors::ApiErrorResponse>; diff --git a/nix/modules/flake/devshell.nix b/nix/modules/flake/devshell.nix index 6df0f5951f1..2fdcdd78627 100644 --- a/nix/modules/flake/devshell.nix +++ b/nix/modules/flake/devshell.nix @@ -35,6 +35,8 @@ shellHook = '' echo 1>&2 "Ready to work on hyperswitch!" rustc --version + export OPENSSL_DIR="${pkgs.openssl.dev}" + export OPENSSL_LIB_DIR="${pkgs.openssl.out}/lib" ''; }; qa = pkgs.mkShell {
2025-08-22T15:11:48Z
## 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 support for Adyen tokenized card payouts in the AdyenPlatform connector. This enables processing payouts using stored PSP tokens - Restructured `AdyenCardIdentification` as an enum supporting both raw card data and stored payment method IDs - Added `StoredPaymentCounterparty` and `RawPaymentCounterparty` for handling different payment method types - Implemented fallback logic: stored payment method ID β†’ raw card details - Added `fetch_payout_method_data` helper function to centralize payout method data retrieval - Enhanced validator to check for stored transfer method IDs before fetching raw card 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 Enables merchants to process Adyen payouts using previously stored PSP tokens without requiring raw card data. This is helpful for migrated PSP tokens (created outside of HS). ## How did you test it? <details> <summary>1. Create a payment CIT</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ACto5kMwzvZvAZCM5LMfFoDaBxAKHNeQkYVRuitCrf2Q30DrqxbPr6YFOe8c2f3l' \ --data-raw '{"amount":4500,"currency":"EUR","confirm":true,"profile_id":"pro_S5yvh1TfnZi2Gjv7uSUQ","capture_method":"automatic","authentication_type":"three_ds","setup_future_usage":"off_session","customer_id":"cus_payment_cit_1","email":"abc@example.com","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4111111111111111","card_exp_month":"03","card_exp_year":"2030","card_cvc":"737"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","zip":"94122","country":"SG","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"guest@example.com"},"metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.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"}},"session_expiry":2890}' Response {"payment_id":"pay_funVtY7kQ3avj2SN3Lzm","merchant_id":"merchant_1755863240","status":"succeeded","amount":4500,"net_amount":4500,"shipping_cost":null,"amount_capturable":0,"amount_received":4500,"connector":"adyen","client_secret":"pay_funVtY7kQ3avj2SN3Lzm_secret_cR7UTM6j2h1jabVHAFHq","created":"2025-08-22T12:57:49.884Z","currency":"EUR","customer_id":"cus_uRtCHhDU0C2hafZMVHx1","customer":{"id":"cus_uRtCHhDU0C2hafZMVHx1","name":"Albert Klaassen","email":"abc@example.com","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":"card","payment_method_data":{"card":{"last4":"1111","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"SG","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":null,"first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"guest@example.com"},"order_details":null,"email":"abc@example.com","name":"Albert Klaassen","phone":"6168205362","return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_uRtCHhDU0C2hafZMVHx1","created_at":1755867469,"expires":1755871069,"secret":"epk_fdc03a4797ef451a98b2929bcfc398ca"},"manual_retry_allowed":false,"connector_transaction_id":"VCV7F35F2L3C37V5","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_funVtY7kQ3avj2SN3Lzm_1","payment_link":null,"profile_id":"pro_sHtakSPxfG6JnK0wpCKG","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_A3zlBnD9y8WvakW0ratr","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-08-22T13:45:59.884Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_channel":null,"payment_method_id":"pm_L6rQCpfqi5f1OAG4DHIG","network_transaction_id":"056847192959811","payment_method_status":"active","updated":"2025-08-22T12:57:50.457Z","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":"X99D3DNTHP447NV5","card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null,"is_iframe_redirection_enabled":null,"whole_connector_response":null,"enable_partial_authorization":null} Manually update `connector_mandate_detail` to include payout MCA as well { "mca_A3zlBnD9y8WvakW0ratr": { "mandate_metadata": null, "payment_method_type": "debit", "connector_mandate_id": "X99D3DNTHP447NV5", "connector_mandate_status": "active", "original_payment_authorized_amount": 4500, "original_payment_authorized_currency": "EUR", "connector_mandate_request_reference_id": "GOSHRSEHXi2emhKCLC" } } Updated to { "mca_A3zlBnD9y8WvakW0ratr": { "mandate_metadata": null, "payment_method_type": "debit", "connector_mandate_id": "X99D3DNTHP447NV5", "connector_mandate_status": "active", "original_payment_authorized_amount": 4500, "original_payment_authorized_currency": "EUR", "connector_mandate_request_reference_id": "GOSHRSEHXi2emhKCLC" }, "payouts": { "mca_NsHlFe2GsWvK9CdftrLt": { "transfer_method_id": "X99D3DNTHP447NV5" } } } </details> <details> <summary>2. Create a payout using payout_method_id</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_XKQaI34jBT7ZKVNZtpbrc1feIuijxd7MgPf8GMFvqLxniEGUdbNoKPcm0r8aHZhg' \ --data '{"payout_method_id":"pm_L6rQCpfqi5f1OAG4DHIG","amount":100,"currency":"EUR","customer_id":"cus_CzI1yN5av9n1nICj0ofl","connector":["adyenplatform"],"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"DE","first_name":"Albert","last_name":"Klassen"},"phone":{"number":"8056594427","country_code":"+91"}},"entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true}' Response {"payout_id":"payout_wJvyBtv3lJXXYe2f2Zlo","merchant_id":"merchant_1755867774","merchant_order_reference_id":null,"amount":100,"currency":"EUR","connector":"adyenplatform","payout_type":"card","payout_method_data":null,"billing":{"address":{"city":"San Fransico","country":"DE","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"Albert","last_name":"Klassen","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"auto_fulfill":true,"customer_id":"cus_CzI1yN5av9n1nICj0ofl","customer":{"id":"cus_CzI1yN5av9n1nICj0ofl","name":"Albert Klaassen","email":"abc@example.com","phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_wJvyBtv3lJXXYe2f2Zlo_secret_jgJ0TCCA8exlXEeh5KsK","return_url":null,"business_country":null,"business_label":null,"description":null,"entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"merchant_connector_id":"mca_8gi7OlijF22Wv9ImMR4w","status":"initiated","error_message":null,"error_code":null,"profile_id":"pro_8lrTNA9EX88OGfPXiElF","created":"2025-08-22T14:57:13.628Z","connector_transaction_id":"38EBH7682DK7VMVK","priority":null,"payout_link":null,"email":"abc@example.com","name":"Albert Klaassen","phone":"6168205362","phone_country_code":"+1","unified_code":null,"unified_message":null,"payout_method_id":"pm_L6rQCpfqi5f1OAG4DHIG"} </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.116.0
ad05dc4176114dad3420a78af238d3842160e464
ad05dc4176114dad3420a78af238d3842160e464
juspay/hyperswitch
juspay__hyperswitch-9014
Bug: Add gsm api for v2 Add gsm api for v2
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index eaab79a7351..04ebb83cbab 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -14631,7 +14631,9 @@ "processor_downtime", "processor_decline_unauthorized", "issue_with_payment_method", - "processor_decline_incorrect_data" + "processor_decline_incorrect_data", + "hard_decline", + "soft_decline" ] }, "EventClass": { diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 00d83f79657..92807225de6 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -10718,7 +10718,9 @@ "processor_downtime", "processor_decline_unauthorized", "issue_with_payment_method", - "processor_decline_incorrect_data" + "processor_decline_incorrect_data", + "hard_decline", + "soft_decline" ] }, "ErrorDetails": { diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 8fbc29c6963..c874271285b 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -8385,6 +8385,8 @@ pub enum ErrorCategory { ProcessorDeclineUnauthorized, IssueWithPaymentMethod, ProcessorDeclineIncorrectData, + HardDecline, + SoftDecline, } impl ErrorCategory { @@ -8393,7 +8395,9 @@ impl ErrorCategory { Self::ProcessorDowntime | Self::ProcessorDeclineUnauthorized => true, Self::IssueWithPaymentMethod | Self::ProcessorDeclineIncorrectData - | Self::FrmDecline => false, + | Self::FrmDecline + | Self::HardDecline + | Self::SoftDecline => false, } } } diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index 00a661527a1..1bccb5134bb 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -49,7 +49,7 @@ use crate::{ }; type RecoveryResult<T> = error_stack::Result<T, errors::RecoveryError>; - +pub const REVENUE_RECOVERY: &str = "revenue_recovery"; /// The status of Passive Churn Payments #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub enum RevenueRecoveryPaymentsAttemptStatus { @@ -559,7 +559,7 @@ impl Action { revenue_recovery_payment_data, ) .await; - let db = &*state.store; + match response { Ok(_payment_data) => match payment_attempt.status.foreign_into() { RevenueRecoveryPaymentsAttemptStatus::Succeeded => { @@ -757,7 +757,35 @@ impl Action { payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, ) -> RecoveryResult<Self> { + let db = &*state.store; let next_retry_count = pt.retry_count + 1; + let error_message = payment_attempt + .error + .as_ref() + .map(|details| details.message.clone()); + let error_code = payment_attempt + .error + .as_ref() + .map(|details| details.code.clone()); + let connector_name = payment_attempt + .connector + .clone() + .ok_or(errors::RecoveryError::ValueNotFound) + .attach_printable("unable to derive payment connector from payment attempt")?; + let gsm_record = helpers::get_gsm_record( + state, + error_code, + error_message, + connector_name, + REVENUE_RECOVERY.to_string(), + ) + .await; + let is_hard_decline = gsm_record + .and_then(|gsm_record| gsm_record.error_category) + .map(|gsm_error_category| { + gsm_error_category == common_enums::ErrorCategory::HardDecline + }) + .unwrap_or(false); let schedule_time = revenue_recovery_payment_data .get_schedule_time_based_on_retry_type( state, @@ -765,6 +793,7 @@ impl Action { next_retry_count, payment_attempt, payment_intent, + is_hard_decline, ) .await; @@ -775,7 +804,6 @@ impl Action { } } } - // TODO: Move these to impl based functions async fn record_back_to_billing_connector( state: &SessionState, diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 828986aeeee..4584bee1725 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -219,7 +219,8 @@ pub fn mk_app( server_app = server_app .service(routes::UserDeprecated::server(state.clone())) .service(routes::ProcessTrackerDeprecated::server(state.clone())) - .service(routes::ProcessTracker::server(state.clone())); + .service(routes::ProcessTracker::server(state.clone())) + .service(routes::Gsm::server(state.clone())); } } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f5e7eee7347..cf684a680e8 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2292,7 +2292,7 @@ impl ProfileNew { pub struct Gsm; -#[cfg(all(feature = "olap", feature = "v1"))] +#[cfg(all(feature = "v1", feature = "olap"))] impl Gsm { pub fn server(state: AppState) -> Scope { web::scope("/gsm") @@ -2304,6 +2304,17 @@ impl Gsm { } } +#[cfg(all(feature = "v2", feature = "olap"))] +impl Gsm { + pub fn server(state: AppState) -> Scope { + web::scope("/v2/gsm") + .app_data(web::Data::new(state)) + .service(web::resource("").route(web::post().to(gsm::create_gsm_rule))) + .service(web::resource("/get").route(web::post().to(gsm::get_gsm_rule))) + .service(web::resource("/update").route(web::post().to(gsm::update_gsm_rule))) + .service(web::resource("/delete").route(web::post().to(gsm::delete_gsm_rule))) + } +} pub struct Chat; #[cfg(feature = "olap")] diff --git a/crates/router/src/routes/gsm.rs b/crates/router/src/routes/gsm.rs index 77a0cb0a645..886b24bbdb9 100644 --- a/crates/router/src/routes/gsm.rs +++ b/crates/router/src/routes/gsm.rs @@ -7,7 +7,10 @@ use crate::{ core::{api_locking, gsm}, services::{api, authentication as auth}, }; - +#[cfg(feature = "v1")] +const ADMIN_API_AUTH: auth::AdminApiAuth = auth::AdminApiAuth; +#[cfg(feature = "v2")] +const ADMIN_API_AUTH: auth::V2AdminApiAuth = auth::V2AdminApiAuth; /// Gsm - Create /// /// To create a Gsm Rule @@ -40,7 +43,7 @@ pub async fn create_gsm_rule( &req, payload, |state, _, payload, _| gsm::create_gsm_rule(state, payload), - &auth::AdminApiAuth, + &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, )) .await @@ -77,7 +80,7 @@ pub async fn get_gsm_rule( &req, gsm_retrieve_req, |state, _, gsm_retrieve_req, _| gsm::retrieve_gsm_rule(state, gsm_retrieve_req), - &auth::AdminApiAuth, + &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, )) .await @@ -115,7 +118,7 @@ pub async fn update_gsm_rule( &req, payload, |state, _, payload, _| gsm::update_gsm_rule(state, payload), - &auth::AdminApiAuth, + &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, )) .await @@ -154,7 +157,7 @@ pub async fn delete_gsm_rule( &req, payload, |state, _, payload, _| gsm::delete_gsm_rule(state, payload), - &auth::AdminApiAuth, + &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rs index 4b0dd2f2bc8..1c1a076fd01 100644 --- a/crates/router/src/types/storage/revenue_recovery.rs +++ b/crates/router/src/types/storage/revenue_recovery.rs @@ -1,7 +1,7 @@ use std::fmt::Debug; use common_enums::enums; -use common_utils::{ext_traits::ValueExt, id_type}; +use common_utils::{date_time, ext_traits::ValueExt, id_type}; use external_services::grpc_client::{self as external_grpc_client, GrpcHeaders}; use hyperswitch_domain_models::{ business_profile, merchant_account, merchant_connector_account, merchant_key_store, @@ -38,6 +38,7 @@ impl RevenueRecoveryPaymentData { retry_count: i32, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, + is_hard_decline: bool, ) -> Option<time::PrimitiveDateTime> { match self.retry_algorithm { enums::RevenueRecoveryAlgorithmType::Monitoring => { @@ -53,13 +54,18 @@ impl RevenueRecoveryPaymentData { .await } enums::RevenueRecoveryAlgorithmType::Smart => { - revenue_recovery::get_schedule_time_for_smart_retry( - state, - payment_attempt, - payment_intent, - retry_count, - ) - .await + if is_hard_decline { + None + } else { + // TODO: Integrate the smart retry call to return back a schedule time + revenue_recovery::get_schedule_time_for_smart_retry( + state, + payment_attempt, + payment_intent, + retry_count, + ) + .await + } } } }
2025-08-08T12:35:12Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add support for hard-decline switch for revenue-recovery service. If we encounter a hard-decline we would not call the external service . This PR also adds support for gsm apis in v2 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? - hit this curl ``` curl curl --location 'http://localhost:8080/v2/gsm' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'Content-Type: application/json' \ --data '{ "connector": "authipay", "flow": "revenue_recovery", "sub_flow": "sub_flow", "code": "100", "message": "Insuffiecient Funds", "status": "Failure", "decision": "retry", "clear_pan_possible":false, "step_up_possible":false, "error_category": "hard_decline" }' ``` - Response ```{"connector":"authipay","flow":"revenue_recovery","sub_flow":"sub_flow","code":"100","message":"Insuffiecient Funds","status":"Failure","router_error":null,"decision":"retry","step_up_possible":false,"unified_code":null,"unified_message":null,"error_category":"hard_decline","clear_pan_possible":false,"feature":"retry","feature_data":{"retry":{"step_up_possible":false,"clear_pan_possible":false,"alternate_network_possible":false,"decision":"retry"}}}% ``` - Db entry would be present <img width="1017" height="385" alt="Screenshot 2025-08-21 at 5 45 52β€―PM" src="https://github.com/user-attachments/assets/7f9da820-f793-4e57-81dd-cd34608979e9" /> ## 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.116.0
a819b4639b1e4279b117f4693cb0716b08e5e2e9
a819b4639b1e4279b117f4693cb0716b08e5e2e9
juspay/hyperswitch
juspay__hyperswitch-9003
Bug: [BUG] Error message not getting populated in Stripe Incremental Authorization Flow ### Bug Description Error message not getting populated in Stripe Incremental Authorization Flow ### Expected Behavior Error message should be populated in Stripe Incremental Authorization Flow ### Actual Behavior Error message not getting populated in Stripe Incremental Authorization Flow ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/stripe.rs b/crates/hyperswitch_connectors/src/connectors/stripe.rs index fc27effefca..b7810310369 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripe.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe.rs @@ -1086,7 +1086,7 @@ impl MinorUnit::new(req.request.total_amount), req.request.currency, )?; - let connector_req = stripe::StripeIncrementalAuthRequest { amount }; + let connector_req = stripe::StripeIncrementalAuthRequest { amount }; // Incremental authorization can be done a maximum of 10 times in Stripe Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } @@ -1162,7 +1162,8 @@ impl .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error - .code + .message + .clone() .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs index a32f89ef4d3..862fcd8ff18 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -101,7 +101,7 @@ impl<F: Send + Clone + Sync> // Incremental authorization should be performed on an amount greater than the original authorized amount (in this case, greater than the net_amount which is sent for authorization) // request.amount is the total amount that should be authorized in incremental authorization which should be greater than the original authorized amount - if payment_attempt.get_total_amount() > request.amount { + if payment_attempt.get_total_amount() >= request.amount { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Amount should be greater than original authorized amount".to_owned(), })?
2025-08-20T13:37:11Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes these issues - [Issue 1](https://github.com/juspay/hyperswitch/issues/9003) [Issue 2](https://github.com/juspay/hyperswitch/issues/9004) ## Description <!-- Describe your changes in detail --> Populated Error Message in Incremental Authorization Flow. Added check for same amount in incremental authorization requests. ### 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 1. Payments - Create Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_jVOnDLj6Q2nOHSSL8NIMQUws6P8WIRE9QNZ6toLt4gB7DqXuObIkVwPiXLJsY16n' \ --data-raw '{ "amount": 6500, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6500, "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "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": "2025-07-25T11:46:12Z" }, "request_incremental_authorization": true }' ``` Response: ``` { "payment_id": "pay_fXzLwsUeDagw7Cdyp8Sh", "merchant_id": "merchant_1755689870", "status": "requires_capture", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 6500, "amount_received": 0, "connector": "stripe", "client_secret": "pay_fXzLwsUeDagw7Cdyp8Sh_secret_Uoa82RaRfj6xcV3MnUtO", "created": "2025-08-20T12:16:31.560Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": 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": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1755692191, "expires": 1755695791, "secret": "epk_c558a24e699a4b9db808d953a8df38f5" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RyAwOE9cSvqiivY17rwXSCJ", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3RyAwOE9cSvqiivY17rwXSCJ", "payment_link": null, "profile_id": "pro_PMx2Y9TaHmSY8wUiC8kP", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_7VMxMHsmscuHwnVdYZPE", "incremental_authorization_allowed": true, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-20T12:31:31.560Z", "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_channel": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-08-20T12:16:32.579Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` 2. Payments - Incremental Authorization (with same amount) Request: ``` curl --location 'http://localhost:8080/payments/pay_fXzLwsUeDagw7Cdyp8Sh/incremental_authorization' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_jVOnDLj6Q2nOHSSL8NIMQUws6P8WIRE9QNZ6toLt4gB7DqXuObIkVwPiXLJsY16n' \ --data '{ "amount": 6500 }' ``` Response: ``` { "error": { "type": "invalid_request", "message": "Amount should be greater than original authorized amount", "code": "IR_16" } } ``` 3. Payments - Incremental Authorization (exceeding the maximum amount of time the flow can be called in Stripe) Request: ``` curl --location 'http://localhost:8080/payments/pay_gIQKmooikg2npSvaM9xZ/incremental_authorization' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_jVOnDLj6Q2nOHSSL8NIMQUws6P8WIRE9QNZ6toLt4gB7DqXuObIkVwPiXLJsY16n' \ --data '{ "amount": 6511 }' ``` Response: ``` { "payment_id": "pay_gIQKmooikg2npSvaM9xZ", "merchant_id": "merchant_1755689870", "status": "requires_capture", "amount": 6510, "net_amount": 6510, "shipping_cost": null, "amount_capturable": 6510, "amount_received": null, "connector": "stripe", "client_secret": "pay_gIQKmooikg2npSvaM9xZ_secret_cmcrBTpMQL6Prbvudezo", "created": "2025-08-20T13:28:31.692Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": 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": "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": "pi_3RyC44E9cSvqiivY14N3VxbQ", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pi_3RyC44E9cSvqiivY14N3VxbQ", "payment_link": null, "profile_id": "pro_PMx2Y9TaHmSY8wUiC8kP", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_7VMxMHsmscuHwnVdYZPE", "incremental_authorization_allowed": true, "authorization_count": 11, "incremental_authorizations": [ { "authorization_id": "auth_RI9tMBRwaju7LpkDhNrT_1", "amount": 6501, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6500 }, { "authorization_id": "auth_BoyLq9eHomflrMn5f2kD_2", "amount": 6502, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6501 }, { "authorization_id": "auth_LZZQWDEHw57lbLcqqKv2_3", "amount": 6503, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6502 }, { "authorization_id": "auth_RQeNDy0sdQnaLEW7f4Rm_4", "amount": 6504, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6503 }, { "authorization_id": "auth_2MRj0ANmGIW6BvFARHAe_5", "amount": 6505, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6504 }, { "authorization_id": "auth_egVuyLWfl6jGIZKdgLrt_6", "amount": 6506, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6505 }, { "authorization_id": "auth_M33NayFU2GQicIGYMMkU_7", "amount": 6507, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6506 }, { "authorization_id": "auth_UHtSahoOk1wVd8yacnJx_8", "amount": 6508, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6507 }, { "authorization_id": "auth_IejW3q4wdP5LcRouVvGs_9", "amount": 6509, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6508 }, { "authorization_id": "auth_sZNDStbUEPdqMMEZMlOV_10", "amount": 6510, "status": "success", "error_code": null, "error_message": null, "previously_authorized_amount": 6509 }, { "authorization_id": "auth_33dxNtWv6DiOdu3kGC4l_11", "amount": 6511, "status": "failure", "error_code": "No error code", "error_message": "The PaymentIntent has reached the maximum number of 10 allowed increments and cannot be incremented further.", "previously_authorized_amount": 6510 } ], "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-20T13:43:31.691Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-20T13:29:27.355Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": 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.116.0
e1fc14135cc3527cfb5afeccd4934bad8386c7b1
e1fc14135cc3527cfb5afeccd4934bad8386c7b1
juspay/hyperswitch
juspay__hyperswitch-8998
Bug: [FEATURE] feat(router): verify service for applepay merchant registration v2 ### Feature Description verify service for applepay merchant registration in v2 ### Possible Implementation Add POST /v2/verify/apple-pay/{merchant_id} endpoint for verify domains with Apple ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rs index 3c1b95dd982..f7ed33be642 100644 --- a/crates/router/src/core/verification.rs +++ b/crates/router/src/core/verification.rs @@ -117,11 +117,16 @@ pub async fn get_verified_apple_domains_with_mid_mca_id( .unwrap_or_default(); #[cfg(feature = "v2")] - let verified_domains = { - let _ = merchant_connector_id; - let _ = key_store; - todo!() - }; + let verified_domains = db + .find_merchant_connector_account_by_id( + key_manager_state, + &merchant_connector_id, + &key_store, + ) + .await + .change_context(errors::ApiErrorResponse::ResourceIdNotFound)? + .applepay_verified_domains + .unwrap_or_default(); Ok(services::api::ApplicationResponse::Json( verifications::ApplepayVerifiedDomainsResponse { verified_domains }, diff --git a/crates/router/src/core/verification/utils.rs b/crates/router/src/core/verification/utils.rs index 81b916206af..fb38d0a619a 100644 --- a/crates/router/src/core/verification/utils.rs +++ b/crates/router/src/core/verification/utils.rs @@ -43,12 +43,15 @@ pub async fn check_existence_and_add_domain_to_db( .change_context(errors::ApiErrorResponse::InternalServerError)?; #[cfg(feature = "v2")] - let merchant_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount = { - let _ = merchant_connector_id; - let _ = key_store; - let _ = domain_from_req; - todo!() - }; + let merchant_connector_account = state + .store + .find_merchant_connector_account_by_id( + key_manager_state, + &merchant_connector_id, + &key_store, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; utils::validate_profile_id_from_auth_layer( profile_id_from_auth_layer, &merchant_connector_account, diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 828986aeeee..48e9845c06b 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -198,6 +198,11 @@ pub fn mk_app( .service(routes::Routing::server(state.clone())) .service(routes::Chat::server(state.clone())); + #[cfg(all(feature = "olap", any(feature = "v1", feature = "v2")))] + { + server_app = server_app.service(routes::Verify::server(state.clone())); + } + #[cfg(feature = "v1")] { server_app = server_app @@ -208,7 +213,6 @@ pub fn mk_app( .service(routes::ApplePayCertificatesMigration::server(state.clone())) .service(routes::PaymentLink::server(state.clone())) .service(routes::ConnectorOnboarding::server(state.clone())) - .service(routes::Verify::server(state.clone())) .service(routes::Analytics::server(state.clone())) .service(routes::WebhookEvents::server(state.clone())) .service(routes::FeatureMatrix::server(state.clone())); diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 01455e9e17b..5b0471537c8 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -56,7 +56,7 @@ use super::refunds; use super::routing; #[cfg(all(feature = "oltp", feature = "v2"))] use super::tokenization as tokenization_routes; -#[cfg(all(feature = "olap", feature = "v1"))] +#[cfg(all(feature = "olap", any(feature = "v1", feature = "v2")))] use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains}; #[cfg(feature = "oltp")] use super::webhooks::*; @@ -2325,7 +2325,6 @@ impl ThreeDsDecisionRule { #[cfg(feature = "olap")] pub struct Verify; - #[cfg(all(feature = "olap", feature = "v1"))] impl Verify { pub fn server(state: AppState) -> Scope { @@ -2342,6 +2341,22 @@ impl Verify { } } +#[cfg(all(feature = "olap", feature = "v2"))] +impl Verify { + pub fn server(state: AppState) -> Scope { + web::scope("/v2/verify") + .app_data(web::Data::new(state)) + .service( + web::resource("/apple-pay/{merchant_id}") + .route(web::post().to(apple_pay_merchant_registration)), + ) + .service( + web::resource("/applepay-verified-domains") + .route(web::get().to(retrieve_apple_pay_verified_domains)), + ) + } +} + pub struct UserDeprecated; #[cfg(all(feature = "olap", feature = "v2"))] diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rs index ed987fb76ad..71b3c12dd75 100644 --- a/crates/router/src/routes/verification.rs +++ b/crates/router/src/routes/verification.rs @@ -46,6 +46,44 @@ pub async fn apple_pay_merchant_registration( .await } +#[cfg(all(feature = "olap", feature = "v2"))] +#[instrument(skip_all, fields(flow = ?Flow::Verification))] +pub async fn apple_pay_merchant_registration( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<verifications::ApplepayMerchantVerificationRequest>, + path: web::Path<common_utils::id_type::MerchantId>, +) -> impl Responder { + let flow = Flow::Verification; + let merchant_id = path.into_inner(); + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: auth::AuthenticationData, body, _| { + verification::verify_merchant_creds_for_applepay( + state.clone(), + body, + merchant_id.clone(), + Some(auth.profile.get_id().clone()), + ) + }, + auth::auth_type( + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + &auth::JWTAuth { + permission: Permission::ProfileAccountWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[instrument(skip_all, fields(flow = ?Flow::Verification))] pub async fn retrieve_apple_pay_verified_domains( state: web::Data<AppState>,
2025-08-20T09:01:30Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add Apple Pay merchant registration and verified domains retrieval for v2 ### Additional Changes - [X] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Request: ``` curl --location 'http://localhost:8080/v2/verify/apple-pay/cloth_seller_4hdx8pW2mxW0V6TZEQfm' \ --header 'x-client-secret: cs_0198af34cbcd72d0becd4db96e800bd9' \ --header 'x-profile-id: pro_833jt2bQKinLLA4pucBK' \ --header 'Authorization: api-key=dev_WH5clkiXgFqCpCDr62FCsFnjcRDZzIdwbvuuLK3sjC0nR3g6YWUYWVkOOzlfhxpd' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_WH5clkiXgFqCpCDr62FCsFnjcRDZzIdwbvuuLK3sjC0nR3g6YWUYWVkOOzlfhxpd' \ --data '{ "domain_names": ["hyperswitch-demo-store.netlify.app","sdk-test-app.netlify.app"], "merchant_connector_account_id": "mca_zYpPX5yTd3vo5NeMn26P" }' ``` Response: ``` { "status_message": "Applepay verification Completed" } ``` Request: ``` curl --location 'http://localhost:8080/v2/verify/applepay-verified-domains?merchant_id=cloth_seller_4hdx8pW2mxW0V6TZEQfm&merchant_connector_account_id=mca_zYpPX5yTd3vo5NeMn26P' \ --header 'x-profile-id: pro_833jt2bQKinLLA4pucBK' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'api-key: dev_WH5clkiXgFqCpCDr62FCsFnjcRDZzIdwbvuuLK3sjC0nR3g6YWUYWVkOOzlfhxpd' \ --data '' ``` Response: ``` { "verified_domains": [ "hyperswitch-demo-store.netlify.app", "sdk-test-app.netlify.app" ] } ``` <img width="1329" height="886" alt="image" src="https://github.com/user-attachments/assets/6077be64-5e4e-42a5-854e-f2872aa4e8a4" /> <img width="1338" height="904" alt="image" src="https://github.com/user-attachments/assets/08ef59d1-7ed2-4ad1-850f-12ce5118e67e" /> closes #8998 ## 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.116.0
c09c936643170c595303293601d41c4207e12068
c09c936643170c595303293601d41c4207e12068
juspay/hyperswitch
juspay__hyperswitch-8977
Bug: [FEATURE] add payment method filter in v2 ### Feature Description List all the available currencies and countries for the given connector and payment method type. ### Possible Implementation Add the filter route to the V2 PaymentMethods implementation. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 01455e9e17b..be17d98ff47 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1344,38 +1344,52 @@ impl Payouts { } } -#[cfg(all(feature = "oltp", feature = "v2"))] +#[cfg(all(feature = "v2", any(feature = "olap", feature = "oltp")))] impl PaymentMethods { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/v2/payment-methods").app_data(web::Data::new(state)); - route = route - .service( - web::resource("").route(web::post().to(payment_methods::create_payment_method_api)), - ) - .service( - web::resource("/create-intent") - .route(web::post().to(payment_methods::create_payment_method_intent_api)), - ); - route = route.service( - web::scope("/{id}") + #[cfg(feature = "olap")] + { + route = + route.service(web::resource("/filter").route( + web::get().to( + payment_methods::list_countries_currencies_for_connector_payment_method, + ), + )); + } + #[cfg(feature = "oltp")] + { + route = route .service( web::resource("") - .route(web::get().to(payment_methods::payment_method_retrieve_api)) - .route(web::delete().to(payment_methods::payment_method_delete_api)), - ) - .service(web::resource("/list-enabled-payment-methods").route( - web::get().to(payment_methods::payment_method_session_list_payment_methods), - )) - .service( - web::resource("/update-saved-payment-method") - .route(web::put().to(payment_methods::payment_method_update_api)), + .route(web::post().to(payment_methods::create_payment_method_api)), ) .service( - web::resource("/get-token") - .route(web::get().to(payment_methods::get_payment_method_token_data)), - ), - ); + web::resource("/create-intent") + .route(web::post().to(payment_methods::create_payment_method_intent_api)), + ); + + route = route.service( + web::scope("/{id}") + .service( + web::resource("") + .route(web::get().to(payment_methods::payment_method_retrieve_api)) + .route(web::delete().to(payment_methods::payment_method_delete_api)), + ) + .service(web::resource("/list-enabled-payment-methods").route( + web::get().to(payment_methods::payment_method_session_list_payment_methods), + )) + .service( + web::resource("/update-saved-payment-method") + .route(web::put().to(payment_methods::payment_method_update_api)), + ) + .service( + web::resource("/get-token") + .route(web::get().to(payment_methods::get_payment_method_token_data)), + ), + ); + } route } diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 367ece308c3..08b84e40977 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -913,6 +913,47 @@ pub async fn list_countries_currencies_for_connector_payment_method( .await } +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::ListCountriesCurrencies))] +pub async fn list_countries_currencies_for_connector_payment_method( + state: web::Data<AppState>, + req: HttpRequest, + query_payload: web::Query<payment_methods::ListCountriesCurrenciesRequest>, +) -> HttpResponse { + let flow = Flow::ListCountriesCurrencies; + let payload = query_payload.into_inner(); + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: auth::AuthenticationData, req, _| { + cards::list_countries_currencies_for_connector_payment_method( + state, + req, + Some(auth.profile.get_id().clone()), + ) + }, + #[cfg(not(feature = "release"))] + auth::auth_type( + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + &auth::JWTAuth { + permission: Permission::ProfileConnectorRead, + }, + req.headers(), + ), + #[cfg(feature = "release")] + &auth::JWTAuth { + permission: Permission::ProfileConnectorRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::DefaultPaymentMethodsSet))] pub async fn default_payment_method_set_api(
2025-08-18T10:55:59Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add the payment method filter route to the V2 PaymentMethods implementation which list all available countries and currencies based on connector and payment method type. ### Additional Changes - [X] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Request: ``` curl --location 'http://localhost:8080/v2/payment-methods/filter?connector=stripe&paymentMethodType=debit' \ --header 'Authorization: api-key=dev_4DIYNBJfJIQ2Tr1wLavfp48BJvXLtHmBWdkkALwWj6U91DAjP7h2RfQmhnDMATmB' \ --header 'x-profile-id: pro_9dDVfbJRfEb7o7qxBatP' \ --header 'api-key: dev_4DIYNBJfJIQ2Tr1wLavfp48BJvXLtHmBWdkkALwWj6U91DAjP7h2RfQmhnDMATmB' \ --data '' ``` Response: ``` { "currencies": [ "QAR", "BMD", "ERN", "ETB", "ILS", "MOP", "STN", "TND", "SRD", "TOP", "JMD", "BHD", "SSP", "BRL", "COP", "KMF", "PEN", "SLE", "TZS", "KZT", "CUP", "MDL", "XCD", "BGN", "NIO", "BTN", "MXN", "FKP", "CLF", "OMR", "GHS", "DZD", "BSD", "SEK", "VND", "ZAR", "VES", "DOP", "RON", "BND", "PGK", "SVC", "HTG", "KWD", "TMT", "SBD", "AED", "HKD", "CRC", "DKK", "TTD", "TWD", "UGX", "SLL", "FJD", "ZWL", "ANG", "JPY", "CNY", "DJF", "PLN", "BBD", "WST", "PHP", "PKR", "MVR", "LSL", "HRK", "UZS", "NAD", "KRW", "RUB", "TJS", "TRY", "BWP", "KHR", "BZD", "YER", "CDF", "NOK", "IDR", "MAD", "MMK", "MZN", "BAM", "JOD", "XOF", "NZD", "KES", "BIF", "MUR", "IRR", "UAH", "XPF", "THB", "AWG", "GBP", "GMD", "INR", "MYR", "PAB", "BDT", "HNL", "PYG", "CZK", "GEL", "ISK", "GTQ", "CAD", "KPW", "MWK", "NGN", "SYP", "LAK", "RWF", "KGS", "MKD", "MNT", "HUF", "LYD", "SCR", "XAF", "AOA", "NPR", "CLP", "MRU", "SDG", "STD", "ARS", "SAR", "AUD", "SZL", "VUV", "CVE", "ALL", "RSD", "AFN", "ZMW", "AMD", "MGA", "LRD", "BOB", "AZN", "CUC", "KYD", "BYN", "USD", "EUR", "SGD", "SHP", "SOS", "GYD", "GIP", "GNF", "EGP", "CHF", "LBP", "UYU", "LKR", "IQD" ], "countries": [ { "code": "GU", "name": "Guam" }, { "code": "AW", "name": "Aruba" }, { "code": "HR", "name": "Croatia" }, { "code": "TD", "name": "Chad" }, { "code": "TM", "name": "Turkmenistan" }, { "code": "GB", "name": "UnitedKingdomOfGreatBritainAndNorthernIreland" }, { "code": "CL", "name": "Chile" }, { "code": "LK", "name": "SriLanka" }, { "code": "SI", "name": "Slovenia" }, { "code": "PA", "name": "Panama" }, { "code": "NE", "name": "Niger" }, { "code": "AZ", "name": "Azerbaijan" }, { "code": "MQ", "name": "Martinique" }, { "code": "BY", "name": "Belarus" }, { "code": "FJ", "name": "Fiji" }, { "code": "PY", "name": "Paraguay" }, { "code": "HK", "name": "HongKong" }, { "code": "UZ", "name": "Uzbekistan" }, { "code": "DE", "name": "Germany" }, { "code": "CX", "name": "ChristmasIsland" }, { "code": "BB", "name": "Barbados" }, { "code": "DJ", "name": "Djibouti" }, { "code": "GP", "name": "Guadeloupe" }, { "code": "CR", "name": "CostaRica" }, { "code": "ZM", "name": "Zambia" }, { "code": "ST", "name": "SaoTomeAndPrincipe" }, { "code": "BA", "name": "BosniaAndHerzegovina" }, { "code": "NI", "name": "Nicaragua" }, { "code": "SO", "name": "Somalia" }, { "code": "PR", "name": "PuertoRico" }, { "code": "SC", "name": "Seychelles" }, { "code": "KR", "name": "KoreaRepublic" }, { "code": "FM", "name": "MicronesiaFederatedStates" }, { "code": "DO", "name": "DominicanRepublic" }, { "code": "MO", "name": "Macao" }, { "code": "JP", "name": "Japan" }, { "code": "MH", "name": "MarshallIslands" }, { "code": "AQ", "name": "Antarctica" }, { "code": "CD", "name": "CongoDemocraticRepublic" }, { "code": "NA", "name": "Namibia" }, { "code": "TV", "name": "Tuvalu" }, { "code": "EE", "name": "Estonia" }, { "code": "ML", "name": "Mali" }, { "code": "IS", "name": "Iceland" }, { "code": "SR", "name": "Suriname" }, { "code": "UM", "name": "UnitedStatesMinorOutlyingIslands" }, { "code": "SB", "name": "SolomonIslands" }, { "code": "RO", "name": "Romania" }, { "code": "CI", "name": "CotedIvoire" }, { "code": "MD", "name": "MoldovaRepublic" }, { "code": "GS", "name": "SouthGeorgiaAndTheSouthSandwichIslands" }, { "code": "PF", "name": "FrenchPolynesia" }, { "code": "GE", "name": "Georgia" }, { "code": "JE", "name": "Jersey" }, { "code": "SK", "name": "Slovakia" }, { "code": "ID", "name": "Indonesia" }, { "code": "NR", "name": "Nauru" }, { "code": "CO", "name": "Colombia" }, { "code": "GR", "name": "Greece" }, { "code": "KW", "name": "Kuwait" }, { "code": "TH", "name": "Thailand" }, { "code": "KI", "name": "Kiribati" }, { "code": "BN", "name": "BruneiDarussalam" }, { "code": "WS", "name": "Samoa" }, { "code": "AI", "name": "Anguilla" }, { "code": "TC", "name": "TurksAndCaicosIslands" }, { "code": "BG", "name": "Bulgaria" }, { "code": "RS", "name": "Serbia" }, { "code": "BW", "name": "Botswana" }, { "code": "KM", "name": "Comoros" }, { "code": "SN", "name": "Senegal" }, { "code": "TR", "name": "Turkey" }, { "code": "SL", "name": "SierraLeone" }, { "code": "MC", "name": "Monaco" }, { "code": "BL", "name": "SaintBarthelemy" }, { "code": "GL", "name": "Greenland" }, { "code": "KG", "name": "Kyrgyzstan" }, { "code": "MT", "name": "Malta" }, { "code": "VA", "name": "HolySee" }, { "code": "AS", "name": "AmericanSamoa" }, { "code": "TJ", "name": "Tajikistan" }, { "code": "TN", "name": "Tunisia" }, { "code": "IT", "name": "Italy" }, { "code": "CV", "name": "CaboVerde" }, { "code": "IN", "name": "India" }, { "code": "ME", "name": "Montenegro" }, { "code": "LR", "name": "Liberia" }, { "code": "AE", "name": "UnitedArabEmirates" }, { "code": "TK", "name": "Tokelau" }, { "code": "IQ", "name": "Iraq" }, { "code": "FO", "name": "FaroeIslands" }, { "code": "MW", "name": "Malawi" }, { "code": "SY", "name": "SyrianArabRepublic" }, { "code": "CA", "name": "Canada" }, { "code": "GF", "name": "FrenchGuiana" }, { "code": "ER", "name": "Eritrea" }, { "code": "MY", "name": "Malaysia" }, { "code": "VG", "name": "VirginIslandsBritish" }, { "code": "RE", "name": "Reunion" }, { "code": "JM", "name": "Jamaica" }, { "code": "AF", "name": "Afghanistan" }, { "code": "MN", "name": "Mongolia" }, { "code": "CW", "name": "Curacao" }, { "code": "IE", "name": "Ireland" }, { "code": "CG", "name": "Congo" }, { "code": "NG", "name": "Nigeria" }, { "code": "VC", "name": "SaintVincentAndTheGrenadines" }, { "code": "TO", "name": "Tonga" }, { "code": "LU", "name": "Luxembourg" }, { "code": "TL", "name": "TimorLeste" }, { "code": "MF", "name": "SaintMartinFrenchpart" }, { "code": "AT", "name": "Austria" }, { "code": "ET", "name": "Ethiopia" }, { "code": "SX", "name": "SintMaartenDutchpart" }, { "code": "GT", "name": "Guatemala" }, { "code": "TF", "name": "FrenchSouthernTerritories" }, { "code": "KP", "name": "KoreaDemocraticPeoplesRepublic" }, { "code": "LC", "name": "SaintLucia" }, { "code": "BT", "name": "Bhutan" }, { "code": "SM", "name": "SanMarino" }, { "code": "QA", "name": "Qatar" }, { "code": "DM", "name": "Dominica" }, { "code": "BJ", "name": "Benin" }, { "code": "GA", "name": "Gabon" }, { "code": "YT", "name": "Mayotte" }, { "code": "KZ", "name": "Kazakhstan" }, { "code": "LV", "name": "Latvia" }, { "code": "GG", "name": "Guernsey" }, { "code": "CH", "name": "Switzerland" }, { "code": "HM", "name": "HeardIslandAndMcDonaldIslands" }, { "code": "AG", "name": "AntiguaAndBarbuda" }, { "code": "WF", "name": "WallisAndFutuna" }, { "code": "CC", "name": "CocosKeelingIslands" }, { "code": "ZW", "name": "Zimbabwe" }, { "code": "IL", "name": "Israel" }, { "code": "TG", "name": "Togo" }, { "code": "MG", "name": "Madagascar" }, { "code": "NP", "name": "Nepal" }, { "code": "GW", "name": "GuineaBissau" }, { "code": "PW", "name": "Palau" }, { "code": "LY", "name": "Libya" }, { "code": "FI", "name": "Finland" }, { "code": "AR", "name": "Argentina" }, { "code": "TT", "name": "TrinidadAndTobago" }, { "code": "FR", "name": "France" }, { "code": "MS", "name": "Montserrat" }, { "code": "IO", "name": "BritishIndianOceanTerritory" }, { "code": "TW", "name": "TaiwanProvinceOfChina" }, { "code": "EC", "name": "Ecuador" }, { "code": "NO", "name": "Norway" }, { "code": "MZ", "name": "Mozambique" }, { "code": "GH", "name": "Ghana" }, { "code": "HU", "name": "Hungary" }, { "code": "CU", "name": "Cuba" }, { "code": "LI", "name": "Liechtenstein" }, { "code": "MU", "name": "Mauritius" }, { "code": "EG", "name": "Egypt" }, { "code": "MX", "name": "Mexico" }, { "code": "MV", "name": "Maldives" }, { "code": "BE", "name": "Belgium" }, { "code": "VN", "name": "Vietnam" }, { "code": "NU", "name": "Niue" }, { "code": "CY", "name": "Cyprus" }, { "code": "GQ", "name": "EquatorialGuinea" }, { "code": "SD", "name": "Sudan" }, { "code": "LT", "name": "Lithuania" }, { "code": "BD", "name": "Bangladesh" }, { "code": "NL", "name": "Netherlands" }, { "code": "BH", "name": "Bahrain" }, { "code": "AX", "name": "AlandIslands" }, { "code": "BR", "name": "Brazil" }, { "code": "AM", "name": "Armenia" }, { "code": "UY", "name": "Uruguay" }, { "code": "MP", "name": "NorthernMarianaIslands" }, { "code": "NZ", "name": "NewZealand" }, { "code": "GY", "name": "Guyana" }, { "code": "CZ", "name": "Czechia" }, { "code": "AU", "name": "Australia" }, { "code": "SH", "name": "SaintHelenaAscensionAndTristandaCunha" }, { "code": "HT", "name": "Haiti" }, { "code": "SA", "name": "SaudiArabia" }, { "code": "CM", "name": "Cameroon" }, { "code": "JO", "name": "Jordan" }, { "code": "UA", "name": "Ukraine" }, { "code": "BV", "name": "BouvetIsland" }, { "code": "GI", "name": "Gibraltar" }, { "code": "GD", "name": "Grenada" }, { "code": "UG", "name": "Uganda" }, { "code": "TZ", "name": "TanzaniaUnitedRepublic" }, { "code": "DZ", "name": "Algeria" }, { "code": "PM", "name": "SaintPierreAndMiquelon" }, { "code": "ZA", "name": "SouthAfrica" }, { "code": "OM", "name": "Oman" }, { "code": "KY", "name": "CaymanIslands" }, { "code": "LS", "name": "Lesotho" }, { "code": "ES", "name": "Spain" }, { "code": "MM", "name": "Myanmar" }, { "code": "AO", "name": "Angola" }, { "code": "EH", "name": "WesternSahara" }, { "code": "IR", "name": "IranIslamicRepublic" }, { "code": "HN", "name": "Honduras" }, { "code": "KH", "name": "Cambodia" }, { "code": "KE", "name": "Kenya" }, { "code": "MK", "name": "MacedoniaTheFormerYugoslavRepublic" }, { "code": "AL", "name": "Albania" }, { "code": "US", "name": "UnitedStatesOfAmerica" }, { "code": "YE", "name": "Yemen" }, { "code": "DK", "name": "Denmark" }, { "code": "MR", "name": "Mauritania" }, { "code": "SG", "name": "Singapore" }, { "code": "CN", "name": "China" }, { "code": "IM", "name": "IsleOfMan" }, { "code": "PH", "name": "Philippines" }, { "code": "SZ", "name": "Swaziland" }, { "code": "BO", "name": "BoliviaPlurinationalState" }, { "code": "CF", "name": "CentralAfricanRepublic" }, { "code": "PE", "name": "Peru" }, { "code": "BQ", "name": "BonaireSintEustatiusAndSaba" }, { "code": "SV", "name": "ElSalvador" }, { "code": "NC", "name": "NewCaledonia" }, { "code": "VU", "name": "Vanuatu" }, { "code": "MA", "name": "Morocco" }, { "code": "SS", "name": "SouthSudan" }, { "code": "BZ", "name": "Belize" }, { "code": "PS", "name": "PalestineState" }, { "code": "CK", "name": "CookIslands" }, { "code": "BF", "name": "BurkinaFaso" }, { "code": "FK", "name": "FalklandIslandsMalvinas" }, { "code": "SJ", "name": "SvalbardAndJanMayen" }, { "code": "VE", "name": "VenezuelaBolivarianRepublic" }, { "code": "BI", "name": "Burundi" }, { "code": "PT", "name": "Portugal" }, { "code": "VI", "name": "VirginIslandsUS" }, { "code": "PG", "name": "PapuaNewGuinea" }, { "code": "RU", "name": "RussianFederation" }, { "code": "AD", "name": "Andorra" }, { "code": "NF", "name": "NorfolkIsland" }, { "code": "LB", "name": "Lebanon" }, { "code": "GM", "name": "Gambia" }, { "code": "BM", "name": "Bermuda" }, { "code": "BS", "name": "Bahamas" }, { "code": "KN", "name": "SaintKittsAndNevis" }, { "code": "PN", "name": "Pitcairn" }, { "code": "PL", "name": "Poland" }, { "code": "SE", "name": "Sweden" }, { "code": "RW", "name": "Rwanda" }, { "code": "PK", "name": "Pakistan" }, { "code": "GN", "name": "Guinea" }, { "code": "LA", "name": "LaoPeoplesDemocraticRepublic" } ] } ``` Request with JWT Authentication: ``` curl --location 'http://localhost:8081/v2/payment-methods/filter?connector=stripe&paymentMethodType=debit' \ --header 'x-profile-id: pro_vJRG8ITXZXHXQuoHA59p' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNjIwY2E1NzAtY2I1Ni00YTUwLTk4MTctODEzYzEyNjljOWUwIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzU1NTkyMzYyIiwicm9sZV9pZCI6InByb2ZpbGVfdmlld19vbmx5IiwiZXhwIjoxNzU1NzY1NjI3LCJvcmdfaWQiOiJvcmdfelFiZUprcUlPWWhMUTNmeDVMOHQiLCJwcm9maWxlX2lkIjoicHJvX3ZKUkc4SVRYWlhIWFF1b0hBNTlwIiwidGVuYW50X2lkIjoicHVibGljIn0.9DafPc6vkoO8K-JLHxetMmmDYQDek35-HV8zrVe5QTg' \ --data '' ``` Respone: ``` { "currencies": [ "ERN", "LSL", "MMK", "LKR", "THB", "SHP", "FKP", "XCD", "NIO", "GIP", "RWF", "CUP", "OMR", "UYU", "GTQ", "GNF", "FJD", "GBP", "KMF", "ILS", "ETB", "SYP", "GHS", "GMD", "MUR", "BSD", "KRW", "MZN", "TMT", "TOP", "SBD", "KGS", "UGX", "UZS", "YER", "RUB", "TZS", "COP", "PYG", "NAD", "SSP", "GYD", "CHF", "KWD", "MYR", "PKR", "SAR", "WST", "EGP", "BAM", "QAR", "XOF", "DZD", "SZL", "CZK", "VND", "SCR", "IDR", "ANG", "LAK", "DJF", "TTD", "HUF", "PLN", "VES", "ALL", "MRU", "ZMW", "STN", "ZWL", "AFN", "NOK", "ISK", "AED", "EUR", "MVR", "CRC", "GEL", "TND", "XAF", "KHR", "IRR", "JOD", "CNY", "CVE", "AWG", "CUC", "NGN", "STD", "MXN", "LYD", "SRD", "BWP", "CDF", "KPW", "SEK", "PGK", "AMD", "NZD", "BOB", "CAD", "NPR", "PEN", "SDG", "MNT", "AZN", "MOP", "BDT", "CLF", "BMD", "BTN", "PAB", "USD", "BGN", "HNL", "DKK", "ZAR", "AOA", "TJS", "VUV", "BHD", "BZD", "TRY", "HKD", "ARS", "BND", "HTG", "LRD", "MGA", "SVC", "SLL", "KES", "HRK", "SLE", "RON", "MKD", "MDL", "UAH", "BIF", "KYD", "BBD", "BRL", "CLP", "SOS", "JPY", "RSD", "INR", "MWK", "AUD", "PHP", "IQD", "LBP", "MAD", "XPF", "JMD", "DOP", "TWD", "KZT", "SGD", "BYN" ], "countries": [ { "code": "VU", "name": "Vanuatu" }, { "code": "AI", "name": "Anguilla" }, { "code": "UA", "name": "Ukraine" }, { "code": "PW", "name": "Palau" }, { "code": "FR", "name": "France" }, { "code": "TO", "name": "Tonga" }, { "code": "JO", "name": "Jordan" }, { "code": "ZW", "name": "Zimbabwe" }, { "code": "KZ", "name": "Kazakhstan" }, { "code": "AW", "name": "Aruba" }, { "code": "GY", "name": "Guyana" }, { "code": "KE", "name": "Kenya" }, { "code": "LS", "name": "Lesotho" }, { "code": "NP", "name": "Nepal" }, { "code": "US", "name": "UnitedStatesOfAmerica" }, { "code": "ER", "name": "Eritrea" }, { "code": "LY", "name": "Libya" }, { "code": "GW", "name": "GuineaBissau" }, { "code": "GP", "name": "Guadeloupe" }, { "code": "NO", "name": "Norway" }, { "code": "TM", "name": "Turkmenistan" }, { "code": "BY", "name": "Belarus" }, { "code": "KH", "name": "Cambodia" }, { "code": "KW", "name": "Kuwait" }, { "code": "JM", "name": "Jamaica" }, { "code": "MQ", "name": "Martinique" }, { "code": "CY", "name": "Cyprus" }, { "code": "TH", "name": "Thailand" }, { "code": "CF", "name": "CentralAfricanRepublic" }, { "code": "PH", "name": "Philippines" }, { "code": "IO", "name": "BritishIndianOceanTerritory" }, { "code": "FK", "name": "FalklandIslandsMalvinas" }, { "code": "EH", "name": "WesternSahara" }, { "code": "TC", "name": "TurksAndCaicosIslands" }, { "code": "KN", "name": "SaintKittsAndNevis" }, { "code": "MW", "name": "Malawi" }, { "code": "UY", "name": "Uruguay" }, { "code": "SI", "name": "Slovenia" }, { "code": "HN", "name": "Honduras" }, { "code": "PT", "name": "Portugal" }, { "code": "RO", "name": "Romania" }, { "code": "BF", "name": "BurkinaFaso" }, { "code": "GH", "name": "Ghana" }, { "code": "KP", "name": "KoreaDemocraticPeoplesRepublic" }, { "code": "CC", "name": "CocosKeelingIslands" }, { "code": "BE", "name": "Belgium" }, { "code": "BT", "name": "Bhutan" }, { "code": "CG", "name": "Congo" }, { "code": "SX", "name": "SintMaartenDutchpart" }, { "code": "CL", "name": "Chile" }, { "code": "DM", "name": "Dominica" }, { "code": "TF", "name": "FrenchSouthernTerritories" }, { "code": "MZ", "name": "Mozambique" }, { "code": "PL", "name": "Poland" }, { "code": "YE", "name": "Yemen" }, { "code": "MX", "name": "Mexico" }, { "code": "AS", "name": "AmericanSamoa" }, { "code": "TG", "name": "Togo" }, { "code": "OM", "name": "Oman" }, { "code": "CH", "name": "Switzerland" }, { "code": "AD", "name": "Andorra" }, { "code": "WS", "name": "Samoa" }, { "code": "TN", "name": "Tunisia" }, { "code": "GG", "name": "Guernsey" }, { "code": "SD", "name": "Sudan" }, { "code": "CD", "name": "CongoDemocraticRepublic" }, { "code": "CM", "name": "Cameroon" }, { "code": "CU", "name": "Cuba" }, { "code": "SY", "name": "SyrianArabRepublic" }, { "code": "BM", "name": "Bermuda" }, { "code": "PR", "name": "PuertoRico" }, { "code": "PK", "name": "Pakistan" }, { "code": "BI", "name": "Burundi" }, { "code": "ET", "name": "Ethiopia" }, { "code": "BJ", "name": "Benin" }, { "code": "AQ", "name": "Antarctica" }, { "code": "CX", "name": "ChristmasIsland" }, { "code": "IE", "name": "Ireland" }, { "code": "VI", "name": "VirginIslandsUS" }, { "code": "PM", "name": "SaintPierreAndMiquelon" }, { "code": "GQ", "name": "EquatorialGuinea" }, { "code": "IM", "name": "IsleOfMan" }, { "code": "SA", "name": "SaudiArabia" }, { "code": "BZ", "name": "Belize" }, { "code": "CO", "name": "Colombia" }, { "code": "MT", "name": "Malta" }, { "code": "AU", "name": "Australia" }, { "code": "EE", "name": "Estonia" }, { "code": "NR", "name": "Nauru" }, { "code": "KR", "name": "KoreaRepublic" }, { "code": "AZ", "name": "Azerbaijan" }, { "code": "NG", "name": "Nigeria" }, { "code": "TW", "name": "TaiwanProvinceOfChina" }, { "code": "UZ", "name": "Uzbekistan" }, { "code": "IS", "name": "Iceland" }, { "code": "BQ", "name": "BonaireSintEustatiusAndSaba" }, { "code": "MG", "name": "Madagascar" }, { "code": "MC", "name": "Monaco" }, { "code": "LK", "name": "SriLanka" }, { "code": "NF", "name": "NorfolkIsland" }, { "code": "MM", "name": "Myanmar" }, { "code": "GS", "name": "SouthGeorgiaAndTheSouthSandwichIslands" }, { "code": "LI", "name": "Liechtenstein" }, { "code": "CZ", "name": "Czechia" }, { "code": "TK", "name": "Tokelau" }, { "code": "GI", "name": "Gibraltar" }, { "code": "PS", "name": "PalestineState" }, { "code": "SG", "name": "Singapore" }, { "code": "SM", "name": "SanMarino" }, { "code": "AG", "name": "AntiguaAndBarbuda" }, { "code": "ZA", "name": "SouthAfrica" }, { "code": "YT", "name": "Mayotte" }, { "code": "MP", "name": "NorthernMarianaIslands" }, { "code": "RW", "name": "Rwanda" }, { "code": "HK", "name": "HongKong" }, { "code": "HT", "name": "Haiti" }, { "code": "PA", "name": "Panama" }, { "code": "PN", "name": "Pitcairn" }, { "code": "LT", "name": "Lithuania" }, { "code": "VA", "name": "HolySee" }, { "code": "MF", "name": "SaintMartinFrenchpart" }, { "code": "LC", "name": "SaintLucia" }, { "code": "GE", "name": "Georgia" }, { "code": "BB", "name": "Barbados" }, { "code": "BD", "name": "Bangladesh" }, { "code": "VN", "name": "Vietnam" }, { "code": "AX", "name": "AlandIslands" }, { "code": "TJ", "name": "Tajikistan" }, { "code": "GU", "name": "Guam" }, { "code": "FJ", "name": "Fiji" }, { "code": "BS", "name": "Bahamas" }, { "code": "PG", "name": "PapuaNewGuinea" }, { "code": "IQ", "name": "Iraq" }, { "code": "UG", "name": "Uganda" }, { "code": "MN", "name": "Mongolia" }, { "code": "GM", "name": "Gambia" }, { "code": "UM", "name": "UnitedStatesMinorOutlyingIslands" }, { "code": "NZ", "name": "NewZealand" }, { "code": "JE", "name": "Jersey" }, { "code": "SC", "name": "Seychelles" }, { "code": "IT", "name": "Italy" }, { "code": "RE", "name": "Reunion" }, { "code": "GF", "name": "FrenchGuiana" }, { "code": "TD", "name": "Chad" }, { "code": "NC", "name": "NewCaledonia" }, { "code": "CV", "name": "CaboVerde" }, { "code": "SL", "name": "SierraLeone" }, { "code": "GT", "name": "Guatemala" }, { "code": "KY", "name": "CaymanIslands" }, { "code": "ID", "name": "Indonesia" }, { "code": "SR", "name": "Suriname" }, { "code": "WF", "name": "WallisAndFutuna" }, { "code": "LA", "name": "LaoPeoplesDemocraticRepublic" }, { "code": "TT", "name": "TrinidadAndTobago" }, { "code": "NA", "name": "Namibia" }, { "code": "ZM", "name": "Zambia" }, { "code": "SN", "name": "Senegal" }, { "code": "MA", "name": "Morocco" }, { "code": "NL", "name": "Netherlands" }, { "code": "NI", "name": "Nicaragua" }, { "code": "KG", "name": "Kyrgyzstan" }, { "code": "MY", "name": "Malaysia" }, { "code": "TR", "name": "Turkey" }, { "code": "NE", "name": "Niger" }, { "code": "MH", "name": "MarshallIslands" }, { "code": "LR", "name": "Liberia" }, { "code": "FI", "name": "Finland" }, { "code": "MD", "name": "MoldovaRepublic" }, { "code": "ME", "name": "Montenegro" }, { "code": "AL", "name": "Albania" }, { "code": "HM", "name": "HeardIslandAndMcDonaldIslands" }, { "code": "FM", "name": "MicronesiaFederatedStates" }, { "code": "CR", "name": "CostaRica" }, { "code": "CW", "name": "Curacao" }, { "code": "SO", "name": "Somalia" }, { "code": "MK", "name": "MacedoniaTheFormerYugoslavRepublic" }, { "code": "TZ", "name": "TanzaniaUnitedRepublic" }, { "code": "RS", "name": "Serbia" }, { "code": "KM", "name": "Comoros" }, { "code": "VG", "name": "VirginIslandsBritish" }, { "code": "AM", "name": "Armenia" }, { "code": "BH", "name": "Bahrain" }, { "code": "BL", "name": "SaintBarthelemy" }, { "code": "NU", "name": "Niue" }, { "code": "LU", "name": "Luxembourg" }, { "code": "MO", "name": "Macao" }, { "code": "BA", "name": "BosniaAndHerzegovina" }, { "code": "AF", "name": "Afghanistan" }, { "code": "EG", "name": "Egypt" }, { "code": "CK", "name": "CookIslands" }, { "code": "CA", "name": "Canada" }, { "code": "SZ", "name": "Swaziland" }, { "code": "ML", "name": "Mali" }, { "code": "BR", "name": "Brazil" }, { "code": "LV", "name": "Latvia" }, { "code": "TL", "name": "TimorLeste" }, { "code": "BG", "name": "Bulgaria" }, { "code": "AT", "name": "Austria" }, { "code": "KI", "name": "Kiribati" }, { "code": "IR", "name": "IranIslamicRepublic" }, { "code": "MV", "name": "Maldives" }, { "code": "RU", "name": "RussianFederation" }, { "code": "VE", "name": "VenezuelaBolivarianRepublic" }, { "code": "AE", "name": "UnitedArabEmirates" }, { "code": "VC", "name": "SaintVincentAndTheGrenadines" }, { "code": "MS", "name": "Montserrat" }, { "code": "AO", "name": "Angola" }, { "code": "PY", "name": "Paraguay" }, { "code": "BV", "name": "BouvetIsland" }, { "code": "DO", "name": "DominicanRepublic" }, { "code": "SH", "name": "SaintHelenaAscensionAndTristandaCunha" }, { "code": "ES", "name": "Spain" }, { "code": "AR", "name": "Argentina" }, { "code": "LB", "name": "Lebanon" }, { "code": "PF", "name": "FrenchPolynesia" }, { "code": "IL", "name": "Israel" }, { "code": "DJ", "name": "Djibouti" }, { "code": "DZ", "name": "Algeria" }, { "code": "TV", "name": "Tuvalu" }, { "code": "MU", "name": "Mauritius" }, { "code": "JP", "name": "Japan" }, { "code": "DK", "name": "Denmark" }, { "code": "SE", "name": "Sweden" }, { "code": "CN", "name": "China" }, { "code": "PE", "name": "Peru" }, { "code": "BW", "name": "Botswana" }, { "code": "SV", "name": "ElSalvador" }, { "code": "CI", "name": "CotedIvoire" }, { "code": "HR", "name": "Croatia" }, { "code": "SK", "name": "Slovakia" }, { "code": "GD", "name": "Grenada" }, { "code": "SS", "name": "SouthSudan" }, { "code": "BO", "name": "BoliviaPlurinationalState" }, { "code": "QA", "name": "Qatar" }, { "code": "HU", "name": "Hungary" }, { "code": "SB", "name": "SolomonIslands" }, { "code": "BN", "name": "BruneiDarussalam" }, { "code": "GB", "name": "UnitedKingdomOfGreatBritainAndNorthernIreland" }, { "code": "GL", "name": "Greenland" }, { "code": "ST", "name": "SaoTomeAndPrincipe" }, { "code": "GR", "name": "Greece" }, { "code": "FO", "name": "FaroeIslands" }, { "code": "SJ", "name": "SvalbardAndJanMayen" }, { "code": "IN", "name": "India" }, { "code": "EC", "name": "Ecuador" }, { "code": "MR", "name": "Mauritania" }, { "code": "GA", "name": "Gabon" }, { "code": "DE", "name": "Germany" }, { "code": "GN", "name": "Guinea" } ] } ``` Closes #8977 ## 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.116.0
f762f4f5854eeb7a78c78149075804ee4f07bb25
f762f4f5854eeb7a78c78149075804ee4f07bb25
juspay/hyperswitch
juspay__hyperswitch-9000
Bug: [REFACTOR] Adyen's balance platform webhooks Webhooks for balance platform are different for different payout methods - Banks - https://docs.adyen.com/payouts/payout-service/pay-out-to-bank-accounts/payout-webhooks/ Cards - https://docs.adyen.com/payouts/payout-service/pay-out-to-cards/payout-webhooks/
diff --git a/crates/hyperswitch_connectors/src/connectors/adyenplatform.rs b/crates/hyperswitch_connectors/src/connectors/adyenplatform.rs index 78c8c4c8067..2158fece4c9 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyenplatform.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyenplatform.rs @@ -402,6 +402,7 @@ impl IncomingWebhook for Adyenplatform { webhook_body.webhook_type, webhook_body.data.status, webhook_body.data.tracking, + webhook_body.data.category.as_ref(), )) } #[cfg(not(feature = "payouts"))] diff --git a/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs index 6c964aea20f..b04ca410d39 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs @@ -513,6 +513,7 @@ pub struct AdyenplatformIncomingWebhookData { pub status: AdyenplatformWebhookStatus, pub reference: String, pub tracking: Option<AdyenplatformInstantStatus>, + pub category: Option<AdyenPayoutMethod>, } #[derive(Debug, Serialize, Deserialize)] @@ -551,6 +552,7 @@ pub fn get_adyen_webhook_event( event_type: AdyenplatformWebhookEventType, status: AdyenplatformWebhookStatus, instant_status: Option<AdyenplatformInstantStatus>, + category: Option<&AdyenPayoutMethod>, ) -> webhooks::IncomingWebhookEvent { match (event_type, status, instant_status) { (AdyenplatformWebhookEventType::PayoutCreated, _, _) => { @@ -565,9 +567,25 @@ pub fn get_adyen_webhook_event( } } (AdyenplatformWebhookEventType::PayoutUpdated, status, _) => match status { - AdyenplatformWebhookStatus::Authorised - | AdyenplatformWebhookStatus::Booked - | AdyenplatformWebhookStatus::Received => webhooks::IncomingWebhookEvent::PayoutCreated, + AdyenplatformWebhookStatus::Authorised | AdyenplatformWebhookStatus::Received => { + webhooks::IncomingWebhookEvent::PayoutCreated + } + AdyenplatformWebhookStatus::Booked => { + match category { + Some(AdyenPayoutMethod::Card) => { + // For card payouts, "booked" is the final success state + webhooks::IncomingWebhookEvent::PayoutSuccess + } + Some(AdyenPayoutMethod::Bank) => { + // For bank payouts, "booked" is intermediate - wait for final confirmation + webhooks::IncomingWebhookEvent::PayoutProcessing + } + None => { + // Default to processing if category is unknown + webhooks::IncomingWebhookEvent::PayoutProcessing + } + } + } AdyenplatformWebhookStatus::Pending => webhooks::IncomingWebhookEvent::PayoutProcessing, AdyenplatformWebhookStatus::Failed => webhooks::IncomingWebhookEvent::PayoutFailure, AdyenplatformWebhookStatus::Returned => webhooks::IncomingWebhookEvent::PayoutReversed,
2025-08-20T10:56:53Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR updates the webhooks for Adyen's BalancePlatform for payouts. Main changes - For status `booked` from Adyen, map it to `success` for cards `processing` for banks - reason being status `credited` is received from Adyen for successful credits. Check the relevant issue for more 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 Enhances payout webhooks for Adyen's BalancePlatform. ## How did you test it? <details> <summary>1. Create a successful card payout</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_3ItwbKI2nwx45BPimAEaYP7QwnwKuC5a5GsG0aaow5wWefb62tXAcldZUrntn0jd' \ --data '{"amount":100,"currency":"EUR","profile_id":"pro_S5yvh1TfnZi2Gjv7uSUQ","customer_id":"cus_2bXx7dm7bRTOLOMlBAQi","connector":["adyenplatform"],"description":"Its my first payout request","payout_type":"card","payout_method_data":{"card":{"card_number":"4111111111111111","expiry_month":"03","expiry_year":"2030","card_holder_name":"John Doe"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","city":"San Fransico","country":"FR","first_name":"John","last_name":"Doe"}},"recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true}' Response {"payout_id":"payout_5nv2qm3avmPmQTbvFBZg","merchant_id":"merchant_1755690193","merchant_order_reference_id":null,"amount":100,"currency":"EUR","connector":"adyenplatform","payout_type":"card","payout_method_data":{"card":{"card_issuer":null,"card_network":null,"card_type":null,"card_issuing_country":null,"bank_code":null,"last4":"1111","card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe"}},"billing":{"address":{"city":"San Fransico","country":"FR","line1":"1467","line2":"Harrison Street","line3":null,"zip":null,"state":null,"first_name":"John","last_name":"Doe","origin_zip":null},"phone":null,"email":null},"auto_fulfill":true,"customer_id":"cus_2bXx7dm7bRTOLOMlBAQi","customer":{"id":"cus_2bXx7dm7bRTOLOMlBAQi","name":"John Nether","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_5nv2qm3avmPmQTbvFBZg_secret_j2B52JTji1yRrEOtd6FI","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_NsHlFe2GsWvK9CdftrLt","status":"initiated","error_message":null,"error_code":null,"profile_id":"pro_S5yvh1TfnZi2Gjv7uSUQ","created":"2025-08-20T11:49:11.757Z","connector_transaction_id":"38EBIY681J48U2JS","priority":null,"payout_link":null,"email":null,"name":"John Nether","phone":"6168205362","phone_country_code":"+1","unified_code":null,"unified_message":null,"payout_method_id":"pm_ywYBGKd0jKSUhIFyNho9"} Wait for incoming webhook Check for outgoing webhooks Initiated <img width="1726" height="906" alt="Screenshot 2025-08-20 at 5 21 04β€―PM" src="https://github.com/user-attachments/assets/74cc3db1-2338-4a31-8045-b5c54e156cfe" /> Successful <img width="1726" height="891" alt="Screenshot 2025-08-20 at 5 21 12β€―PM" src="https://github.com/user-attachments/assets/ae8fd898-a3f8-4f78-adcf-12d6ddb4c8f8" /> </details> <details> <summary>2. Create a successful SEPA payout</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Accept-Language: fr' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_3ItwbKI2nwx45BPimAEaYP7QwnwKuC5a5GsG0aaow5wWefb62tXAcldZUrntn0jd' \ --data '{"amount":1,"currency":"EUR","customer_id":"cus_2bXx7dm7bRTOLOMlBAQi","description":"Its my first payout request","payout_type":"bank","priority":"regular","payout_method_data":{"bank":{"iban":"NL57INGB4654188101"}},"connector":["adyenplatform"],"billing":{"address":{"line1":"Raadhuisplein","line2":"92","city":"Hoogeveen","country":"NL","first_name":"John"}},"entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true,"profile_id":"pro_S5yvh1TfnZi2Gjv7uSUQ"}' Response {"payout_id":"payout_FywtoqrSxKtwDDsbCvGa","merchant_id":"merchant_1755690193","merchant_order_reference_id":null,"amount":1,"currency":"EUR","connector":"adyenplatform","payout_type":"bank","payout_method_data":{"bank":{"iban":"NL57I********88101","bank_name":null,"bank_country_code":null,"bank_city":null,"bic":null}},"billing":{"address":{"city":"Hoogeveen","country":"NL","line1":"Raadhuisplein","line2":"92","line3":null,"zip":null,"state":null,"first_name":"John","last_name":null,"origin_zip":null},"phone":null,"email":null},"auto_fulfill":true,"customer_id":"cus_2bXx7dm7bRTOLOMlBAQi","customer":{"id":"cus_2bXx7dm7bRTOLOMlBAQi","name":"John Nether","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_FywtoqrSxKtwDDsbCvGa_secret_fC2TqhM2tucPGuzvQcDr","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_NsHlFe2GsWvK9CdftrLt","status":"initiated","error_message":null,"error_code":null,"profile_id":"pro_S5yvh1TfnZi2Gjv7uSUQ","created":"2025-08-20T11:51:48.487Z","connector_transaction_id":"38EBH1681J56C4WZ","priority":"regular","payout_link":null,"email":null,"name":"John Nether","phone":"6168205362","phone_country_code":"+1","unified_code":null,"unified_message":null,"payout_method_id":"pm_Vc6t4FK6HmbM2TUXsaBs"} Wait for incoming webhook Check for outgoing webhooks Initiated <img width="1728" height="898" alt="Screenshot 2025-08-20 at 5 22 39β€―PM" src="https://github.com/user-attachments/assets/a435370c-7954-4d02-8dc3-09b7bd242349" /> Successful <img width="1728" height="892" alt="Screenshot 2025-08-20 at 5 22 46β€―PM" src="https://github.com/user-attachments/assets/5b17c1e3-2990-4b9b-9b42-4685a7271a97" /> </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.116.0
a56d78a46a3ee80cdb2b48f9abfd2cd7b297e328
a56d78a46a3ee80cdb2b48f9abfd2cd7b297e328
juspay/hyperswitch
juspay__hyperswitch-8993
Bug: refactor: [Netcetera] Handle response deserialization error
diff --git a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs index 8444c7b9dd3..b6e85aea3ce 100644 --- a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs @@ -163,7 +163,10 @@ impl .authentication_request .as_ref() .and_then(|req| req.three_ds_requestor_challenge_ind.as_ref()) - .and_then(|v| v.first().cloned()); + .and_then(|ind| match ind { + ThreedsRequestorChallengeInd::Single(s) => Some(s.clone()), + ThreedsRequestorChallengeInd::Multiple(v) => v.first().cloned(), + }); let message_extension = response .authentication_request @@ -680,10 +683,17 @@ pub struct NetceteraAuthenticationFailureResponse { #[serde(rename_all = "camelCase")] pub struct AuthenticationRequest { #[serde(rename = "threeDSRequestorChallengeInd")] - pub three_ds_requestor_challenge_ind: Option<Vec<String>>, + pub three_ds_requestor_challenge_ind: Option<ThreedsRequestorChallengeInd>, pub message_extension: Option<serde_json::Value>, } +#[derive(Debug, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ThreedsRequestorChallengeInd { + Single(String), + Multiple(Vec<String>), +} + #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthenticationResponse { diff --git a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs index a26d0c7689f..1c6977ac5c9 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs @@ -75,7 +75,7 @@ pub struct MessageExtensionAttribute { pub id: String, pub name: String, pub criticality_indicator: bool, - pub data: String, + pub data: serde_json::Value, } #[derive(Clone, Default, Debug)]
2025-08-19T08:46:13Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Handle response deserialization error - three_ds_requestor_challenge_ind can be vector or string ### 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? Sanity flow with netcetra and cybersource Profile update ``` curl --location 'http://localhost:8080/account/merchant_1755510755/business_profile/pro_BwyTBsmG8NfDWCJNSozM' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_QBdrxdNVk1Qi1kfHVAxfkkN4It60LAsZB1Zfb1SWaXePTncdQ8qS6v0ikHyHcXJy' \ --data '{ "authentication_connector_details": { "authentication_connectors": ["netcetera"], "three_ds_requestor_url": "https://google.com" } }' ``` Response ``` { "merchant_id": "merchant_1755510755", "profile_id": "pro_BwyTBsmG8NfDWCJNSozM", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "iCpLwpK7rw6BuAvVHhA4n73QtuDLJ82MUwAqMzWsiAhytB8SnxVVjrqRmOhRuLD4", "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, "payment_statuses_enabled": null, "refund_statuses_enabled": null, "payout_statuses_enabled": null }, "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": { "authentication_connectors": [ "netcetera" ], "three_ds_requestor_url": "https://google.com", "three_ds_requestor_app_url": 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": false, "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, "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, "force_3ds_challenge": false, "is_debit_routing_enabled": false, "merchant_business_country": null, "is_pre_network_tokenization_enabled": false, "acquirer_configs": null, "is_iframe_redirection_enabled": null, "merchant_category_code": null, "merchant_country_code": null, "dispute_polling_interval": null } ``` Card request ``` { "amount": 2540, "currency": "USD", "profile_id": "pro_BwyTBsmG8NfDWCJNSozM", "confirm": true, "amount_to_capture": 2540, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "request_external_three_ds_authentication": true, "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "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" } }, "routing": { "type": "single", "data": "nmi" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4035 5014 2814 6300", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" // "card_network": "CartesBancaires" } }, "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" } } } ``` response ``` { "payment_id": "pay_VIDTWLGUcRV3CD9htaVR", "merchant_id": "merchant_1755510755", "status": "requires_customer_action", "amount": 2540, "net_amount": 2540, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "cybersource", "client_secret": "pay_VIDTWLGUcRV3CD9htaVR_secret_oQT12tBHvaPkuODXoyex", "created": "2025-08-19T10:17:28.860Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "6300", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "403550", "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": "token_V0xBNOlCVuSJuByMCfEB", "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", "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "three_ds_invoke", "three_ds_data": { "three_ds_authentication_url": "http://localhost:8080/payments/pay_VIDTWLGUcRV3CD9htaVR/3ds/authentication", "three_ds_authorize_url": "http://localhost:8080/payments/pay_VIDTWLGUcRV3CD9htaVR/merchant_1755510755/authorize/cybersource", "three_ds_method_details": { "three_ds_method_key": "threeDSMethodData", "three_ds_method_data_submission": true, "three_ds_method_data": "eyJ0aHJlZURTTWV0aG9kTm90aWZpY2F0aW9uVVJMIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS8zZHMtbWV0aG9kLW5vdGlmaWNhdGlvbi11cmwiLCJ0aHJlZURTU2VydmVyVHJhbnNJRCI6IjNiMGRhOGE5LWJhY2UtNGNlMS05NWI4LTJhMWNmOTlmOThhOCJ9", "three_ds_method_url": "https://ndm-prev.3dss-non-prod.cloud.netcetera.com/acs/3ds-method" }, "poll_config": { "poll_id": "external_authentication_pay_VIDTWLGUcRV3CD9htaVR", "delay_in_secs": 2, "frequency": 5 }, "message_version": "2.3.1", "directory_server_id": "A000000003" } }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1755598648, "expires": 1755602248, "secret": "epk_fd1d2eec8768439685e62ee45dabb4bc" }, "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_BwyTBsmG8NfDWCJNSozM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_dRvP71fPP5fDcWrMaE2z", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": { "authentication_flow": null, "electronic_commerce_indicator": null, "status": "pending", "ds_transaction_id": "3b0da8a9-bace-4ce1-95b8-2a1cf99f98a8", "version": "2.3.1", "error_code": null, "error_message": null }, "external_3ds_authentication_attempted": true, "expires_on": "2025-08-19T10:32:28.860Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-19T10:17:29.573Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } Create challenge ``` curl --location 'http://localhost:8080/payments/pay_VIDTWLGUcRV3CD9htaVR/3ds/authentication' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_5b6e1d248e7f412eaba54679208f9a84' \ --data '{ "client_secret": "pay_VIDTWLGUcRV3CD9htaVR_secret_oQT12tBHvaPkuODXoyex", "device_channel": "BRW", "threeds_method_comp_ind": "Y" }' Response ``` { "trans_status": "C", "acs_url": "https://ndm-prev.3dss-non-prod.cloud.netcetera.com/acs/challenge", "challenge_request": "eyJtZXNzYWdlVHlwZSI6IkNSZXEiLCJ0aHJlZURTU2VydmVyVHJhbnNJRCI6IjNiMGRhOGE5LWJhY2UtNGNlMS05NWI4LTJhMWNmOTlmOThhOCIsImFjc1RyYW5zSUQiOiJlNjcxYWM4ZS0wZWEyLTRhNzQtOGY5NC0zMzAyMDRhMWI3NmUiLCJjaGFsbGVuZ2VXaW5kb3dTaXplIjoiMDUiLCJtZXNzYWdlVmVyc2lvbiI6IjIuMy4xIn0", "acs_reference_number": "3DS_LOA_ACS_201_13579", "acs_trans_id": "e671ac8e-0ea2-4a74-8f94-330204a1b76e", "three_dsserver_trans_id": "3b0da8a9-bace-4ce1-95b8-2a1cf99f98a8", "acs_signed_content": null, "three_ds_requestor_url": "https://google.com", "three_ds_requestor_app_url": 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.116.0
58abb604d7a89519befa296d59506857bbdb0b8b
58abb604d7a89519befa296d59506857bbdb0b8b
juspay/hyperswitch
juspay__hyperswitch-8971
Bug: refactor(routing): receive json value instead of string
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 0b1395ed4ba..98b71748b35 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -2481,7 +2481,7 @@ pub async fn enable_decision_engine_dynamic_routing_setup( create_merchant_in_decision_engine_if_not_exists(state, profile_id, dynamic_routing_algo_ref) .await; - routing_utils::ConfigApiClient::send_decision_engine_request::<_, String>( + routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>( state, services::Method::Post, DECISION_ENGINE_RULE_CREATE_ENDPOINT, @@ -2559,7 +2559,7 @@ pub async fn update_decision_engine_dynamic_routing_setup( create_merchant_in_decision_engine_if_not_exists(state, profile_id, dynamic_routing_algo_ref) .await; - routing_utils::ConfigApiClient::send_decision_engine_request::<_, String>( + routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>( state, services::Method::Post, DECISION_ENGINE_RULE_UPDATE_ENDPOINT, @@ -2640,7 +2640,7 @@ pub async fn disable_decision_engine_dynamic_routing_setup( create_merchant_in_decision_engine_if_not_exists(state, profile_id, dynamic_routing_algo_ref) .await; - routing_utils::ConfigApiClient::send_decision_engine_request::<_, String>( + routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>( state, services::Method::Post, DECISION_ENGINE_RULE_DELETE_ENDPOINT, @@ -2691,7 +2691,7 @@ pub async fn create_decision_engine_merchant( gateway_success_rate_based_decider_input: None, }; - routing_utils::ConfigApiClient::send_decision_engine_request::<_, String>( + routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>( state, services::Method::Post, DECISION_ENGINE_MERCHANT_CREATE_ENDPOINT, @@ -2717,7 +2717,7 @@ pub async fn delete_decision_engine_merchant( DECISION_ENGINE_MERCHANT_BASE_ENDPOINT, profile_id.get_string_repr() ); - routing_utils::ConfigApiClient::send_decision_engine_request::<_, String>( + routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>( state, services::Method::Delete, &path,
2025-08-14T14:11:07Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Refactoring to recieve json response instead of string Updated `ConfigApiClient::send_decision_engine_request` calls in `crates/router/src/core/routing/helpers.rs` to return `serde_json::Value` instead of `String`. This ensures the response is parsed as JSON for better type safety and avoids manual string-to-JSON conversions in downstream logic. ### Changes Made * Replaced generic type parameter `String` with `serde_json::Value` in the following functions: * `enable_decision_engine_dynamic_routing_setup` * `update_decision_engine_dynamic_routing_setup` * `disable_decision_engine_dynamic_routing_setup` * `create_decision_engine_merchant` * `delete_decision_engine_merchant` ### Purpose Switching to `serde_json::Value` directly improves clarity, reduces redundant parsing, and enforces better response handling. ### Screenshot create <img width="1717" height="93" alt="Screenshot 2025-08-21 at 4 11 10β€―PM" src="https://github.com/user-attachments/assets/68f8bc6a-ffa4-48fc-b030-68fc0a98da2c" /> update <img width="1709" height="141" alt="Screenshot 2025-08-21 at 4 30 10β€―PM" src="https://github.com/user-attachments/assets/1dbf40ea-87d9-40fc-83dc-ac39036262db" /> delete <img width="1725" height="71" alt="Screenshot 2025-08-21 at 4 31 25β€―PM" src="https://github.com/user-attachments/assets/bffe1bc7-28ac-43ab-9e4f-e1403dd6bca7" /> <img width="1612" height="992" alt="Screenshot 2025-08-19 at 6 23 55β€―PM" src="https://github.com/user-attachments/assets/14d788c3-9645-456f-a924-7988e46e9b10" /> <img width="1299" height="962" alt="Screenshot 2025-08-19 at 6 24 33β€―PM" src="https://github.com/user-attachments/assets/1ef46ebd-e286-4ae4-afcd-a33e3d505d7e" /> <img width="1335" height="637" alt="Screenshot 2025-08-19 at 6 25 46β€―PM" src="https://github.com/user-attachments/assets/c3a52c37-bbc4-4574-877b-e952406730c8" /> Curls and responses create ``` curl --location 'http://localhost:8080/account/merchant_1756381962/business_profile/pro_nbWFu0RUhkjNIV4YgAJF/dynamic_routing/success_based/create?enable=dynamic_connector_selection' \ --header 'Content-Type: application/json' \ --header 'api-key:****' \ --data '{ "decision_engine_configs": { "defaultLatencyThreshold": 90, "defaultBucketSize": 200, "defaultHedgingPercent": 5, "subLevelInputConfig": [ { "paymentMethodType": "card", "paymentMethod": "credit", "bucketSize": 250, "hedgingPercent": 1 } ] } }' ``` ``` { "id": "routing_51b92mSgs0B0PJz5xM9R", "profile_id": "pro_nbWFu0RUhkjNIV4YgAJF", "name": "Success rate based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1756381971, "modified_at": 1756381971, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` update ``` curl --location --request PATCH 'http://localhost:8080/account/merchant_1756381962/business_profile/pro_nbWFu0RUhkjNIV4YgAJF/dynamic_routing/success_based/config/routing_51b92mSgs0B0PJz5xM9R' \ --header 'api-key:****' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --data '{ "decision_engine_configs": { "defaultLatencyThreshold": 90, "defaultBucketSize": 100, "defaultHedgingPercent": 5, "subLevelInputConfig": [ { "paymentMethodType": "card", "paymentMethod": "credit", "bucketSize": 250, "hedgingPercent": 1 } ] } }' ``` ``` { "id": "routing_PTySs5RDUL22VinElTAn", "profile_id": "pro_nbWFu0RUhkjNIV4YgAJF", "name": "Success rate based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1756382062, "modified_at": 1756382062, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` activate ``` curl --location 'http://localhost:8080/routing/routing_51b92mSgs0B0PJz5xM9R/activate' \ --header 'Content-Type: application/json' \ --header 'api-key:****' \ --data '{}' ``` ``` { "id": "routing_51b92mSgs0B0PJz5xM9R", "profile_id": "pro_nbWFu0RUhkjNIV4YgAJF", "name": "Success rate based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1756381971, "modified_at": 1756381971, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` deactivate(deletion) ``` curl --location 'http://localhost:8080/account/merchant_1756381962/business_profile/pro_nbWFu0RUhkjNIV4YgAJF/dynamic_routing/success_based/create?enable=none' \ --header 'Content-Type: application/json' \ --header 'api-key:****' \ --data '{ "decision_engine_configs": { "defaultLatencyThreshold": 90, "defaultBucketSize": 200, "defaultHedgingPercent": 5, "subLevelInputConfig": [ { "paymentMethodType": "card", "paymentMethod": "credit", "bucketSize": 250, "hedgingPercent": 1 } ] } }' ``` ``` { "id": "routing_51b92mSgs0B0PJz5xM9R", "profile_id": "pro_nbWFu0RUhkjNIV4YgAJF", "name": "Success rate based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1756381971, "modified_at": 1756381971, "algorithm_for": "payment", "decision_engine_routing_id": null } ```
v1.116.0
aae1994ea147fa1ebdc9555f00b072bb9ed57abc
aae1994ea147fa1ebdc9555f00b072bb9ed57abc
juspay/hyperswitch
juspay__hyperswitch-8973
Bug: [REFACTOR] remove non mandatory fields for Adyen Platform payouts Hyperswitch mandates a few fields for AdyenPlatform connector which are not needed. These are needed to be made optional. List of fields - Billing address details
diff --git a/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs index 82c9afadeed..6c964aea20f 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs @@ -2,9 +2,9 @@ use api_models::{payouts, webhooks}; use common_enums::enums; use common_utils::pii; use error_stack::{report, ResultExt}; -use hyperswitch_domain_models::types; +use hyperswitch_domain_models::types::{self, PayoutsRouterData}; use hyperswitch_interfaces::errors::ConnectorError; -use masking::Secret; +use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use super::{AdyenPlatformRouterData, Error}; @@ -68,10 +68,11 @@ pub struct AdyenBankAccountDetails { #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenAccountHolder { - address: AdyenAddress, + address: Option<AdyenAddress>, first_name: Option<Secret<String>>, last_name: Option<Secret<String>>, full_name: Option<Secret<String>>, + email: Option<pii::Email>, #[serde(rename = "reference")] customer_id: Option<String>, #[serde(rename = "type")] @@ -251,40 +252,94 @@ impl TryFrom<&hyperswitch_domain_models::address::AddressDetails> for AdyenAddre } } -impl<F> TryFrom<(&types::PayoutsRouterData<F>, enums::PayoutType)> for AdyenAccountHolder { +impl<F> TryFrom<(&PayoutsRouterData<F>, &payouts::CardPayout)> for AdyenAccountHolder { type Error = Error; fn try_from( - (router_data, payout_type): (&types::PayoutsRouterData<F>, enums::PayoutType), + (router_data, card): (&PayoutsRouterData<F>, &payouts::CardPayout), ) -> Result<Self, Self::Error> { - let billing_address = router_data.get_billing_address()?; - let (first_name, last_name, full_name) = match payout_type { - enums::PayoutType::Card => ( - Some(router_data.get_billing_first_name()?), - Some(router_data.get_billing_last_name()?), - None, - ), - enums::PayoutType::Bank => (None, None, Some(router_data.get_billing_full_name()?)), - _ => Err(ConnectorError::NotSupported { - message: "Payout method not supported".to_string(), - connector: "Adyen", - })?, + let billing_address = router_data.get_optional_billing(); + + // Address is required for both card and bank payouts + let address = billing_address + .and_then(|billing| billing.address.as_ref().map(|addr| addr.try_into())) + .transpose()? + .ok_or(ConnectorError::MissingRequiredField { + field_name: "address", + })?; + + let (first_name, last_name) = if let Some(card_holder_name) = &card.card_holder_name { + let exposed_name = card_holder_name.clone().expose(); + let name_parts: Vec<&str> = exposed_name.split_whitespace().collect(); + let first_name = name_parts + .first() + .map(|s| Secret::new(s.to_string())) + .ok_or(ConnectorError::MissingRequiredField { + field_name: "card_holder_name.first_name", + })?; + let last_name = if name_parts.len() > 1 { + let remaining_names: Vec<&str> = name_parts.iter().skip(1).copied().collect(); + Some(Secret::new(remaining_names.join(" "))) + } else { + return Err(ConnectorError::MissingRequiredField { + field_name: "card_holder_name.last_name", + } + .into()); + }; + (Some(first_name), last_name) + } else { + return Err(ConnectorError::MissingRequiredField { + field_name: "card_holder_name", + } + .into()); }; + Ok(Self { - address: billing_address.try_into()?, + address: Some(address), first_name, last_name, - full_name, + full_name: None, + email: router_data.get_optional_billing_email(), + customer_id: Some(router_data.get_customer_id()?.get_string_repr().to_owned()), + entity_type: Some(EntityType::from(router_data.request.entity_type)), + }) + } +} + +impl<F> TryFrom<(&PayoutsRouterData<F>, &payouts::Bank)> for AdyenAccountHolder { + type Error = Error; + + fn try_from( + (router_data, _bank): (&PayoutsRouterData<F>, &payouts::Bank), + ) -> Result<Self, Self::Error> { + let billing_address = router_data.get_optional_billing(); + + // Address is required for both card and bank payouts + let address = billing_address + .and_then(|billing| billing.address.as_ref().map(|addr| addr.try_into())) + .transpose()? + .ok_or(ConnectorError::MissingRequiredField { + field_name: "address", + })?; + + let full_name = router_data.get_billing_full_name()?; + + Ok(Self { + address: Some(address), + first_name: None, + last_name: None, + full_name: Some(full_name), + email: router_data.get_optional_billing_email(), customer_id: Some(router_data.get_customer_id()?.get_string_repr().to_owned()), entity_type: Some(EntityType::from(router_data.request.entity_type)), }) } } -impl<F> TryFrom<&AdyenPlatformRouterData<&types::PayoutsRouterData<F>>> for AdyenTransferRequest { +impl<F> TryFrom<&AdyenPlatformRouterData<&PayoutsRouterData<F>>> for AdyenTransferRequest { type Error = Error; fn try_from( - item: &AdyenPlatformRouterData<&types::PayoutsRouterData<F>>, + item: &AdyenPlatformRouterData<&PayoutsRouterData<F>>, ) -> Result<Self, Self::Error> { let request = &item.router_data.request; let (counterparty, priority) = match item.router_data.get_payout_method_data()? { @@ -292,8 +347,7 @@ impl<F> TryFrom<&AdyenPlatformRouterData<&types::PayoutsRouterData<F>>> for Adye utils::get_unimplemented_payment_method_error_message("Adyenplatform"), ))?, payouts::PayoutMethodData::Card(c) => { - let card_holder: AdyenAccountHolder = - (item.router_data, enums::PayoutType::Card).try_into()?; + let card_holder: AdyenAccountHolder = (item.router_data, &c).try_into()?; let card_identification = AdyenCardIdentification { card_number: c.card_number, expiry_month: c.expiry_month, @@ -309,8 +363,7 @@ impl<F> TryFrom<&AdyenPlatformRouterData<&types::PayoutsRouterData<F>>> for Adye (counterparty, None) } payouts::PayoutMethodData::Bank(bd) => { - let account_holder: AdyenAccountHolder = - (item.router_data, enums::PayoutType::Bank).try_into()?; + let account_holder: AdyenAccountHolder = (item.router_data, &bd).try_into()?; let bank_details = match bd { payouts::Bank::Sepa(b) => AdyenBankAccountIdentification { bank_type: "iban".to_string(), @@ -367,9 +420,7 @@ impl<F> TryFrom<&AdyenPlatformRouterData<&types::PayoutsRouterData<F>>> for Adye } } -impl<F> TryFrom<PayoutsResponseRouterData<F, AdyenTransferResponse>> - for types::PayoutsRouterData<F> -{ +impl<F> TryFrom<PayoutsResponseRouterData<F, AdyenTransferResponse>> for PayoutsRouterData<F> { type Error = Error; fn try_from( item: PayoutsResponseRouterData<F, AdyenTransferResponse>, diff --git a/crates/router/src/configs/defaults/payout_required_fields.rs b/crates/router/src/configs/defaults/payout_required_fields.rs index a056a3ac931..d6b316c42b4 100644 --- a/crates/router/src/configs/defaults/payout_required_fields.rs +++ b/crates/router/src/configs/defaults/payout_required_fields.rs @@ -66,12 +66,81 @@ impl Default for PayoutRequiredFields { } } +fn get_billing_details_for_payment_method( + connector: PayoutConnectors, + payment_method_type: PaymentMethodType, +) -> HashMap<String, RequiredFieldInfo> { + match connector { + PayoutConnectors::Adyenplatform => { + let mut fields = HashMap::from([ + ( + "billing.address.line1".to_string(), + RequiredFieldInfo { + required_field: "billing.address.line1".to_string(), + display_name: "billing_address_line1".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.line2".to_string(), + RequiredFieldInfo { + required_field: "billing.address.line2".to_string(), + display_name: "billing_address_line2".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.city".to_string(), + RequiredFieldInfo { + required_field: "billing.address.city".to_string(), + display_name: "billing_address_city".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.country".to_string(), + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "billing_address_country".to_string(), + field_type: FieldType::UserAddressCountry { + options: get_countries_for_connector(connector) + .iter() + .map(|country| country.to_string()) + .collect::<Vec<String>>(), + }, + value: None, + }, + ), + ]); + + // Add first_name for bank payouts only + if payment_method_type == PaymentMethodType::Sepa { + fields.insert( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_address_first_name".to_string(), + field_type: FieldType::Text, + value: None, + }, + ); + } + + fields + } + _ => get_billing_details(connector), + } +} + #[cfg(feature = "v1")] fn get_connector_payment_method_type_fields( connector: PayoutConnectors, payment_method_type: PaymentMethodType, ) -> (PaymentMethodType, ConnectorFields) { - let mut common_fields = get_billing_details(connector); + let mut common_fields = get_billing_details_for_payment_method(connector, payment_method_type); match payment_method_type { // Card PaymentMethodType::Debit => { @@ -409,67 +478,6 @@ fn get_billing_details(connector: PayoutConnectors) -> HashMap<String, RequiredF }, ), ]), - PayoutConnectors::Adyenplatform => HashMap::from([ - ( - "billing.address.line1".to_string(), - RequiredFieldInfo { - required_field: "billing.address.line1".to_string(), - display_name: "billing_address_line1".to_string(), - field_type: FieldType::Text, - value: None, - }, - ), - ( - "billing.address.line2".to_string(), - RequiredFieldInfo { - required_field: "billing.address.line2".to_string(), - display_name: "billing_address_line2".to_string(), - field_type: FieldType::Text, - value: None, - }, - ), - ( - "billing.address.city".to_string(), - RequiredFieldInfo { - required_field: "billing.address.city".to_string(), - display_name: "billing_address_city".to_string(), - field_type: FieldType::Text, - value: None, - }, - ), - ( - "billing.address.country".to_string(), - RequiredFieldInfo { - required_field: "billing.address.country".to_string(), - display_name: "billing_address_country".to_string(), - field_type: FieldType::UserAddressCountry { - options: get_countries_for_connector(connector) - .iter() - .map(|country| country.to_string()) - .collect::<Vec<String>>(), - }, - value: None, - }, - ), - ( - "billing.address.first_name".to_string(), - RequiredFieldInfo { - required_field: "billing.address.first_name".to_string(), - display_name: "billing_address_first_name".to_string(), - field_type: FieldType::Text, - value: None, - }, - ), - ( - "billing.address.last_name".to_string(), - RequiredFieldInfo { - required_field: "billing.address.last_name".to_string(), - display_name: "billing_address_last_name".to_string(), - field_type: FieldType::Text, - value: None, - }, - ), - ]), PayoutConnectors::Wise => HashMap::from([ ( "billing.address.line1".to_string(), @@ -531,75 +539,6 @@ fn get_billing_details(connector: PayoutConnectors) -> HashMap<String, RequiredF }, ), ]), - _ => HashMap::from([ - ( - "billing.address.line1".to_string(), - RequiredFieldInfo { - required_field: "billing.address.line1".to_string(), - display_name: "billing_address_line1".to_string(), - field_type: FieldType::Text, - value: None, - }, - ), - ( - "billing.address.line2".to_string(), - RequiredFieldInfo { - required_field: "billing.address.line2".to_string(), - display_name: "billing_address_line2".to_string(), - field_type: FieldType::Text, - value: None, - }, - ), - ( - "billing.address.city".to_string(), - RequiredFieldInfo { - required_field: "billing.address.city".to_string(), - display_name: "billing_address_city".to_string(), - field_type: FieldType::Text, - value: None, - }, - ), - ( - "billing.address.zip".to_string(), - RequiredFieldInfo { - required_field: "billing.address.zip".to_string(), - display_name: "billing_address_zip".to_string(), - field_type: FieldType::Text, - value: None, - }, - ), - ( - "billing.address.country".to_string(), - RequiredFieldInfo { - required_field: "billing.address.country".to_string(), - display_name: "billing_address_country".to_string(), - field_type: FieldType::UserAddressCountry { - options: get_countries_for_connector(connector) - .iter() - .map(|country| country.to_string()) - .collect::<Vec<String>>(), - }, - value: None, - }, - ), - ( - "billing.address.first_name".to_string(), - RequiredFieldInfo { - required_field: "billing.address.first_name".to_string(), - display_name: "billing_address_first_name".to_string(), - field_type: FieldType::Text, - value: None, - }, - ), - ( - "billing.address.last_name".to_string(), - RequiredFieldInfo { - required_field: "billing.address.last_name".to_string(), - display_name: "billing_address_last_name".to_string(), - field_type: FieldType::Text, - value: None, - }, - ), - ]), + _ => HashMap::from([]), } }
2025-08-19T09:27:54Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR removes any non mandatory fields from AdyenPlatform connector for card and SEPA payouts. New list - Card payouts [payout_method_data.card.card_number](https://api-reference.hyperswitch.io/v1/payouts/payouts--create#body-payout-method-data-card-card-number) [payout_method_data.card.expiry_month](https://api-reference.hyperswitch.io/v1/payouts/payouts--create#body-payout-method-data-card-expiry-month) [payout_method_data.card.expiry_year](https://api-reference.hyperswitch.io/v1/payouts/payouts--create#body-payout-method-data-card-expiry-year) [payout_method_data.card.card_holder_name](https://api-reference.hyperswitch.io/v1/payouts/payouts--create#body-payout-method-data-card-card-holder-name) [billing.address.line1](https://api-reference.hyperswitch.io/v1/payouts/payouts--create#body-billing-address-line1) [billing.address.line2](https://api-reference.hyperswitch.io/v1/payouts/payouts--create#body-billing-address-line2) [billing.address.city](https://api-reference.hyperswitch.io/v1/payouts/payouts--create#body-billing-address-city) [billing.address.country](https://api-reference.hyperswitch.io/v1/payouts/payouts--create#body-billing-address-country) - Bank payouts Along with the payout method data depending on the bank (https://api-reference.hyperswitch.io/v1/payouts/payouts--create#body-payout-method-data-bank) [billing.address.line1](https://api-reference.hyperswitch.io/v1/payouts/payouts--create#body-billing-address-line1) [billing.address.line2](https://api-reference.hyperswitch.io/v1/payouts/payouts--create#body-billing-address-line2) [billing.address.city](https://api-reference.hyperswitch.io/v1/payouts/payouts--create#body-billing-address-city) [billing.address.country](https://api-reference.hyperswitch.io/v1/payouts/payouts--create#body-billing-address-country) [billing.address.first_name](https://api-reference.hyperswitch.io/v1/payouts/payouts--create#body-billing-address-first-name) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context This PR removes any mandatory fields that were needed for processing payouts via Adyenplatform ## How did you test it? Tested locally <details> <summary>[Negative] 1. Create SEPA payout with missing billing details</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_Rko4ofOnDKpn3Dbs0ZUz8PQ1qdIDgT183ONTPiY0dUFAJcv4eyDrzIzEnd6iFc0j' \ --data '{"amount":1,"currency":"EUR","customer_id":"cus_5SyQoohBVj6cdUfmqLLK","description":"Its my first payout request","payout_type":"bank","priority":"instant","payout_method_data":{"bank":{"iban":"NL06INGB5632579034"}},"connector":["adyenplatform"],"entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true,"profile_id":"pro_AiAxQKHVhrQ8xdFAllu5"}' Response { "error": { "type": "invalid_request", "message": "Missing required param: address", "code": "IR_04" } } </details> <details> <summary>[Negative] 2. Create Card payout with missing billing details</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_Rko4ofOnDKpn3Dbs0ZUz8PQ1qdIDgT183ONTPiY0dUFAJcv4eyDrzIzEnd6iFc0j' \ --data '{"amount":100,"currency":"EUR","profile_id":"pro_AiAxQKHVhrQ8xdFAllu5","customer_id":"cus_5SyQoohBVj6cdUfmqLLK","connector":["adyenplatform"],"description":"Its my first payout request","payout_type":"card","payout_method_data":{"card":{"card_number":"4111111111111111","expiry_month":"03","expiry_year":"2030","card_holder_name":"John Doe"}},"recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true}' Response { "error": { "type": "invalid_request", "message": "Missing required param: address", "code": "IR_04" } } </details> <details> <summary>3. Create a SEPA payout with mandatory fields</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_Rko4ofOnDKpn3Dbs0ZUz8PQ1qdIDgT183ONTPiY0dUFAJcv4eyDrzIzEnd6iFc0j' \ --data '{"amount":1,"currency":"EUR","customer_id":"cus_5SyQoohBVj6cdUfmqLLK","description":"Its my first payout request","payout_type":"bank","priority":"instant","payout_method_data":{"bank":{"iban":"NL06INGB5632579034"}},"connector":["adyenplatform"],"billing":{"address":{"line1":"Raadhuisplein","line2":"92","city":"Hoogeveen","country":"NL","first_name":"John"}},"entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true,"profile_id":"pro_AiAxQKHVhrQ8xdFAllu5"}' Response {"payout_id":"payout_rBKFN2yzDxmULDYFUApY","merchant_id":"merchant_1755587924","merchant_order_reference_id":null,"amount":1,"currency":"EUR","connector":"adyenplatform","payout_type":"bank","payout_method_data":{"bank":{"iban":"NL06I********79034","bank_name":null,"bank_country_code":null,"bank_city":null,"bic":null}},"billing":{"address":{"city":"Hoogeveen","country":"NL","line1":"Raadhuisplein","line2":"92","line3":null,"zip":null,"state":null,"first_name":"John","last_name":null,"origin_zip":null},"phone":null,"email":null},"auto_fulfill":true,"customer_id":"cus_5SyQoohBVj6cdUfmqLLK","customer":{"id":"cus_5SyQoohBVj6cdUfmqLLK","name":"John Nether","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_rBKFN2yzDxmULDYFUApY_secret_3G01mWdnAttOAfeC2wa8","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_KrzAoNCxtUDCf6kAzESd","status":"initiated","error_message":null,"error_code":null,"profile_id":"pro_AiAxQKHVhrQ8xdFAllu5","created":"2025-08-19T09:31:28.239Z","connector_transaction_id":"38EBH16813GN2MVG","priority":"instant","payout_link":null,"email":null,"name":"John Nether","phone":"6168205362","phone_country_code":"+1","unified_code":null,"unified_message":null,"payout_method_id":"pm_jod7TuYT46i6dCHkGmev"} </details> <details> <summary>4. Card payout with required fields</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_Rko4ofOnDKpn3Dbs0ZUz8PQ1qdIDgT183ONTPiY0dUFAJcv4eyDrzIzEnd6iFc0j' \ --data '{"amount":100,"currency":"EUR","profile_id":"pro_AiAxQKHVhrQ8xdFAllu5","customer_id":"cus_5SyQoohBVj6cdUfmqLLK","connector":["adyenplatform"],"description":"Its my first payout request","payout_type":"card","payout_method_data":{"card":{"card_number":"4111111111111111","expiry_month":"03","expiry_year":"2030","card_holder_name":"John Doe"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","city":"San Fransico","country":"FR"}},"recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true}' Response {"payout_id":"payout_Lg2UYU0m2wQQC23NIGSD","merchant_id":"merchant_1755587924","merchant_order_reference_id":null,"amount":100,"currency":"EUR","connector":"adyenplatform","payout_type":"card","payout_method_data":{"card":{"card_issuer":null,"card_network":null,"card_type":null,"card_issuing_country":null,"bank_code":null,"last4":"1111","card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe"}},"billing":{"address":{"city":"San Fransico","country":"FR","line1":"1467","line2":"Harrison Street","line3":null,"zip":null,"state":null,"first_name":null,"last_name":null,"origin_zip":null},"phone":null,"email":null},"auto_fulfill":true,"customer_id":"cus_5SyQoohBVj6cdUfmqLLK","customer":{"id":"cus_5SyQoohBVj6cdUfmqLLK","name":"John Nether","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_Lg2UYU0m2wQQC23NIGSD_secret_52k9WAGvV9OkAbfIZ4t4","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_KrzAoNCxtUDCf6kAzESd","status":"initiated","error_message":null,"error_code":null,"profile_id":"pro_AiAxQKHVhrQ8xdFAllu5","created":"2025-08-19T09:32:26.497Z","connector_transaction_id":"38EBH66813GZBWSE","priority":null,"payout_link":null,"email":null,"name":"John Nether","phone":"6168205362","phone_country_code":"+1","unified_code":null,"unified_message":null,"payout_method_id":"pm_sKZq1HLWSxrszfZGuubX"} </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.116.0
58abb604d7a89519befa296d59506857bbdb0b8b
58abb604d7a89519befa296d59506857bbdb0b8b
juspay/hyperswitch
juspay__hyperswitch-8969
Bug: [BUG] Logging sensitive information on deserialization failure ### Bug Description In `common_utils/src/ext_traits.rs` we are logging serde_json Values in plaintext when deserialization fails. This is a problem in cases where the JSON objects contain sensitive data. ### Expected Behavior Sensitive data is not logged. Values are logged after masking. ### Actual Behavior Sensitive information is logged. ### Steps To Reproduce Supply malformed data to the `parse_value` method in `ValueExt` trait. ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs index 6bdeae9b6d9..b60ef5a22f2 100644 --- a/crates/common_utils/src/ext_traits.rs +++ b/crates/common_utils/src/ext_traits.rs @@ -175,7 +175,13 @@ impl BytesExt for bytes::Bytes { .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| { let variable_type = std::any::type_name::<T>(); - format!("Unable to parse {variable_type} from bytes {self:?}") + let value = serde_json::from_slice::<serde_json::Value>(self) + .unwrap_or_else(|_| serde_json::Value::String(String::new())); + + format!( + "Unable to parse {variable_type} from bytes {:?}", + Secret::<_, masking::JsonMaskStrategy>::new(value) + ) }) } } @@ -202,7 +208,15 @@ impl ByteSliceExt for [u8] { { serde_json::from_slice(self) .change_context(errors::ParsingError::StructParseFailure(type_name)) - .attach_printable_lazy(|| format!("Unable to parse {type_name} from &[u8] {:?}", &self)) + .attach_printable_lazy(|| { + let value = serde_json::from_slice::<serde_json::Value>(self) + .unwrap_or_else(|_| serde_json::Value::String(String::new())); + + format!( + "Unable to parse {type_name} from &[u8] {:?}", + Secret::<_, masking::JsonMaskStrategy>::new(value) + ) + }) } } @@ -219,13 +233,15 @@ impl ValueExt for serde_json::Value { where T: serde::de::DeserializeOwned, { - let debug = format!( - "Unable to parse {type_name} from serde_json::Value: {:?}", - &self - ); - serde_json::from_value::<T>(self) + serde_json::from_value::<T>(self.clone()) .change_context(errors::ParsingError::StructParseFailure(type_name)) - .attach_printable_lazy(|| debug) + .attach_printable_lazy(|| { + format!( + "Unable to parse {type_name} from serde_json::Value: {:?}", + // Required to prevent logging sensitive data in case of deserialization failure + Secret::<_, masking::JsonMaskStrategy>::new(self) + ) + }) } } @@ -289,7 +305,12 @@ impl<T> StringExt<T> for String { serde_json::from_str::<T>(self) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| { - format!("Unable to parse {type_name} from string {:?}", &self) + format!( + "Unable to parse {type_name} from string {:?}", + Secret::<_, masking::JsonMaskStrategy>::new(serde_json::Value::String( + self.clone() + )) + ) }) } }
2025-08-18T04:03:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Modified `parse_value` method in `ValueExt` trait to log the JSON object after masking on deserialization failure. - Modified `parse_struct` method in `BytesExt`, `ByteSliceExt` and `StringExt` to log values after converting them into a `serde_json::Value` and then masking ### 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 #8969 ## 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 supplying malformed data to the method and verified it logs data after masking. Object: <img width="1079" height="49" alt="image" src="https://github.com/user-attachments/assets/a7f917af-b356-475d-b3d8-c29fcae29fc0" /> String: <img width="1079" height="47" alt="image" src="https://github.com/user-attachments/assets/d009c43d-f114-4d0b-bda2-4fc8797ee45d" /> Array: <img width="728" height="47" alt="image" src="https://github.com/user-attachments/assets/10929436-aec4-45ef-bec3-8f653dc48cb3" /> ## 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.117.0
b133c534fb1ce40bd6cca27fac4f2d58b0863e30
b133c534fb1ce40bd6cca27fac4f2d58b0863e30
juspay/hyperswitch
juspay__hyperswitch-8963
Bug: refactor(euclid): add logs for euclid routing
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 0c0061e7918..44a4602ffa6 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -8103,6 +8103,7 @@ where .attach_printable("Invalid connector name received in 'routed_through'")?; routing_data.routed_through = Some(connector_name.clone()); + logger::debug!("euclid_routing: predetermined connector present in attempt"); return Ok(ConnectorCallType::PreDetermined(connector_data.into())); } @@ -8122,6 +8123,7 @@ where .merchant_connector_id .clone_from(&mandate_connector_details.merchant_connector_id); + logger::debug!("euclid_routing: predetermined mandate connector"); return Ok(ConnectorCallType::PreDetermined(connector_data.into())); } @@ -8206,6 +8208,8 @@ where } } + logger::debug!("euclid_routing: pre-routing connector present"); + let first_pre_routing_connector_data_list = pre_routing_connector_data_list .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; @@ -8269,6 +8273,7 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; + logger::debug!("euclid_routing: straight through connector present"); return decide_multiplex_connector_for_normal_or_recurring_payment( &state, payment_data, @@ -8313,6 +8318,7 @@ where .attach_printable("failed eligibility analysis and fallback")?; } + logger::debug!("euclid_routing: single connector present in algorithm data"); let connector_data = connectors .into_iter() .map(|conn| { @@ -8400,7 +8406,7 @@ where Some(api::MandateTransactionType::RecurringMandateTransaction), ) | (None, Some(_), None, Some(true), _) => { - logger::debug!("performing routing for token-based MIT flow"); + logger::debug!("euclid_routing: performing routing for token-based MIT flow"); let payment_method_info = payment_data .get_payment_method_info() @@ -8513,7 +8519,9 @@ where .into(), )) } else { - logger::error!("no eligible connector found for the ppt_mandate payment"); + logger::error!( + "euclid_routing: no eligible connector found for the ppt_mandate payment" + ); Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration.into()) } } @@ -8572,7 +8580,7 @@ where }) .unwrap_or(false) { - logger::info!("using connector_mandate_id for MIT flow"); + logger::info!("euclid_routing: using connector_mandate_id for MIT flow"); if let Some(merchant_connector_id) = connector_data.merchant_connector_id.as_ref() { if let Some(mandate_reference_record) = connector_mandate_details.clone() .get_required_value("connector_mandate_details") diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 19ddeb7f15f..a06b6140da4 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -441,6 +441,7 @@ pub async fn perform_static_routing_v1( Vec<routing_types::RoutableConnectorChoice>, Option<common_enums::RoutingApproach>, )> { + logger::debug!("euclid_routing: performing routing for connector selection"); let get_merchant_fallback_config = || async { #[cfg(feature = "v1")] return routing::helpers::get_merchant_default_config( @@ -459,6 +460,7 @@ pub async fn perform_static_routing_v1( id } else { let fallback_config = get_merchant_fallback_config().await?; + logger::debug!("euclid_routing: active algorithm isn't present, default falling back"); return Ok((fallback_config, None)); }; let cached_algorithm = ensure_algorithm_cached_v1( @@ -1038,6 +1040,7 @@ pub async fn perform_eligibility_analysis_with_fallback( eligible_connectors: Option<Vec<api_enums::RoutableConnectors>>, business_profile: &domain::Profile, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { + logger::debug!("euclid_routing: performing eligibility"); let mut final_selection = perform_eligibility_analysis( state, key_store, @@ -1072,7 +1075,7 @@ pub async fn perform_eligibility_analysis_with_fallback( .iter() .map(|item| item.connector) .collect::<Vec<_>>(); - logger::debug!(final_selected_connectors_for_routing=?final_selected_connectors, "List of final selected connectors for routing"); + logger::debug!(final_selected_connectors_for_routing=?final_selected_connectors, "euclid_routing: List of final selected connectors for routing"); Ok(final_selection) }
2025-08-14T11:42:09Z
## 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 --> Added logs for routing engine. ### 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)? --> This PR only introduces logs, hence no testing is required. ## 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.116.0
b797d93433d996e5d22269bcab1980c292b0121e
b797d93433d996e5d22269bcab1980c292b0121e
juspay/hyperswitch
juspay__hyperswitch-8968
Bug: [FEATURE] Cypress test for UCS through Hyperswitch ### Feature Description there should be a cypress test supported for ucs through hyperswitch ### Possible Implementation make code changes in cypress folder and call ucs related api's ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
2025-08-18T03:51:27Z
## 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 --> added cypress test for ucs by maintaing the flow Closes #8968 ### 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)? --> You can test it with `npm run cypress:ucs` ## 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 ScreenShot of the tests <img width="1728" height="1056" alt="Screenshot 2025-08-18 at 9 15 17β€―AM" src="https://github.com/user-attachments/assets/20040bb1-c6a1-4158-a387-50c66330bbdd" /> <img width="1728" height="1062" alt="Screenshot 2025-08-18 at 9 15 30β€―AM" src="https://github.com/user-attachments/assets/809c8e81-0bc4-4d15-a754-aa1a08be7c30" />
v1.116.0
e2d72bef7dc07540ee4d54bfc79b934bc303dca7
e2d72bef7dc07540ee4d54bfc79b934bc303dca7
juspay/hyperswitch
juspay__hyperswitch-8947
Bug: [BUG] Payments in Integ Dashboard failing to load due to backward compatibility issue ### Bug Description Payments in Integ Dashboard failing to load due to backward compatibility issue ### Expected Behavior Payments in Integ Dashboard shouldn't fail to load. ### Actual Behavior Payments in Integ Dashboard failing to load due to backward compatibility issue ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: macOS 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/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 390be5f86f0..02dbdddf4a3 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -22770,7 +22770,8 @@ "type": "string", "enum": [ "true", - "false" + "false", + "default" ] }, "RequestPaymentMethodTypes": { diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index ec8d55ed000..3b61b810baf 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2850,6 +2850,7 @@ pub enum RequestIncrementalAuthorization { True, #[default] False, + Default, } #[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, strum::Display, ToSchema,)]
2025-08-13T20:34:28Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/8947) ## Description <!-- Describe your changes in detail --> Added Default Enum Variant in RequestIncrementalAuthorization ### 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 Tests 1. Create a payment with old version confirm with new (old and new application should be able to retrieve) Payments - Create (with Confirm: false) Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_nDwiGI0dyLcP8uP4zJj6TPrzetozj6rVGm7o9WV3KZJX4nKVPrB1VaIhnrcUrkXv' \ --data-raw '{ "amount": 6500, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6500, "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "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": "2025-07-25T11:46:12Z" } }' ``` Response: ``` { "payment_id": "pay_QpckxK3eCQr65QznPuuN", "merchant_id": "merchant_1755160879", "status": "requires_confirmation", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_QpckxK3eCQr65QznPuuN_secret_qV2I7iHAdO5nQb9g1NiG", "created": "2025-08-14T08:41:43.016Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_yMCfQBl7o3zcFKRn1moK", "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", "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1755160902, "expires": 1755164502, "secret": "epk_c95c09ba12954fa88c93d7216e216242" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_8SHbxLW1M8ueBNJ7tqAf", "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-08-14T08:56:43.016Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-14T08:41:43.114Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` Payments - Confirm Request: ``` curl --location 'http://localhost:8080/payments/pay_QpckxK3eCQr65QznPuuN/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_nDwiGI0dyLcP8uP4zJj6TPrzetozj6rVGm7o9WV3KZJX4nKVPrB1VaIhnrcUrkXv' \ --data-raw '{ "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "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": "2025-07-25T11:46:12Z" } "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6500, "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "amount": 6500, "currency": "USD" }' ``` Response: ``` { "payment_id": "pay_QpckxK3eCQr65QznPuuN", "merchant_id": "merchant_1755160879", "status": "succeeded", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6500, "connector": "stripe", "client_secret": "pay_QpckxK3eCQr65QznPuuN_secret_qV2I7iHAdO5nQb9g1NiG", "created": "2025-08-14T08:41:43.016Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": "token_yMCfQBl7o3zcFKRn1moK", "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", "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RvwugE9cSvqiivY0X0CxZg6", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pi_3RvwugE9cSvqiivY0X0CxZg6", "payment_link": null, "profile_id": "pro_8SHbxLW1M8ueBNJ7tqAf", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_E0iaiKWU18mDERnGMckX", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-14T08:56:43.016Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-14T08:53:35.933Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` Payments - sync (with old application): Response: ``` { "payment_id": "pay_QpckxK3eCQr65QznPuuN", "merchant_id": "merchant_1755160879", "status": "succeeded", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6500, "connector": "stripe", "client_secret": "pay_QpckxK3eCQr65QznPuuN_secret_qV2I7iHAdO5nQb9g1NiG", "created": "2025-08-14T08:41:43.016Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": [ { "refund_id": "ref_nzAqQ7BbLsGuCu7K00Gm", "payment_id": "pay_QpckxK3eCQr65QznPuuN", "amount": 1000, "currency": "USD", "status": "succeeded", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-08-14T08:55:59.292Z", "updated_at": "2025-08-14T08:56:00.603Z", "connector": "stripe", "profile_id": "pro_8SHbxLW1M8ueBNJ7tqAf", "merchant_connector_id": "mca_E0iaiKWU18mDERnGMckX", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null }, { "refund_id": "ref_KehvNBg796Hhj5AnjLIU", "payment_id": "pay_QpckxK3eCQr65QznPuuN", "amount": 1000, "currency": "USD", "status": "succeeded", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-08-14T09:04:53.067Z", "updated_at": "2025-08-14T09:04:54.257Z", "connector": "stripe", "profile_id": "pro_8SHbxLW1M8ueBNJ7tqAf", "merchant_connector_id": "mca_E0iaiKWU18mDERnGMckX", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ], "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": "token_yMCfQBl7o3zcFKRn1moK", "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", "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RvwugE9cSvqiivY0X0CxZg6", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pi_3RvwugE9cSvqiivY0X0CxZg6", "payment_link": null, "profile_id": "pro_8SHbxLW1M8ueBNJ7tqAf", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_E0iaiKWU18mDERnGMckX", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-14T08:56:43.016Z", "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_channel": null, "payment_method_id": "pm_BOcKiwB3ujDSu3H3yheb", "network_transaction_id": null, "payment_method_status": "active", "updated": "2025-08-14T09:05:00.035Z", "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": "pm_1RvwugE9cSvqiivY5A84TvB3", "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` Payments - Sync (New Application) Response: ``` { "payment_id": "pay_QpckxK3eCQr65QznPuuN", "merchant_id": "merchant_1755160879", "status": "succeeded", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6500, "connector": "stripe", "client_secret": "pay_QpckxK3eCQr65QznPuuN_secret_qV2I7iHAdO5nQb9g1NiG", "created": "2025-08-14T08:41:43.016Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": [ { "refund_id": "ref_nzAqQ7BbLsGuCu7K00Gm", "payment_id": "pay_QpckxK3eCQr65QznPuuN", "amount": 1000, "currency": "USD", "status": "succeeded", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-08-14T08:55:59.292Z", "updated_at": "2025-08-14T08:56:00.603Z", "connector": "stripe", "profile_id": "pro_8SHbxLW1M8ueBNJ7tqAf", "merchant_connector_id": "mca_E0iaiKWU18mDERnGMckX", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null }, { "refund_id": "ref_KehvNBg796Hhj5AnjLIU", "payment_id": "pay_QpckxK3eCQr65QznPuuN", "amount": 1000, "currency": "USD", "status": "succeeded", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-08-14T09:04:53.067Z", "updated_at": "2025-08-14T09:04:54.257Z", "connector": "stripe", "profile_id": "pro_8SHbxLW1M8ueBNJ7tqAf", "merchant_connector_id": "mca_E0iaiKWU18mDERnGMckX", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ], "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": "token_yMCfQBl7o3zcFKRn1moK", "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", "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RvwugE9cSvqiivY0X0CxZg6", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pi_3RvwugE9cSvqiivY0X0CxZg6", "payment_link": null, "profile_id": "pro_8SHbxLW1M8ueBNJ7tqAf", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_E0iaiKWU18mDERnGMckX", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-14T08:56:43.016Z", "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_channel": null, "payment_method_id": "pm_BOcKiwB3ujDSu3H3yheb", "network_transaction_id": null, "payment_method_status": "active", "updated": "2025-08-14T09:05:00.035Z", "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": "pm_1RvwugE9cSvqiivY5A84TvB3", "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` 2. Create + confirm on old version (old and new application should be able to retrieve) Create + Confirm: Response: ``` { "payment_id": "pay_qDAKyiWXL2BToORLLOed", "merchant_id": "merchant_1755163699", "status": "succeeded", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6500, "connector": "stripe", "client_secret": "pay_qDAKyiWXL2BToORLLOed_secret_ApS6p4I8eCgpO7LfReIB", "created": "2025-08-14T09:28:48.465Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1755163728, "expires": 1755167328, "secret": "epk_abc7e336d4c840f1a5ccd8067c76f0d5" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RvxSoE9cSvqiivY0Q00nWP3", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pi_3RvxSoE9cSvqiivY0Q00nWP3", "payment_link": null, "profile_id": "pro_mQ5idcJcr37iO0GmRSQU", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_2lED1Q9w5btK5Tgsx6CB", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-14T09:43:48.465Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-14T09:28:51.204Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` Payments - Sync (on old version) Response: ``` { "payment_id": "pay_qDAKyiWXL2BToORLLOed", "merchant_id": "merchant_1755163699", "status": "succeeded", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6500, "connector": "stripe", "client_secret": "pay_qDAKyiWXL2BToORLLOed_secret_ApS6p4I8eCgpO7LfReIB", "created": "2025-08-14T09:28:48.465Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RvxSoE9cSvqiivY0Q00nWP3", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pi_3RvxSoE9cSvqiivY0Q00nWP3", "payment_link": null, "profile_id": "pro_mQ5idcJcr37iO0GmRSQU", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_2lED1Q9w5btK5Tgsx6CB", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-14T09:43:48.465Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-14T09:29:05.152Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` Payments - Sync (on this branch): Response: ``` { "payment_id": "pay_qDAKyiWXL2BToORLLOed", "merchant_id": "merchant_1755163699", "status": "succeeded", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6500, "connector": "stripe", "client_secret": "pay_qDAKyiWXL2BToORLLOed_secret_ApS6p4I8eCgpO7LfReIB", "created": "2025-08-14T09:28:48.465Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RvxSoE9cSvqiivY0Q00nWP3", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pi_3RvxSoE9cSvqiivY0Q00nWP3", "payment_link": null, "profile_id": "pro_mQ5idcJcr37iO0GmRSQU", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_2lED1Q9w5btK5Tgsx6CB", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-14T09:43:48.465Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-14T09:29:05.152Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` 3. Manually override the db enum to store Default and see if the new and old application can retrieve it Payments - Create Response: ``` { "payment_id": "pay_RbtTfVKPmNN6AipdXDBy", "merchant_id": "merchant_1755163699", "status": "requires_capture", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 6500, "amount_received": 0, "connector": "stripe", "client_secret": "pay_RbtTfVKPmNN6AipdXDBy_secret_KgqxaJ94DXsIMOOhWNez", "created": "2025-08-14T10:04:50.873Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1755165890, "expires": 1755169490, "secret": "epk_c08c26656b7d437e9c2bfc248bc39ab3" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3Rvy1gE9cSvqiivY1bcNshY0", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pi_3Rvy1gE9cSvqiivY1bcNshY0", "payment_link": null, "profile_id": "pro_mQ5idcJcr37iO0GmRSQU", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_2lED1Q9w5btK5Tgsx6CB", "incremental_authorization_allowed": true, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-14T10:19:50.873Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-14T10:04:52.820Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` Payments - Sync (on this branch, after changing the value of request_incremental_authorization to default and incremental_authorization_allowed to true): <img width="1259" height="583" alt="Screenshot 2025-08-14 at 3 44 16β€―PM" src="https://github.com/user-attachments/assets/5d8d45e6-a843-47b7-86e4-314b23502c9c" /> Response: ``` { "payment_id": "pay_RbtTfVKPmNN6AipdXDBy", "merchant_id": "merchant_1755163699", "status": "requires_capture", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 6500, "amount_received": 0, "connector": "stripe", "client_secret": "pay_RbtTfVKPmNN6AipdXDBy_secret_KgqxaJ94DXsIMOOhWNez", "created": "2025-08-14T10:04:50.873Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3Rvy1gE9cSvqiivY1bcNshY0", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pi_3Rvy1gE9cSvqiivY1bcNshY0", "payment_link": null, "profile_id": "pro_mQ5idcJcr37iO0GmRSQU", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_2lED1Q9w5btK5Tgsx6CB", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-14T10:19:50.873Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-14T10:07:49.655Z", "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": "pm_1Rvy1gE9cSvqiivYCvmNitR6", "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` Payments - Sync (on old version): Response: ``` { "payment_id": "pay_yySze0C1AcjjVbTE3ecr", "merchant_id": "merchant_1755163699", "status": "requires_capture", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 6500, "amount_received": 0, "connector": "stripe", "client_secret": "pay_yySze0C1AcjjVbTE3ecr_secret_GI3GZQZxrsMa6bdmnSZD", "created": "2025-08-14T10:26:23.998Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RvyMWE9cSvqiivY16aXbZ8T", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pi_3RvyMWE9cSvqiivY16aXbZ8T", "payment_link": null, "profile_id": "pro_mQ5idcJcr37iO0GmRSQU", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_2lED1Q9w5btK5Tgsx6CB", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-14T10:41:23.998Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-14T10:29:43.256Z", "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": "pm_1RvyMWE9cSvqiivYxCV2kKOB", "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": 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.116.0
a0a4b9239dd2fff7a79fabe641ed9f71f56ef254
a0a4b9239dd2fff7a79fabe641ed9f71f56ef254
juspay/hyperswitch
juspay__hyperswitch-8945
Bug: [BUG] Webhook source verification is `false` for NMI [Connector documentation](https://docs.nmi.com/reference/overview) php example says this: ```php function webhookIsVerified($webhookBody, $signingKey, $nonce, $sig) { return $sig === hash_hmac("sha256", $nonce . "." . $webhookBody, $signingKey); } try { $signingKey = "YOUR_SIGNING_KEY_HERE"; $webhookBody = file_get_contents("php://input"); $headers = getallheaders(); $sigHeader = $headers['Webhook-Signature']; if (!is_null($sigHeader) && strlen($sigHeader) < 1) { throw new Exception("invalid webhook - signature header missing"); } if (preg_match('/t=(.*),s=(.*)/', $sigHeader, $matches)) { $nonce = $matches[1]; $signature = $matches[2]; } else { throw new Exception("unrecognized webhook signature format"); } if (!webhookIsVerified($webhookBody, $signingKey, $nonce, $signature)) { throw new Exception("invalid webhook - invalid signature, cannot verify sender"); } // webhook is now verified to have been sent by us, continue processing echo "webhook is verified"; $webhook = json_decode($webhookBody); var_export($webhook); } catch (Exception $e) { echo "error: $e\n"; } ``` In Hyperswitch code: `signature` and `nonce` extraction is wrong. We are extracting `nonce` instead of the signature from the `Webhook-Signature` header and the entire match instead of just the `nonce` value here: - `captures.get(0)` -- entire match instead of nonce, because 0 contains entire regex match - `captures.get(1)` -- nonce instead of signature
diff --git a/crates/hyperswitch_connectors/src/connectors/nmi.rs b/crates/hyperswitch_connectors/src/connectors/nmi.rs index 7ae21664e73..50e5db86e5a 100644 --- a/crates/hyperswitch_connectors/src/connectors/nmi.rs +++ b/crates/hyperswitch_connectors/src/connectors/nmi.rs @@ -9,6 +9,7 @@ use common_utils::{ types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; +use hex; use hyperswitch_domain_models::{ router_data::{AccessToken, ErrorResponse, RouterData}, router_flow_types::{ @@ -859,13 +860,15 @@ impl IncomingWebhook for Nmi { .captures(sig_header) { let signature = captures - .get(1) + .get(2) .ok_or(ConnectorError::WebhookSignatureNotFound)? .as_str(); - return Ok(signature.as_bytes().to_vec()); - } - Err(report!(ConnectorError::WebhookSignatureNotFound)) + // Decode hex signature to bytes + hex::decode(signature).change_context(ConnectorError::WebhookSignatureNotFound) + } else { + Err(report!(ConnectorError::WebhookSignatureNotFound)) + } } fn get_webhook_source_verification_message( @@ -883,15 +886,16 @@ impl IncomingWebhook for Nmi { .captures(sig_header) { let nonce = captures - .get(0) + .get(1) .ok_or(ConnectorError::WebhookSignatureNotFound)? .as_str(); let message = format!("{}.{}", nonce, String::from_utf8_lossy(request.body)); - return Ok(message.into_bytes()); + Ok(message.into_bytes()) + } else { + Err(report!(ConnectorError::WebhookSignatureNotFound)) } - Err(report!(ConnectorError::WebhookSignatureNotFound)) } fn get_webhook_object_reference_id(
2025-08-13T14:43:55Z
## 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 problem is that we previously extracted `nonce` instead of `signature` and entire regex match instead of `nonce`. this pr fixes webhook source verification for nmi connector by properly extracting `signature` (`2`) and `nonce` (`1`) values. check attached issue for detailed explanation. ### 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). --> webhook source verification must not be `false` unless connector does not support it. in this case, it was a mistake from our end where we parsed wrong values. closes https://github.com/juspay/hyperswitch/issues/8945 ## 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)? --> <details> <summary>Setup webhooks for NMI connector and also the signature verification</summary> <img width="1212" height="130" alt="image" src="https://github.com/user-attachments/assets/3759cb84-57f6-441e-845e-d6c53868764a" /> <img width="385" height="30" alt="image" src="https://github.com/user-attachments/assets/2df31bc8-54a4-4779-b112-433526318be3" /> <img width="193" height="55" alt="image" src="https://github.com/user-attachments/assets/eeb4287f-e309-49b0-9943-19334a8c7994" /> </details> <details> <summary>Make a Payment</summary> ```curl curl --location 'https://pix-mbp.orthrus-monster.ts.net/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_A3aKSnvxEuazXkjOdUMlrNTSpmIlH9MlaWJj9Ax9xEpFqGN4aVBUGINJjkjSlRdz' \ --data-raw '{ "amount": 60159, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 60159, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4111111111111111", "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": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "payment_id": "pay_46yfYfNcSmMZ847bso0p", "merchant_id": "postman_merchant_GHAction_1755093166", "status": "succeeded", "amount": 15429, "net_amount": 15429, "shipping_cost": null, "amount_capturable": 0, "amount_received": 15429, "connector": "nmi", "client_secret": "pay_46yfYfNcSmMZ847bso0p_secret_55lzxYdXlKlBI80u1Y8w", "created": "2025-08-13T14:25:56.929Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "JP Morgan", "card_issuing_country": "INDIA", "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_0k7Cgt2Xh8LXsZAxF3gz", "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, "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null, "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1755095156, "expires": 1755098756, "secret": "epk_12014a82ba5c4c97980e8e0ff9a64b7a" }, "manual_retry_allowed": false, "connector_transaction_id": "11025492335", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_46yfYfNcSmMZ847bso0p_1", "payment_link": null, "profile_id": "pro_9TabQmBmCO93BbyuDbqZ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_kMejAtGh3Rsbobtc3dOq", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-13T14:40:56.929Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-13T14:25:58.919Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details> <details> <summary>In logs, source verified should be true</summary> ```log 2025-08-13T14:25:59.722386Z INFO router::core::webhooks::incoming: source_verified: true at crates/router/src/core/webhooks/incoming.rs:597 in router::core::webhooks::incoming::incoming_webhooks_core in router::services::api::server_wrap_util with flow: IncomingWebhookReceive, lock_action: NotApplicable, merchant_id: "postman_merchant_GHAction_1755093166" in router::services::api::server_wrap with flow: IncomingWebhookReceive, lock_action: NotApplicable, request_method: "POST", request_url_path: "/webhooks/postman_merchant_GHAction_1755093166/nmi" in router::routes::webhooks::receive_incoming_webhook with flow: IncomingWebhookReceive in router::middleware::ROOT_SPAN with flow: "UNKNOWN" ``` </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 `just clippy && just clippy_v2` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.116.0
6950c04eaebc0499040556d8bbf5c684aebd2c9e
6950c04eaebc0499040556d8bbf5c684aebd2c9e
juspay/hyperswitch
juspay__hyperswitch-8928
Bug: [BUG] Fix incorrect consumer authenttication information fields ### Bug Description Fix consumer authenttication information request field 1. Rename consumer_authentication_information.pares_status_reason field to consumer_authentication_information.signed_pares_status_reason 2. Move cavv_algorithm from processing_information to consumer_authentication_information ### Expected Behavior n/a ### Actual Behavior Request field struct is correctly incorrect for consumer_authentication_information - - pares_status_reason - cavv_algorithm ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index f080a76b051..ca41d12e9b8 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -335,7 +335,6 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest { ))? } }; - let cavv_algorithm = Some("2".to_string()); let processing_information = ProcessingInformation { capture: Some(false), @@ -345,7 +344,6 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest { authorization_options, commerce_indicator: String::from("internet"), payment_solution: solution.map(String::from), - cavv_algorithm, }; Ok(Self { processing_information, @@ -379,7 +377,6 @@ pub struct ProcessingInformation { capture: Option<bool>, capture_options: Option<CaptureOptions>, payment_solution: Option<String>, - cavv_algorithm: Option<String>, } #[derive(Debug, Serialize)] @@ -425,13 +422,15 @@ pub struct CybersourceConsumerAuthInformation { /// This field indicates the authentication type or challenge presented to the cardholder at checkout. challenge_code: Option<String>, /// This field indicates the reason for payer authentication response status. It is only supported for secure transactions in France. - pares_status_reason: Option<String>, + signed_pares_status_reason: Option<String>, /// This field indicates the reason why strong authentication was cancelled. It is only supported for secure transactions in France. challenge_cancel_code: Option<String>, /// This field indicates the score calculated by the 3D Securing platform. It is only supported for secure transactions in France. network_score: Option<u32>, /// This is the transaction ID generated by the access control server. This field is supported only for secure transactions in France. acs_transaction_id: Option<String>, + /// This is the algorithm for generating a cardholder authentication verification value (CAVV) or universal cardholder authentication field (UCAF) data. + cavv_algorithm: Option<String>, } #[derive(Debug, Serialize)] @@ -1007,11 +1006,6 @@ impl .map(|eci| get_commerce_indicator_for_external_authentication(network, eci)) }); - // The 3DS Server might not include the `cavvAlgorithm` field in the challenge response. - // In such cases, we default to "2", which represents the CVV with Authentication Transaction Number (ATN) algorithm. - // This is the most commonly used value for 3DS 2.0 transactions (e.g., Visa, Mastercard). - let cavv_algorithm = Some("2".to_string()); - Ok(Self { capture: Some(matches!( item.router_data.request.capture_method, @@ -1024,7 +1018,6 @@ impl capture_options: None, commerce_indicator: commerce_indicator_for_external_authentication .unwrap_or(commerce_indicator), - cavv_algorithm, }) } } @@ -1121,7 +1114,6 @@ impl } else { (None, None, None) }; - let cavv_algorithm = Some("2".to_string()); Ok(Self { capture: Some(matches!( @@ -1137,7 +1129,6 @@ impl .indicator .to_owned() .unwrap_or(String::from("internet")), - cavv_algorithm, }) } } @@ -1456,6 +1447,11 @@ impl .and_then(|exts| extract_score_id(&exts)) }); + // The 3DS Server might not include the `cavvAlgorithm` field in the challenge response. + // In such cases, we default to "2", which represents the CVV with Authentication Transaction Number (ATN) algorithm. + // This is the most commonly used value for 3DS 2.0 transactions (e.g., Visa, Mastercard). + let cavv_algorithm = Some("2".to_string()); + CybersourceConsumerAuthInformation { pares_status, ucaf_collection_indicator, @@ -1473,10 +1469,11 @@ impl authentication_date, effective_authentication_type, challenge_code: authn_data.challenge_code.clone(), - pares_status_reason: authn_data.challenge_code_reason.clone(), + signed_pares_status_reason: authn_data.challenge_code_reason.clone(), challenge_cancel_code: authn_data.challenge_cancel.clone(), network_score, acs_transaction_id: authn_data.acs_trans_id.clone(), + cavv_algorithm, } }); @@ -1577,6 +1574,8 @@ impl .and_then(|exts| extract_score_id(&exts)) }); + let cavv_algorithm = Some("2".to_string()); + CybersourceConsumerAuthInformation { pares_status, ucaf_collection_indicator, @@ -1594,10 +1593,11 @@ impl authentication_date, effective_authentication_type, challenge_code: authn_data.challenge_code.clone(), - pares_status_reason: authn_data.challenge_code_reason.clone(), + signed_pares_status_reason: authn_data.challenge_code_reason.clone(), challenge_cancel_code: authn_data.challenge_cancel.clone(), network_score, acs_transaction_id: authn_data.acs_trans_id.clone(), + cavv_algorithm, } }); @@ -1702,6 +1702,8 @@ impl .and_then(|exts| extract_score_id(&exts)) }); + let cavv_algorithm = Some("2".to_string()); + CybersourceConsumerAuthInformation { pares_status, ucaf_collection_indicator, @@ -1719,10 +1721,11 @@ impl authentication_date, effective_authentication_type, challenge_code: authn_data.challenge_code.clone(), - pares_status_reason: authn_data.challenge_code_reason.clone(), + signed_pares_status_reason: authn_data.challenge_code_reason.clone(), challenge_cancel_code: authn_data.challenge_cancel.clone(), network_score, acs_transaction_id: authn_data.acs_trans_id.clone(), + cavv_algorithm, } }); @@ -1907,10 +1910,11 @@ impl authentication_date: None, effective_authentication_type: None, challenge_code: None, - pares_status_reason: None, + signed_pares_status_reason: None, challenge_cancel_code: None, network_score: None, acs_transaction_id: None, + cavv_algorithm: None, }); let merchant_defined_information = item @@ -2014,10 +2018,11 @@ impl authentication_date: None, effective_authentication_type: None, challenge_code: None, - pares_status_reason: None, + signed_pares_status_reason: None, challenge_cancel_code: None, network_score: None, acs_transaction_id: None, + cavv_algorithm: None, }), merchant_defined_information, }) @@ -2166,10 +2171,11 @@ impl authentication_date: None, effective_authentication_type: None, challenge_code: None, - pares_status_reason: None, + signed_pares_status_reason: None, challenge_cancel_code: None, network_score: None, acs_transaction_id: None, + cavv_algorithm: None, }), merchant_defined_information, }) @@ -2384,10 +2390,11 @@ impl TryFrom<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for Cybersour authentication_date: None, effective_authentication_type: None, challenge_code: None, - pares_status_reason: None, + signed_pares_status_reason: None, challenge_cancel_code: None, network_score: None, acs_transaction_id: None, + cavv_algorithm: None, }, ), }) @@ -2658,7 +2665,6 @@ impl TryFrom<&CybersourceRouterData<&PaymentsCaptureRouterData>> ) .then_some(true); - let cavv_algorithm = Some("2".to_string()); Ok(Self { processing_information: ProcessingInformation { capture_options: Some(CaptureOptions { @@ -2672,7 +2678,6 @@ impl TryFrom<&CybersourceRouterData<&PaymentsCaptureRouterData>> capture: None, commerce_indicator: String::from("internet"), payment_solution: None, - cavv_algorithm, }, order_information: OrderInformationWithBill { amount_details: Amount { @@ -2698,7 +2703,6 @@ impl TryFrom<&CybersourceRouterData<&PaymentsIncrementalAuthorizationRouterData> ) -> Result<Self, Self::Error> { let connector_merchant_config = CybersourceConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?; - let cavv_algorithm = Some("2".to_string()); Ok(Self { processing_information: ProcessingInformation { @@ -2722,7 +2726,6 @@ impl TryFrom<&CybersourceRouterData<&PaymentsIncrementalAuthorizationRouterData> capture: None, capture_options: None, payment_solution: None, - cavv_algorithm, }, order_information: OrderInformationIncrementalAuthorization { amount_details: AdditionalAmount {
2025-08-12T11:56:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Fix consumer authenttication information fields 1. Renamed _consumer_authentication_information.pares_status_reason_ field to _consumer_authentication_information.signed_pares_status_reason_ 2. Moved _cavv_algorithm_ from _processing_information_ to _consumer_authentication_information_ Verified with cybersouce api spec <img width="531" height="634" alt="Screenshot 2025-08-12 at 5 24 33β€―PM" src="https://github.com/user-attachments/assets/4e8a1c93-1827-4991-b750-6449f52398fe" /> <img width="416" height="487" alt="Screenshot 2025-08-12 at 5 24 58β€―PM" src="https://github.com/user-attachments/assets/e80e3233-26ba-49f7-90af-4e2bce65456c" /> ### 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` 3. `crates/router/src/configs` 4. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with 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)? --> Steps: 1. Do a 3ds payment via cybersource and netcetera 2. Check cybersource request fields for signed_pares_status_reason, cavv_algorithm <img width="1496" height="359" alt="Screenshot 2025-08-12 at 5 22 54β€―PM" src="https://github.com/user-attachments/assets/82bcb9fc-4a0f-4dcf-a45b-fb7f6c4530c9" /> ## 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.116.0
9de83ee767a14213ae114a6215d4c9e18df767f1
9de83ee767a14213ae114a6215d4c9e18df767f1
juspay/hyperswitch
juspay__hyperswitch-8934
Bug: Update traditional chinese locale for payent link expired Update traditional chinese locale for payent link expired
diff --git a/crates/router/src/core/payment_link/locale.js b/crates/router/src/core/payment_link/locale.js index 5a404c93a5b..e07285a1ef8 100644 --- a/crates/router/src/core/payment_link/locale.js +++ b/crates/router/src/core/payment_link/locale.js @@ -586,7 +586,7 @@ const locales = { }, zh_hant: { expiresOn: "ι€£η΅εˆ°ζœŸζ—₯期:", - refId: "εƒθ€ƒη·¨θ™ŸοΌš", + refId: "εƒθ€ƒη·¨θ™Ÿ", requestedBy: "請求者 ", payNow: "η«‹ε³δ»˜ζ¬Ύ", addPaymentMethod: "ζ–°ε’žδ»˜ζ¬Ύζ–ΉεΌ", @@ -600,7 +600,7 @@ const locales = { paymentTakingLonger: "ζŠ±ζ­‰οΌζ‚¨ηš„δ»˜ζ¬Ύθ™•η†ζ™‚ι–“ζ―”ι ζœŸι•·γ€‚θ«‹η¨εΎŒε†ζŸ₯ηœ‹γ€‚", paymentLinkExpired: "δ»˜ζ¬Ύι€£η΅ε·²ιŽζœŸ", paymentReceived: "ζˆ‘ε€‘ε·²ζˆεŠŸζ”Άεˆ°ζ‚¨ηš„δ»˜ζ¬Ύ", - paymentLinkExpiredMessage: "ζŠ±ζ­‰οΌŒζ­€δ»˜ζ¬Ύι€£η΅ε·²ιŽζœŸγ€‚θ«‹δ½Ώη”¨δ»₯δΈ‹εƒθ€ƒι€²θ‘Œι€²δΈ€ζ­₯θͺΏζŸ₯。", + paymentLinkExpiredMessage: "ζŠ±ζ­‰οΌŒζ­€ζ”―δ»˜ι“ΎζŽ₯ε·²θΏ‡ζœŸγ€‚ 请使用δ»₯δΈ‹ε‚θ€ƒθΏ›θ‘ŒθΏ›δΈ€ζ­₯θ°ƒζŸ₯。", paidSuccessfully: "付款成功", paymentPending: "δ»˜ζ¬ΎεΎ…θ™•η†", paymentFailed: "δ»˜ζ¬Ύε€±ζ•—οΌ",
2025-08-12T16:23:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> We need to update traditional chinese locale for payment link expired. ### 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). --> Raised by the merchant to update the locale to the correct one as shared by them. ## 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)? --> use below curl for payment link create and wait for 60 secs for payment link to get expired: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ***' \ --header 'Accept-Language: zh-Hant' \ --data '{ "amount": 10, "setup_future_usage": "off_session", "currency": "EUR", "payment_link": true, "session_expiry": 60, "return_url": "https://google.com", "payment_link_config": { "theme": "#14356f", "logo": "https://logo.com/wp-content/uploads/2020/08/zurich.svg", "seller_name": "Zurich Inc." } }' ``` <img width="2560" height="1440" alt="image" src="https://github.com/user-attachments/assets/8c4e4fcb-f5ab-4988-b559-5712e5f9f473" /> ## 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.116.0
a0c2a6bc823fdeac193875a04ea04e7d9a81cbc2
a0c2a6bc823fdeac193875a04ea04e7d9a81cbc2
juspay/hyperswitch
juspay__hyperswitch-8931
Bug: [FIX] : refund sync process scheduled time refund sync process scheduled time
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index ed44f61b4da..3d8463c2554 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; #[cfg(feature = "olap")] use api_models::admin::MerchantConnectorInfo; use common_utils::{ - ext_traits::AsyncExt, + ext_traits::{AsyncExt, StringExt}, types::{ConnectorTransactionId, MinorUnit}, }; use diesel_models::{process_tracker::business_status, refund as diesel_refund}; @@ -14,7 +14,9 @@ use hyperswitch_domain_models::{ }; use hyperswitch_interfaces::integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject}; use router_env::{instrument, tracing}; -use scheduler::{consumer::types::process_data, utils as process_tracker_utils}; +use scheduler::{ + consumer::types::process_data, errors as sch_errors, utils as process_tracker_utils, +}; #[cfg(feature = "olap")] use strum::IntoEnumIterator; @@ -40,7 +42,6 @@ use crate::{ transformers::{ForeignFrom, ForeignInto}, }, utils::{self, OptionExt}, - workflows::payment_sync, }; // ********************************************** REFUND EXECUTE ********************************************** @@ -1439,7 +1440,7 @@ pub async fn sync_refund_with_gateway_workflow( .await? } _ => { - _ = payment_sync::retry_sync_task( + _ = retry_refund_sync_task( &*state.store, response.connector, response.merchant_id, @@ -1452,6 +1453,33 @@ pub async fn sync_refund_with_gateway_workflow( Ok(()) } +/// Schedule the task for refund retry +/// +/// Returns bool which indicates whether this was the last refund retry or not +pub async fn retry_refund_sync_task( + db: &dyn db::StorageInterface, + connector: String, + merchant_id: common_utils::id_type::MerchantId, + pt: storage::ProcessTracker, +) -> Result<bool, sch_errors::ProcessTrackerError> { + let schedule_time = + get_refund_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1) + .await?; + + match schedule_time { + Some(s_time) => { + db.as_scheduler().retry_process(pt, s_time).await?; + Ok(false) + } + None => { + db.as_scheduler() + .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED) + .await?; + Ok(true) + } + } +} + #[instrument(skip_all)] pub async fn start_refund_workflow( state: &SessionState, @@ -1614,7 +1642,12 @@ pub async fn add_refund_sync_task( ) -> RouterResult<storage::ProcessTracker> { let task = "SYNC_REFUND"; let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id); - let schedule_time = common_utils::date_time::now(); + let schedule_time = + get_refund_sync_process_schedule_time(db, &refund.connector, &refund.merchant_id, 0) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch schedule time for refund sync process")? + .unwrap_or_else(common_utils::date_time::now); let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); let tag = ["REFUND"]; let process_tracker_entry = storage::ProcessTrackerNew::new( @@ -1688,15 +1721,20 @@ pub async fn get_refund_sync_process_schedule_time( merchant_id: &common_utils::id_type::MerchantId, retry_count: i32, ) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { - let redis_mapping: errors::CustomResult<process_data::ConnectorPTMapping, errors::RedisError> = - db::get_and_deserialize_key( - db, - &format!("pt_mapping_refund_sync_{connector}"), - "ConnectorPTMapping", - ) - .await; - - let mapping = match redis_mapping { + let mapping: common_utils::errors::CustomResult< + process_data::ConnectorPTMapping, + errors::StorageError, + > = db + .find_config_by_key(&format!("pt_mapping_refund_sync_{connector}")) + .await + .map(|value| value.config) + .and_then(|config| { + config + .parse_struct("ConnectorPTMapping") + .change_context(errors::StorageError::DeserializationFailed) + }); + + let mapping = match mapping { Ok(x) => x, Err(err) => { logger::error!("Error: while getting connector mapping: {err:?}"); @@ -1704,8 +1742,7 @@ pub async fn get_refund_sync_process_schedule_time( } }; - let time_delta = - process_tracker_utils::get_schedule_time(mapping, merchant_id, retry_count + 1); + let time_delta = process_tracker_utils::get_schedule_time(mapping, merchant_id, retry_count); Ok(process_tracker_utils::get_time_from_delta(time_delta)) }
2025-08-12T14:24:25Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Before refund sync process tracker task was using pt_mapping_{connector} for sync retries (this is config name of Psync which was incorrect) Fixes made in this PR - - We are using pt_mapping_refund_sync_{connector} - refund sync which was using retry_sync_task so made retry_refund_sync_task which will handle the refund task - fix refund sync workflow being incorrectly scheduled for 2nd retry attempt instead of 1st retry attempt - ConnectorPTMapping should also be read from db , previously we were always reading only from redis ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Create a process tracker config for Adyen connector ``` curl --location 'http://localhost:8080/configs/pt_mapping_refund_sync_adyen' \ --header 'Content-Type: application/json' \ --header 'api-key: _____' \ --data '{ "key": "pt_mapping_refund_sync_adyen", "value": "{\"custom_merchant_mapping\":{},\"default_mapping\":{\"start_after\":180,\"frequencies\":[[20,2],[30,2],[40,2],[60,2],[2400,1],[43200,4],[86400,3],[345600,2]]},\"max_retries_count\":18}" }' ``` Response ``` { "key": "pt_mapping_refund_sync_adyen", "value": "{\"custom_merchant_mapping\":{},\"default_mapping\":{\"start_after\":180,\"frequencies\":[[20,2],[30,2],[40,2],[60,2],[2400,1],[43200,4],[86400,3],[345600,2]]},\"max_retries_count\":18}" } ``` Create a no 3ds card payment via Adyen ``` { "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "metadata": { "order_id": "ORD-12345", "sdata": { "customer_segment": "premium", "purchase_platform": "web_store" } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "merchant_order_reference_id": "order_narvar12", "browser_info": { "os_type": "macOS", "language": "en-GB", "time_zone": -330, "ip_address": "103.159.11.202", "os_version": "10.15.7", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36", "color_depth": 24, "device_model": "Macintosh", "java_enabled": true, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1080, "accept_language": "en", "java_script_enabled": true }, "profile_id": "{{payment_profile_id}}" } ``` Response ``` { "payment_id": "pay_PuKa9OvV1e3yrcdZcfEo", "merchant_id": "merchant_1755523756", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "adyen", "client_secret": "pay_PuKa9OvV1e3yrcdZcfEo_secret_V1Yu4MdVf3iEhwKygr0H", "created": "2025-08-19T06:21:08.206Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "JP Morgan", "card_issuing_country": "INDIA", "card_isin": "411111", "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, "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null, "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1755584468, "expires": 1755588068, "secret": "epk_eadaf298af8f4d58b46ac00860f9e440" }, "manual_retry_allowed": false, "connector_transaction_id": "HH2TDB3NBZXRHBV5", "frm_message": null, "metadata": { "sdata": { "customer_segment": "premium", "purchase_platform": "web_store" }, "order_id": "ORD-12345" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_PuKa9OvV1e3yrcdZcfEo_1", "payment_link": null, "profile_id": "pro_IBcsy1G8u4AqtpDlpoQ6", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_ST0rQKrUA8r95Bvci4FV", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-19T06:36:08.206Z", "fingerprint": null, "browser_info": { "os_type": "macOS", "language": "en-GB", "time_zone": -330, "ip_address": "103.159.11.202", "os_version": "10.15.7", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36", "color_depth": 24, "device_model": "Macintosh", "java_enabled": true, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1080, "accept_language": "en", "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-19T06:21:11.290Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": "order_narvar12", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` Create a Refund Request ``` { "payment_id": "{{payment_id}}", "amount": 600, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ``` Response ``` { "refund_id": "ref_ItP2mAScOD5yeWYmsgWA", "payment_id": "pay_PuKa9OvV1e3yrcdZcfEo", "amount": 600, "currency": "USD", "status": "pending", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-08-19T06:21:25.378Z", "updated_at": "2025-08-19T06:21:25.738Z", "connector": "adyen", "profile_id": "pro_IBcsy1G8u4AqtpDlpoQ6", "merchant_connector_id": "mca_ST0rQKrUA8r95Bvci4FV", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ``` In db search for this refund id `select * from refund where refund_id = 'ref_ItP2mAScOD5yeWYmsgWA';` We will get internal_reference_id | refid_DFtahM9L64gRSkyzkibF <img width="964" height="715" alt="Screenshot 2025-08-19 at 11 57 31β€―AM" src="https://github.com/user-attachments/assets/c237e56e-f6a2-4ad0-b82c-e462f3f90017" /> Using this internal_reference_id we will check in process_tracker table to check the scheduled time `select * from process_tracker where id like '%refid_DFtahM9L64gRSkyzkibF%';` We can scheduled time is 3min after updated_at as in config start_after time was set 180 sec <img width="1124" height="349" alt="Screenshot 2025-08-19 at 11 57 58β€―AM" src="https://github.com/user-attachments/assets/59250474-a27c-4815-8598-ca8ade392121" /> After 3 min if we check process_tracker scheduled time is 20sec min after updated_at as in config 1st frequency was set 20 sec <img width="1252" height="344" alt="Screenshot 2025-08-19 at 12 01 19β€―PM" src="https://github.com/user-attachments/assets/650b5b2f-f16b-4eae-a8ab-9ddc513925a0" /> ## 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.116.0
a0c2a6bc823fdeac193875a04ea04e7d9a81cbc2
a0c2a6bc823fdeac193875a04ea04e7d9a81cbc2
juspay/hyperswitch
juspay__hyperswitch-8924
Bug: [BUG] TrustPay Connector: Request Reference ID Length Validation Issue ### Bug Description Bug Description: Summary: The TrustPay connector implementation fails when the connector_request_reference_id exceeds TrustPay's API limits for merchant reference fields. Impact: - Payment requests may be rejected by TrustPay API due to reference ID length violations Proposed Fix: - Add connector-specific validation in the transformer methods ### Expected Behavior -TrustPay connector should validate connector_request_reference_id length against TrustPay's API requirements before sending requests - Generate a shorter alternative reference ID ### Actual Behavior - Reference IDs up to 64 characters (Hyperswitch limit) are passed through without consideration of TrustPay limits but The length of receipt for Trustpay order request should not exceed 35 characters. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay.rs b/crates/hyperswitch_connectors/src/connectors/trustpay.rs index d3a6a2cdf71..878c4ed0c1c 100644 --- a/crates/hyperswitch_connectors/src/connectors/trustpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/trustpay.rs @@ -1364,4 +1364,13 @@ impl ConnectorSpecifications for Trustpay { fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&TRUSTPAY_SUPPORTED_WEBHOOK_FLOWS) } + #[cfg(feature = "v2")] + fn generate_connector_request_reference_id( + &self, + _payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, + _payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, + ) -> String { + // The length of receipt for Trustpay order request should not exceed 35 characters. + uuid::Uuid::now_v7().simple().to_string() + } }
2025-08-12T11:08:39Z
## 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 length of receipt for Trustpay order request should not exceed 35 characters. So added generate_connector_request_reference_id specific to trustpay which generates less than 35 charcters. ### 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). --> TrustPay API rejects payment requests when the reference field exceeds 35 characters, causing payment failures so now after this it generates uuid of 35 character for reference field specific to trustpay. ## 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)? --> PaymentCreateIntent ``` { "amount_details": { "order_amount": 10000, "currency": "USD" }, "capture_method":"automatic", "customer_id": "{{customer_id}}", "authentication_type": "no_three_ds", "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" }, "email": "example@example.com" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "email": "example@example.com" } } ``` Response: ``` { "id": "12345_pay_01989df58ff572d3b6b44f2b110eed5d", "status": "requires_payment_method", "amount_details": { "order_amount": 10000, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": "cs_01989df590017d239418f1f4e74544b6", "profile_id": "pro_FUMMIiBgcHOyCYD5Fcy5", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "automatic", "authentication_type": "no_three_ds", "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", "origin_zip": null }, "phone": null, "email": "example@example.com" }, "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", "origin_zip": null }, "phone": null, "email": "example@example.com" }, "customer_id": "12345_cus_01989df586017c72a786fa20899c15ed", "customer_present": "present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": null, "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "false", "expires_on": "2025-08-12T11:21:12.862Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip" } ``` Confirm-intent: ``` { "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "26", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit", "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "accept_header": "text\\/html,application\\/xhtml+xml,application\\/xml;q=0.9,image\\/webp,image\\/apng,*\\/*;q=0.8", "language": "en-GB", "color_depth": 24, "screen_height": 1440, "screen_width": 2560, "time_zone": -330, "java_enabled": true, "java_script_enabled": true, "ip_address": "0.0.0.0" } } ``` Response: ``` { "id": "12345_pay_01989df58ff572d3b6b44f2b110eed5d", "status": "succeeded", "amount": { "order_amount": 10000, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 10000, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": 10000 }, "customer_id": "12345_cus_01989df586017c72a786fa20899c15ed", "connector": "trustpay", "created": "2025-08-12T11:06:12.862Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": "SV8ChATq2PXphJpZCzkK2A", "connector_reference_id": null, "merchant_connector_id": "mca_VLpyWHJKJ36kuAYfbmcW", "browser_info": null, "error": null, "shipping": null, "billing": null, "attempts": null, "connector_token_details": null, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds", "is_iframe_redirection_enabled": null, "merchant_reference_id": null, "raw_connector_response": null, "feature_metadata": null } ``` <img width="720" height="167" alt="image" src="https://github.com/user-attachments/assets/bc21eb59-5c41-422b-8e96-849b6d19b00f" /> ## 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.116.0
f79cf784c15df183b11c4b8ad4a3523e9b5c2280
f79cf784c15df183b11c4b8ad4a3523e9b5c2280
juspay/hyperswitch
juspay__hyperswitch-8919
Bug: [CHORE] fix typos in the repo there exist a few typos in the repo.
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 3bdc756dc89..2e70e1a6c95 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -3002,7 +3002,7 @@ pub struct ProfileUpdate { #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, - /// Inidcates the state of revenue recovery algorithm type + /// Indicates the state of revenue recovery algorithm type #[schema(value_type = Option<RevenueRecoveryAlgorithmType>, example = "cascading")] pub revenue_recovery_retry_algorithm_type: Option<common_enums::enums::RevenueRecoveryAlgorithmType>, diff --git a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs index 1b8e2a65057..8444c7b9dd3 100644 --- a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs @@ -188,7 +188,7 @@ impl ds_trans_id: response.authentication_response.ds_trans_id, eci: response.eci, challenge_code, - challenge_cancel: None, // Note - challenge_cancel field is recieved in the RReq and updated in DB during external_authentication_incoming_webhook_flow + challenge_cancel: None, // Note - challenge_cancel field is received in the RReq and updated in DB during external_authentication_incoming_webhook_flow challenge_code_reason: response.authentication_response.trans_status_reason, message_extension, }) diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rs index 3c7a081d41f..22c1681be04 100644 --- a/crates/router/src/core/payments/routing/utils.rs +++ b/crates/router/src/core/payments/routing/utils.rs @@ -420,14 +420,14 @@ pub async fn decision_engine_routing( return Ok(Vec::default()); }; - let de_output_conenctor = extract_de_output_connectors(de_euclid_response.output) + let de_output_connector = extract_de_output_connectors(de_euclid_response.output) .map_err(|e| { logger::error!(error=?e, "decision_engine_euclid_evaluation_error: Failed to extract connector from Output"); e })?; transform_de_output_for_router( - de_output_conenctor.clone(), + de_output_connector.clone(), de_euclid_response.evaluated_output.clone(), ) .map_err(|e| {
2025-08-12T08:11:51Z
## 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 fixes typos. ### 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). --> fix typos in the repo. closes https://github.com/juspay/hyperswitch/issues/8919 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> nothing to test. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `just clippy && just clippy_v2` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.116.0
8bb8b2062e84e8d7116a9ca0e76c8ebd71b2b3ec
8bb8b2062e84e8d7116a9ca0e76c8ebd71b2b3ec
juspay/hyperswitch
juspay__hyperswitch-8920
Bug: [BUG] [XENDIT] CVV needs to be optional ### Bug Description CVV should be made an optional field for the connector Xendit. ### Expected Behavior If we do not pass CVV payment is getting failed for Xendit PSP ### Actual Behavior If we do not pass CVV payment should still get succeeded for Xendit PSP ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/xendit.rs b/crates/hyperswitch_connectors/src/connectors/xendit.rs index ff84224a658..57c5978bdf3 100644 --- a/crates/hyperswitch_connectors/src/connectors/xendit.rs +++ b/crates/hyperswitch_connectors/src/connectors/xendit.rs @@ -626,31 +626,18 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { - let response: xendit::XenditPaymentResponse = res + let response: xendit::XenditCaptureResponse = res .response .parse_struct("Xendit PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - let response_integrity_object = connector_utils::get_capture_integrity_object( - self.amount_converter, - Some(response.amount), - response.currency.to_string().clone(), - )?; - event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - - let new_router_data = RouterData::try_from(ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed); - - new_router_data.map(|mut router_data| { - router_data.request.integrity_object = Some(response_integrity_object); - router_data - }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( diff --git a/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs b/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs index 7b649289ea0..ea10e96dcbf 100644 --- a/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs @@ -133,7 +133,8 @@ pub struct CardInformation { pub card_number: CardNumber, pub expiry_month: Secret<String>, pub expiry_year: Secret<String>, - pub cvv: Secret<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub cvv: Option<Secret<String>>, pub cardholder_name: Secret<String>, pub cardholder_email: pii::Email, pub cardholder_phone_number: Secret<String>, @@ -201,6 +202,16 @@ fn map_payment_response_to_attempt_status( } } +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct XenditCaptureResponse { + pub id: String, + pub status: PaymentStatus, + pub actions: Option<Vec<Action>>, + pub payment_method: PaymentMethodInfo, + pub failure_code: Option<String>, + pub reference_id: Secret<String>, +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum MethodType { @@ -242,7 +253,11 @@ impl TryFrom<XenditRouterData<&PaymentsAuthorizeRouterData>> for XenditPaymentsR card_number: card_data.card_number.clone(), expiry_month: card_data.card_exp_month.clone(), expiry_year: card_data.get_expiry_year_4_digit(), - cvv: card_data.card_cvc.clone(), + cvv: if card_data.card_cvc.clone().expose().is_empty() { + None + } else { + Some(card_data.card_cvc.clone()) + }, cardholder_name: card_data .get_cardholder_name() .or(item.router_data.get_billing_full_name())?, @@ -410,7 +425,7 @@ impl<F> } impl<F> - TryFrom<ResponseRouterData<F, XenditPaymentResponse, PaymentsCaptureData, PaymentsResponseData>> + TryFrom<ResponseRouterData<F, XenditCaptureResponse, PaymentsCaptureData, PaymentsResponseData>> for RouterData<F, PaymentsCaptureData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; @@ -418,12 +433,18 @@ impl<F> fn try_from( item: ResponseRouterData< F, - XenditPaymentResponse, + XenditCaptureResponse, PaymentsCaptureData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { - let status = map_payment_response_to_attempt_status(item.response.clone(), true); + let status = match item.response.status { + PaymentStatus::Failed => enums::AttemptStatus::Failure, + PaymentStatus::Succeeded | PaymentStatus::Verified => enums::AttemptStatus::Charged, + PaymentStatus::Pending => enums::AttemptStatus::Pending, + PaymentStatus::RequiresAction => enums::AttemptStatus::AuthenticationPending, + PaymentStatus::AwaitingCapture => enums::AttemptStatus::Authorized, + }; let response = if status == enums::AttemptStatus::Failure { Err(ErrorResponse { code: item
2025-08-12T09:54: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 --> 1. CVV should be made an optional field for the connector Xendit. 2. Fix Capture Flow for Xendit ### 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` 3. `crates/router/src/configs` 4. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with 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/8920 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Testing CURL's: Payments Create: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_43StkeAliDdRysVQ1Bk58TfaGfqvDrRcQDIWNdnr9rx3WGPr7qnKR9ZQzdmf7P07' \ --data-raw '{ "amount": 6540000, "currency": "IDR", "confirm": true, "capture_method": "manual", "email": "abc@def.com", "amount_to_capture": 6540000, "billing": { "phone": { "number": "8056594427", "country_code": "+91" } }, "payment_method": "card", "payment_method_data": { "card": { "card_exp_month": "11", "card_exp_year": "29", "card_holder_name": "John Doe", "card_number": "4000000000001091", "card_cvc": "100" } }, "payment_method_type": "credit", "retry_action": "manual_retry" }' ``` Response: ``` { "payment_id": "pay_iapkM8sQja6Xvfdn9Tje", "merchant_id": "merchant_1754983663", "status": "processing", "amount": 6540000, "net_amount": 6540000, "shipping_cost": null, "amount_capturable": 6540000, "amount_received": null, "connector": "xendit", "client_secret": "pay_iapkM8sQja6Xvfdn9Tje_secret_83zsZQ4asN8r6n39cRgb", "created": "2025-08-12T09:59:40.385Z", "currency": "IDR", "customer_id": null, "customer": { "id": null, "name": null, "email": "abc@def.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "1091", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "11", "card_exp_year": "29", "card_holder_name": "John Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": null, "phone": { "number": "8056594427", "country_code": "+91" }, "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": "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": "pr-d7afb058-5ecb-424b-af1a-60c6ce3f8df0", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "2aa664ab-6a91-417d-a9bb-db3f6fd1fc21", "payment_link": null, "profile_id": "pro_pRZDis5aB5cSfftyA4Dq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_mJa8AsZOXYdYmggROjBG", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-12T10:14:40.385Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-12T09:59:41.228Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` Payments Retrieve: Request: ``` curl --location 'http://localhost:8080/payments/pay_iapkM8sQja6Xvfdn9Tje?force_sync=true&expand_captures=true&expand_attempts=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_43StkeAliDdRysVQ1Bk58TfaGfqvDrRcQDIWNdnr9rx3WGPr7qnKR9ZQzdmf7P07' ``` Response: ``` { "payment_id": "pay_iapkM8sQja6Xvfdn9Tje", "merchant_id": "merchant_1754983663", "status": "requires_capture", "amount": 6540000, "net_amount": 6540000, "shipping_cost": null, "amount_capturable": 6540000, "amount_received": null, "connector": "xendit", "client_secret": "pay_iapkM8sQja6Xvfdn9Tje_secret_83zsZQ4asN8r6n39cRgb", "created": "2025-08-12T09:59:40.385Z", "currency": "IDR", "customer_id": null, "customer": { "id": null, "name": null, "email": "abc@def.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "attempts": [ { "attempt_id": "pay_iapkM8sQja6Xvfdn9Tje_1", "status": "pending", "amount": 6540000, "order_tax_amount": null, "currency": "IDR", "connector": "xendit", "error_message": null, "payment_method": "card", "connector_transaction_id": "pr-d7afb058-5ecb-424b-af1a-60c6ce3f8df0", "capture_method": "manual", "authentication_type": "no_three_ds", "created_at": "2025-08-12T09:59:40.385Z", "modified_at": "2025-08-12T09:59:41.229Z", "cancellation_reason": null, "mandate_id": null, "error_code": null, "payment_token": null, "connector_metadata": null, "payment_experience": null, "payment_method_type": "credit", "reference_id": "2aa664ab-6a91-417d-a9bb-db3f6fd1fc21", "unified_code": null, "unified_message": null, "client_source": null, "client_version": 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": "1091", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "11", "card_exp_year": "29", "card_holder_name": "John Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": null, "phone": { "number": "8056594427", "country_code": "+91" }, "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": "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": "pr-d7afb058-5ecb-424b-af1a-60c6ce3f8df0", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "2aa664ab-6a91-417d-a9bb-db3f6fd1fc21", "payment_link": null, "profile_id": "pro_pRZDis5aB5cSfftyA4Dq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_mJa8AsZOXYdYmggROjBG", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-12T10:14:40.385Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-12T09:59:48.778Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` Payments Capture: Request: ``` curl --location 'http://localhost:8080/payments/pay_iapkM8sQja6Xvfdn9Tje/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_43StkeAliDdRysVQ1Bk58TfaGfqvDrRcQDIWNdnr9rx3WGPr7qnKR9ZQzdmf7P07' \ --data '{ "statement_descriptor_name": "Joseph", "statement_descriptor_prefix" :"joseph", "statement_descriptor_suffix": "JS" }' ``` Response: ``` { "payment_id": "pay_iapkM8sQja6Xvfdn9Tje", "merchant_id": "merchant_1754983663", "status": "succeeded", "amount": 6540000, "net_amount": 6540000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6540000, "connector": "xendit", "client_secret": "pay_iapkM8sQja6Xvfdn9Tje_secret_83zsZQ4asN8r6n39cRgb", "created": "2025-08-12T09:59:40.385Z", "currency": "IDR", "customer_id": null, "customer": { "id": null, "name": null, "email": "abc@def.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "1091", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "11", "card_exp_year": "29", "card_holder_name": "John Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": null, "phone": { "number": "8056594427", "country_code": "+91" }, "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": "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": "pr-d7afb058-5ecb-424b-af1a-60c6ce3f8df0", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "1746e4f7-36a7-4058-9301-aac9772f97b7", "payment_link": null, "profile_id": "pro_pRZDis5aB5cSfftyA4Dq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_mJa8AsZOXYdYmggROjBG", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-12T10:14:40.385Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-12T09:59:57.719Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` Note: Existing CYPRESS not working on main branch for PSP Xendit and hence skipping Cypress tests for this PR ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.116.0
8bb8b2062e84e8d7116a9ca0e76c8ebd71b2b3ec
8bb8b2062e84e8d7116a9ca0e76c8ebd71b2b3ec
juspay/hyperswitch
juspay__hyperswitch-8914
Bug: [REFACTOR]: [NUVIE] Fix card 3ds Fix card 3ds for Nuvie connector
diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 6d4b27f17e6..3e811b7dddf 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -62,6 +62,11 @@ fn to_boolean(string: String) -> bool { } } +// The dimensions of the challenge window for full screen. +const CHALLENGE_WINDOW_SIZE: &str = "05"; +// The challenge preference for the challenge flow. +const CHALLENGE_PREFERNCE: &str = "01"; + trait NuveiAuthorizePreprocessingCommon { fn get_browser_info(&self) -> Option<BrowserInformation>; fn get_related_transaction_id(&self) -> Option<String>; @@ -527,6 +532,7 @@ pub struct V2AdditionalParams { pub rebill_expiry: Option<String>, /// Recurring Frequency in days pub rebill_frequency: Option<String>, + pub challenge_preference: Option<String>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] @@ -563,7 +569,7 @@ pub struct NuveiACSResponse { pub message_type: String, pub message_version: String, pub trans_status: Option<LiabilityShift>, - pub message_extension: Vec<MessageExtensionAttribute>, + pub message_extension: Option<Vec<MessageExtensionAttribute>>, pub acs_signed_content: Option<serde_json::Value>, } @@ -1197,11 +1203,22 @@ where ), rebill_frequency: Some(mandate_meta.frequency), challenge_window_size: None, + challenge_preference: None, }), item.request.get_customer_id_required(), ) } - _ => (None, None, None), + // non mandate transactions + _ => ( + None, + Some(V2AdditionalParams { + rebill_expiry: None, + rebill_frequency: None, + challenge_window_size: Some(CHALLENGE_WINDOW_SIZE.to_string()), + challenge_preference: Some(CHALLENGE_PREFERNCE.to_string()), + }), + None, + ), }; let three_d = if item.is_three_ds() { let browser_details = match &browser_information { @@ -1277,14 +1294,18 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, Secret<String>)> ) -> Result<Self, Self::Error> { let item = data.0; let request_data = match item.request.payment_method_data.clone() { - Some(PaymentMethodData::Card(card)) => Ok(Self { - payment_option: PaymentOption::from(NuveiCardDetails { - card, - three_d: None, - card_holder_name: item.get_optional_billing_full_name(), - }), - ..Default::default() - }), + Some(PaymentMethodData::Card(card)) => { + let device_details = DeviceDetails::foreign_try_from(&item.request.browser_info)?; + Ok(Self { + payment_option: PaymentOption::from(NuveiCardDetails { + card, + three_d: None, + card_holder_name: item.get_optional_billing_full_name(), + }), + device_details, + ..Default::default() + }) + } Some(PaymentMethodData::Wallet(..)) | Some(PaymentMethodData::PayLater(..)) | Some(PaymentMethodData::BankDebit(..)) @@ -1319,6 +1340,7 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, Secret<String>)> Ok(Self { related_transaction_id: request_data.related_transaction_id, payment_option: request_data.payment_option, + device_details: request_data.device_details, ..request }) } diff --git a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs index a26d0c7689f..1c6977ac5c9 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs @@ -75,7 +75,7 @@ pub struct MessageExtensionAttribute { pub id: String, pub name: String, pub criticality_indicator: bool, - pub data: String, + pub data: serde_json::Value, } #[derive(Clone, Default, Debug)]
2025-08-11T14:21:59Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Fix deserlization error for Nuvei card 3ds ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Create nuvie card 3ds ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_5iub419oM0WIf9pI6nHrCbopoQ5dSKQEJkyPJZCmYbqECx5KC61S7N1yl7c1IdKD' \ --data-raw '{ "amount": 15100, "currency": "EUR", "confirm": true, "customer_id":"nithxxinn", "return_url": "https://www.google.com", "capture_method": "automatic", "payment_method": "card", "payment_method_type": "credit", "authentication_type": "three_ds", "description": "hellow world", "billing": { "address": { "zip": "560095", "country": "US", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" } }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "hello@gmail.com", "payment_method_data": { "card": { "card_number": "2221008123677736", "card_exp_month": "12", "card_exp_year": "2030", "card_holder_name": "CL-BRW2", "card_cvc": "217" } }, "setup_future_usage": "on_session" }' ``` response ``` { "payment_id": "pay_SwA17VK0vJc9lZyksSsp", "merchant_id": "merchant_1754896786", "status": "requires_customer_action", "amount": 15100, "net_amount": 15100, "shipping_cost": null, "amount_capturable": 15100, "amount_received": null, "connector": "nuvei", "client_secret": "pay_SwA17VK0vJc9lZyksSsp_secret_1Le4qoHaeDahJN4pDv4N", "created": "2025-08-11T12:47:40.099Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "hello@gmail.com", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "7736", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "222100", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "2030", "card_holder_name": "CL-BRW2", "payment_checks": { "avs_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "cReq": "eyJ0aHJlZURTU2VydmVyVHJhbnNJRCI6IjZjNzNkZWQ5LTRmMzEtNDNjMS1iYjdmLTEwMDA2YmYyMTBmYiIsImFjc1RyYW5zSUQiOiIzZmRhNGVjYS0xMzI3LTQyZjctOGU2Ny1mYzE4ZDUxNDM0NTIiLCJjaGFsbGVuZ2VXaW5kb3dTaXplIjoiMDUiLCJtZXNzYWdlVHlwZSI6IkNSZXEiLCJtZXNzYWdlVmVyc2lvbiI6IjIuMi4wIn0", "flow": "challenge", "acsUrl": "https://3dsn.sandbox.safecharge.com/ThreeDSACSEmulatorChallenge/api/ThreeDSACSChallengeController/ChallengePage?eyJub3RpZmljYXRpb25VUkwiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvcGF5bWVudHMvcGF5X1N3QTE3VkswdkpjOWxaeWtzU3NwL21lcmNoYW50XzE3NTQ4OTY3ODYvcmVkaXJlY3QvY29tcGxldGUvbnV2ZWkiLCJ0aHJlZURTU2VydmVyVHJhbnNJRCI6IjZjNzNkZWQ5LTRmMzEtNDNjMS1iYjdmLTEwMDA2YmYyMTBmYiIsImFjc1RyYW5zSUQiOiIzZmRhNGVjYS0xMzI3LTQyZjctOGU2Ny1mYzE4ZDUxNDM0NTIiLCJkc1RyYW5zSUQiOiI3ZGUyY2YxZC00MmYxLTQ1ZWItOGE1Mi02MmQ5Mjk3OWEwOWUiLCJkYXRhIjpudWxsLCJNZXNzYWdlVmVyc2lvbiI6IjIuMi4wIn0=", "version": "2.2.0", "threeDFlow": "1", "decisionReason": "NoPreference", "threeDReasonId": "", "acquirerDecision": "ExemptionRequest", "challengePreferenceReason": "12", "isExemptionRequestInAuthentication": "0" } }, "billing": null }, "payment_token": "token_jptsctTb26hNYSmaPHom", "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "hello@gmail.com", "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "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_SwA17VK0vJc9lZyksSsp/merchant_1754896786/pay_SwA17VK0vJc9lZyksSsp_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": "nithxxinn", "created_at": 1754916460, "expires": 1754920060, "secret": "epk_00825ca507a647b1a68b6e174af4ad28" }, "manual_retry_allowed": null, "connector_transaction_id": "8110000000012074375", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "7784849111", "payment_link": null, "profile_id": "pro_Ff3vG29EedTBVrRtdf20", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_vvdYt5E4uXbNvYftGlYf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-11T13:02:40.099Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-11T12:47:42.875Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` Complete payment using redirection 2. Do psync Response ``` { "payment_id": "pay_SwA17VK0vJc9lZyksSsp", "merchant_id": "merchant_1754896786", "status": "succeeded", "amount": 15100, "net_amount": 15100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 15100, "connector": "nuvei", "client_secret": "pay_SwA17VK0vJc9lZyksSsp_secret_1Le4qoHaeDahJN4pDv4N", "created": "2025-08-11T12:47:40.099Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "hello@gmail.com", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "7736", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "222100", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "2030", "card_holder_name": "CL-BRW2", "payment_checks": { "avs_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "flow": "challenge", "decisionReason": "NoPreference", "acquirerDecision": "ExemptionRequest", "challengePreferenceReason": "12" } }, "billing": null }, "payment_token": "token_jptsctTb26hNYSmaPHom", "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "hello@gmail.com", "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "8110000000012074525", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "7784849111", "payment_link": null, "profile_id": "pro_Ff3vG29EedTBVrRtdf20", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_vvdYt5E4uXbNvYftGlYf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-11T13:02:40.099Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-11T12:49:18.842Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` cypress test <img width="1486" height="1756" alt="Screenshot 2025-08-12 at 1 41 17β€―PM" src="https://github.com/user-attachments/assets/e52ca0ab-1600-48ca-8430-3b3e80ba4545" /> <img width="1824" height="1550" alt="Screenshot 2025-08-12 at 4 44 25β€―PM" src="https://github.com/user-attachments/assets/42c36473-c99e-489c-b668-07782a3b7a99" /> <img width="855" height="792" alt="Screenshot 2025-08-19 at 3 30 24β€―PM" src="https://github.com/user-attachments/assets/78d85781-a5e4-4e6c-842a-26736dd57151" /> ## 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.116.0
6950c04eaebc0499040556d8bbf5c684aebd2c9e
6950c04eaebc0499040556d8bbf5c684aebd2c9e
juspay/hyperswitch
juspay__hyperswitch-8910
Bug: refactor(euclid): transform enum types to include sub-variants of payment method types
diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rs index d9d5ed1de26..f7eafcc28d1 100644 --- a/crates/router/src/core/payments/routing/utils.rs +++ b/crates/router/src/core/payments/routing/utils.rs @@ -18,7 +18,10 @@ use diesel_models::{enums, routing_algorithm}; use error_stack::ResultExt; use euclid::{ backend::BackendInput, - frontend::ast::{self}, + frontend::{ + ast::{self}, + dir::{self, transformers::IntoDirValue}, + }, }; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use external_services::grpc_client::dynamic_routing as ir_client; @@ -593,6 +596,17 @@ pub fn convert_backend_input_to_routing_eval( "payment_method".to_string(), Some(ValueType::EnumVariant(pm.to_string())), ); + if let Some(pmt) = input.payment_method.payment_method_type { + match (pmt, pm).into_dir_value() { + Ok(dv) => insert_dirvalue_param(&mut params, dv), + Err(e) => logger::debug!( + ?e, + ?pmt, + ?pm, + "decision_engine_euclid: into_dir_value failed; skipping subset param" + ), + } + } } if let Some(pmt) = input.payment_method.payment_method_type { params.insert( @@ -647,6 +661,110 @@ pub fn convert_backend_input_to_routing_eval( }) } +// All the independent variants of payment method types, configured via dashboard +fn insert_dirvalue_param(params: &mut HashMap<String, Option<ValueType>>, dv: dir::DirValue) { + match dv { + dir::DirValue::RewardType(v) => { + params.insert( + "reward".to_string(), + Some(ValueType::EnumVariant(v.to_string())), + ); + } + dir::DirValue::CardType(v) => { + params.insert( + "card".to_string(), + Some(ValueType::EnumVariant(v.to_string())), + ); + } + dir::DirValue::PayLaterType(v) => { + params.insert( + "pay_later".to_string(), + Some(ValueType::EnumVariant(v.to_string())), + ); + } + dir::DirValue::WalletType(v) => { + params.insert( + "wallet".to_string(), + Some(ValueType::EnumVariant(v.to_string())), + ); + } + dir::DirValue::VoucherType(v) => { + params.insert( + "voucher".to_string(), + Some(ValueType::EnumVariant(v.to_string())), + ); + } + dir::DirValue::BankRedirectType(v) => { + params.insert( + "bank_redirect".to_string(), + Some(ValueType::EnumVariant(v.to_string())), + ); + } + dir::DirValue::BankDebitType(v) => { + params.insert( + "bank_debit".to_string(), + Some(ValueType::EnumVariant(v.to_string())), + ); + } + dir::DirValue::BankTransferType(v) => { + params.insert( + "bank_transfer".to_string(), + Some(ValueType::EnumVariant(v.to_string())), + ); + } + dir::DirValue::RealTimePaymentType(v) => { + params.insert( + "real_time_payment".to_string(), + Some(ValueType::EnumVariant(v.to_string())), + ); + } + dir::DirValue::UpiType(v) => { + params.insert( + "upi".to_string(), + Some(ValueType::EnumVariant(v.to_string())), + ); + } + dir::DirValue::GiftCardType(v) => { + params.insert( + "gift_card".to_string(), + Some(ValueType::EnumVariant(v.to_string())), + ); + } + dir::DirValue::CardRedirectType(v) => { + params.insert( + "card_redirect".to_string(), + Some(ValueType::EnumVariant(v.to_string())), + ); + } + dir::DirValue::OpenBankingType(v) => { + params.insert( + "open_banking".to_string(), + Some(ValueType::EnumVariant(v.to_string())), + ); + } + dir::DirValue::MobilePaymentType(v) => { + params.insert( + "mobile_payment".to_string(), + Some(ValueType::EnumVariant(v.to_string())), + ); + } + dir::DirValue::CryptoType(v) => { + params.insert( + "crypto".to_string(), + Some(ValueType::EnumVariant(v.to_string())), + ); + } + other => { + // all other values can be ignored for now as they don't converge with + // payment method type + logger::warn!( + ?other, + "decision_engine_euclid: unmapped dir::DirValue; add a mapping here" + ); + } + } +} + #[derive(Debug, Clone, serde::Deserialize)] struct DeErrorResponse { code: String,
2025-08-11T12:19:51Z
## 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 refactors the Euclid routing parameter transformation logic to **include sub-variants of payment method types** in the Decision Engine evaluation request. Key updates: - Added logic to **convert `(payment_method_type, payment_method)` pairs** into a `DirValue` representation. - Introduced `insert_dirvalue_param()` to map each `DirValue` variant into a corresponding routing parameter key. - Enhanced `convert_backend_input_to_routing_eval` to insert these sub-variant parameters alongside existing routing parameters. - This ensures richer context is sent to Euclid for more granular routing decisions. ## Outcomes - Enables **finer-grained routing rules** based on payment method sub-types (e.g., `WalletType`, `CryptoType`, `GiftCardType`). - Improves compatibility with dashboard-configured payment method rules in Euclid. - Makes routing evaluation requests **more descriptive and precise**, improving match accuracy. ## Diff Hunk Explanation ### `crates/router/src/core/payments/routing/utils.rs` - **Modified** `convert_backend_input_to_routing_eval`: - Added check for both `payment_method_type` and `payment_method` presence. - Converted them into a `DirValue` using `into_dir_value()`. - Inserted the resulting parameters into the evaluation request map. - **Added** new helper `insert_dirvalue_param()`: - Matches on each `DirValue` variant and inserts it as a `ValueType::EnumVariant` with an appropriate key (e.g., `"wallet"`, `"crypto"`, `"bank_transfer"`). - Ignores unsupported or non-converging variants for now. - **No changes** to external APIs or DB schema β€” purely internal parameter transformation refactor. This refactor lays the groundwork for **sub-type aware routing** in Euclid without requiring external schema changes. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Testing isn't required as this is just an enum mapping change. ## 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.116.0
0e957854372f1e6a81ce72234b8a4fda16cb4b8d
0e957854372f1e6a81ce72234b8a4fda16cb4b8d
juspay/hyperswitch
juspay__hyperswitch-8906
Bug: Improve UCS connector configuration format for better type safety and usability ## Problem Statement The current unified connector service (UCS) configuration uses an array format for specifying connectors that should use UCS only. This approach has several limitations: ### Current Issues 1. **Type Safety**: The current `Vec<String>` approach allows invalid connector names to be specified without compile-time validation 2. **Configuration Verbosity**: Array format in TOML files is more verbose and harder to read/maintain 3. **Runtime Validation**: Invalid connector names are only caught at runtime when the configuration is parsed 4. **Inconsistent Format**: Different from other comma-separated configuration patterns used elsewhere in the codebase ### Current Configuration Format ```toml [grpc_client.unified_connector_service] ucs_only_connectors = [ "razorpay", "phonepe", "paytm", "cashfree", ] ``` ## Proposed Solution Refactor the configuration to use a comma-separated string format with type-safe parsing: ### Benefits - **Type Safety**: Use `HashSet<Connector>` with enum validation to prevent invalid connector names - **Cleaner Configuration**: More concise and readable comma-separated format - **Better Error Handling**: Custom deserializer with detailed error messages for invalid configurations - **Consistency**: Aligns with other comma-separated configuration patterns in the codebase - **Performance**: HashSet provides O(1) lookup time for connector validation ### Proposed Configuration Format ```toml [grpc_client.unified_connector_service] ucs_only_connectors = "paytm, phonepe, razorpay, cashfree" ``` ## Implementation Requirements 1. **Custom Deserializer**: Implement a generic deserializer for comma-separated strings to typed HashSets 2. **Type Safety**: Use `Connector` enum instead of raw strings 3. **Backward Compatibility**: Ensure existing connector validation logic continues to work 4. **Configuration Updates**: Update all config files to use the new format 5. **Comprehensive Testing**: Add unit tests for the deserializer and configuration parsing ## Acceptance Criteria - [x] Configuration uses comma-separated string format - [x] Type-safe parsing with `Connector` enum validation - [x] Custom deserializer handles edge cases (whitespace, duplicates, empty strings) - [x] All configuration files updated consistently - [x] Comprehensive unit tests for the deserializer - [x] Existing connector validation logic works with new format - [x] Detailed error messages for invalid configurations ## Labels - Enhancement - Configuration - Type Safety - Refactoring
diff --git a/config/config.example.toml b/config/config.example.toml index d4ce454edfc..5783a70c370 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -1159,6 +1159,7 @@ url = "http://localhost:8080" # Open Router URL [grpc_client.unified_connector_service] base_url = "http://localhost:8000" # Unified Connector Service Base URL connection_timeout = 10 # Connection Timeout Duration in Seconds +ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only [grpc_client.recovery_decider_client] # Revenue recovery client base url base_url = "http://127.0.0.1:8080" #Base URL diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 6acf697ac4d..64db7079f40 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -384,6 +384,7 @@ connector_names = "connector_names" # Comma-separated list of allowed connec [grpc_client.unified_connector_service] base_url = "http://localhost:8000" # Unified Connector Service Base URL connection_timeout = 10 # Connection Timeout Duration in Seconds +ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only [revenue_recovery.recovery_timestamp] # Timestamp configuration for Revenue Recovery initial_timestamp_in_hours = 1 # number of hours added to start time for Decider service of Revenue Recovery diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 47c2bc39bc1..a387cd0c164 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -837,3 +837,6 @@ click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [list_dispute_supported_connectors] connector_list = "worldpayvantiv" + +[grpc_client.unified_connector_service] +ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 3550b1ec929..a95d88dc632 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -847,3 +847,6 @@ click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [revenue_recovery] monitoring_threshold_in_seconds = 60 retry_algorithm_type = "cascading" + +[grpc_client.unified_connector_service] +ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 47a64b91b4b..296888abcdd 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -856,3 +856,6 @@ retry_algorithm_type = "cascading" [list_dispute_supported_connectors] connector_list = "worldpayvantiv" + +[grpc_client.unified_connector_service] +ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only diff --git a/config/development.toml b/config/development.toml index 7bc0dcc397d..95b2f289621 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1268,12 +1268,7 @@ enabled = "true" [grpc_client.unified_connector_service] base_url = "http://localhost:8000" connection_timeout = 10 -ucs_only_connectors = [ - "razorpay", - "phonepe", - "paytm", - "cashfree", -] +ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only [revenue_recovery] monitoring_threshold_in_seconds = 60 diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs index 62f681a985c..81bb2dc8988 100644 --- a/crates/external_services/src/grpc_client/unified_connector_service.rs +++ b/crates/external_services/src/grpc_client/unified_connector_service.rs @@ -1,5 +1,6 @@ -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; +use common_enums::connector_enums::Connector; use common_utils::{consts as common_utils_consts, errors::CustomResult, types::Url}; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; @@ -18,6 +19,7 @@ use unified_connector_service_client::payments::{ use crate::{ consts, grpc_client::{GrpcClientSettings, GrpcHeaders}, + utils::deserialize_hashset, }; /// Unified Connector Service error variants @@ -123,9 +125,9 @@ pub struct UnifiedConnectorServiceClientConfig { /// Contains the connection timeout duration in seconds pub connection_timeout: u64, - /// List of connectors to use with the unified connector service - #[serde(default)] - pub ucs_only_connectors: Vec<String>, + /// Set of external services/connectors available for the unified connector service + #[serde(default, deserialize_with = "deserialize_hashset")] + pub ucs_only_connectors: HashSet<Connector>, } /// Contains the Connector Auth Type and related authentication data. diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index 7d97b5e99c0..aee7d232bb3 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -28,6 +28,9 @@ pub mod managers; /// crm module pub mod crm; +/// deserializers module_path +pub mod utils; + #[cfg(feature = "revenue_recovery")] /// date_time module pub mod date_time { diff --git a/crates/external_services/src/utils.rs b/crates/external_services/src/utils.rs new file mode 100644 index 00000000000..16cfc8ea008 --- /dev/null +++ b/crates/external_services/src/utils.rs @@ -0,0 +1,178 @@ +//! Custom deserializers for external services configuration + +use std::collections::HashSet; + +use serde::Deserialize; + +/// Parses a comma-separated string into a HashSet of typed values. +/// +/// # Arguments +/// +/// * `value` - String or string reference containing comma-separated values +/// +/// # Returns +/// +/// * `Ok(HashSet<T>)` - Successfully parsed HashSet +/// * `Err(String)` - Error message if any value parsing fails +/// +/// # Type Parameters +/// +/// * `T` - Target type that implements `FromStr`, `Eq`, and `Hash` +/// +/// # Examples +/// +/// ``` +/// use std::collections::HashSet; +/// +/// let result: Result<HashSet<i32>, String> = +/// deserialize_hashset_inner("1,2,3"); +/// assert!(result.is_ok()); +/// +/// if let Ok(hashset) = result { +/// assert!(hashset.contains(&1)); +/// assert!(hashset.contains(&2)); +/// assert!(hashset.contains(&3)); +/// } +/// ``` +fn deserialize_hashset_inner<T>(value: impl AsRef<str>) -> Result<HashSet<T>, String> +where + T: Eq + std::str::FromStr + std::hash::Hash, + <T as std::str::FromStr>::Err: std::fmt::Display, +{ + let (values, errors) = value + .as_ref() + .trim() + .split(',') + .map(|s| { + T::from_str(s.trim()).map_err(|error| { + format!( + "Unable to deserialize `{}` as `{}`: {error}", + s.trim(), + std::any::type_name::<T>() + ) + }) + }) + .fold( + (HashSet::new(), Vec::new()), + |(mut values, mut errors), result| match result { + Ok(t) => { + values.insert(t); + (values, errors) + } + Err(error) => { + errors.push(error); + (values, errors) + } + }, + ); + if !errors.is_empty() { + Err(format!("Some errors occurred:\n{}", errors.join("\n"))) + } else { + Ok(values) + } +} + +/// Serde deserializer function for converting comma-separated strings into typed HashSets. +/// +/// This function is designed to be used with serde's `#[serde(deserialize_with = "deserialize_hashset")]` +/// attribute to customize deserialization of HashSet fields. +/// +/// # Arguments +/// +/// * `deserializer` - Serde deserializer instance +/// +/// # Returns +/// +/// * `Ok(HashSet<T>)` - Successfully deserialized HashSet +/// * `Err(D::Error)` - Serde deserialization error +/// +/// # Type Parameters +/// +/// * `D` - Serde deserializer type +/// * `T` - Target type that implements `FromStr`, `Eq`, and `Hash` +pub(crate) fn deserialize_hashset<'a, D, T>(deserializer: D) -> Result<HashSet<T>, D::Error> +where + D: serde::Deserializer<'a>, + T: Eq + std::str::FromStr + std::hash::Hash, + <T as std::str::FromStr>::Err: std::fmt::Display, +{ + use serde::de::Error; + + deserialize_hashset_inner(<String>::deserialize(deserializer)?).map_err(D::Error::custom) +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + + use super::*; + + #[test] + fn test_deserialize_hashset_inner_success() { + let result: Result<HashSet<i32>, String> = deserialize_hashset_inner("1,2,3"); + assert!(result.is_ok()); + + if let Ok(hashset) = result { + assert_eq!(hashset.len(), 3); + assert!(hashset.contains(&1)); + assert!(hashset.contains(&2)); + assert!(hashset.contains(&3)); + } + } + + #[test] + fn test_deserialize_hashset_inner_with_whitespace() { + let result: Result<HashSet<String>, String> = deserialize_hashset_inner(" a , b , c "); + assert!(result.is_ok()); + + if let Ok(hashset) = result { + assert_eq!(hashset.len(), 3); + assert!(hashset.contains("a")); + assert!(hashset.contains("b")); + assert!(hashset.contains("c")); + } + } + + #[test] + fn test_deserialize_hashset_inner_empty_string() { + let result: Result<HashSet<String>, String> = deserialize_hashset_inner(""); + assert!(result.is_ok()); + if let Ok(hashset) = result { + assert_eq!(hashset.len(), 0); + } + } + + #[test] + fn test_deserialize_hashset_inner_single_value() { + let result: Result<HashSet<String>, String> = deserialize_hashset_inner("single"); + assert!(result.is_ok()); + + if let Ok(hashset) = result { + assert_eq!(hashset.len(), 1); + assert!(hashset.contains("single")); + } + } + + #[test] + fn test_deserialize_hashset_inner_invalid_int() { + let result: Result<HashSet<i32>, String> = deserialize_hashset_inner("1,invalid,3"); + assert!(result.is_err()); + + if let Err(error) = result { + assert!(error.contains("Unable to deserialize `invalid` as `i32`")); + } + } + + #[test] + fn test_deserialize_hashset_inner_duplicates() { + let result: Result<HashSet<String>, String> = deserialize_hashset_inner("a,b,a,c,b"); + assert!(result.is_ok()); + + if let Ok(hashset) = result { + assert_eq!(hashset.len(), 3); // Duplicates should be removed + assert!(hashset.contains("a")); + assert!(hashset.contains("b")); + assert!(hashset.contains("c")); + } + } +} diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs index b14811ea735..2ef6e81eedc 100644 --- a/crates/router/src/core/unified_connector_service.rs +++ b/crates/router/src/core/unified_connector_service.rs @@ -1,5 +1,7 @@ +use std::str::FromStr; + use api_models::admin; -use common_enums::{AttemptStatus, GatewaySystem, PaymentMethodType}; +use common_enums::{connector_enums::Connector, AttemptStatus, GatewaySystem, PaymentMethodType}; use common_utils::{errors::CustomResult, ext_traits::ValueExt}; use diesel_models::types::FeatureMetadata; use error_stack::ResultExt; @@ -105,6 +107,9 @@ where .get_string_repr(); let connector_name = router_data.connector.clone(); + let connector_enum = Connector::from_str(&connector_name) + .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)?; + let payment_method = router_data.payment_method.to_string(); let flow_name = get_flow_name::<F>()?; @@ -113,7 +118,7 @@ where .grpc_client .unified_connector_service .as_ref() - .is_some_and(|config| config.ucs_only_connectors.contains(&connector_name)); + .is_some_and(|config| config.ucs_only_connectors.contains(&connector_enum)); if is_ucs_only_connector { router_env::logger::info!(
2025-08-11T10:41:24Z
# Refactor: Change UCS connector configuration from array to comma-separated string ## Summary This PR refactors the unified connector service (UCS) configuration to use a comma-separated string format instead of an array for specifying connectors that should use UCS only. This change improves configuration management and parsing efficiency while maintaining type safety through a custom deserializer. ## Changes - **Configuration Format Change**: Modified `ucs_only_connectors` from `Vec<String>` to `HashSet<Connector>` with comma-separated string input - **Custom Deserializer Implementation**: Added a new `utils.rs` module in `external_services` with `deserialize_hashset` function for parsing comma-separated values into typed HashSets - **Type Safety Enhancement**: Updated connector validation to use `Connector` enum instead of raw strings, preventing invalid connector names - **Configuration Updates**: Updated all config files (`development.toml`, `config.example.toml`, `deployments/env_specific.toml`) to use the new comma-separated format - **Dependencies**: Added `common_enums` dependency to `external_services` crate for proper connector enum handling ## Related Issues Closes #8906 - Improve UCS connector configuration format for better type safety and usability ## Type of Change - [x] Refactoring - [ ] Bug fix - [ ] New feature - [ ] Breaking change - [ ] Documentation update ## Testing - **Configuration Parsing**: Tested comma-separated string parsing with various inputs including whitespace handling - **Type Validation**: Verified that invalid connector names are properly rejected during deserialization - **Backward Compatibility**: Ensured existing connector validation logic works with the new enum-based approach - **Unit Tests**: Added comprehensive test suite for the new deserializer functionality covering: - Valid comma-separated inputs - Whitespace handling - Error handling for invalid values - Empty string and single value scenarios - Duplicate value handling ## Implementation Details ### Key Files Modified - `crates/external_services/src/grpc_client/unified_connector_service.rs:119` - Configuration struct update - `crates/external_services/src/utils.rs` - New deserializer implementation - `crates/router/src/core/unified_connector_service.rs:57` - Connector validation logic update - Configuration files in `config/` directory ### New Functionality The custom deserializer provides: - Type-safe parsing of comma-separated strings into HashSets - Comprehensive error handling with detailed error messages - Generic implementation supporting any type that implements `FromStr + Eq + Hash` - Proper handling of edge cases (empty strings, whitespace, duplicates) ## Checklist - [x] Code follows project style guidelines - [x] Self-review completed - [x] Configuration changes tested locally - [x] Unit tests added for new deserializer functionality - [x] Type safety improvements verified - [x] All config files updated consistently
v1.116.0
07a6271b76f6986f30064d51113838d486f0f2c6
07a6271b76f6986f30064d51113838d486f0f2c6
juspay/hyperswitch
juspay__hyperswitch-8908
Bug: [BUG] (connector): [Netcetera] Fix struct fields for Netcetera Authentication Response ### Bug Description current structure NetceteraAuthenticationSuccessResponse{ .... pub challenge_cancel: Option<String>, pub trans_status_reason: Option<String>, pub message_extension: Option<Vec<MessageExtensionAttribute>>, } Correct structure NetceteraAuthenticationSuccessResponse{ .... authentication_response: { pub trans_status_reason: Option<String>, }, authentication_request: { pub message_extension: Option<String>, } } ### Expected Behavior When the struct is fixed in code, the expected behavior is to: Receive message_extension and trans_status_reason fields in Netcetera’s authentication response and store them in the authentication table. Receive the challenge_cancel field from the Netcetera notification payload and store it in the authentication table. ### Actual Behavior Currently expected behaviour is not happening and mentioned fields are not getting stored in authentication table. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index 2025d29d10d..f080a76b051 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -1439,29 +1439,23 @@ impl ) .ok(); let effective_authentication_type = authn_data.authentication_type.map(Into::into); - let network_score: Option<u32> = - if ccard.card_network == Some(common_enums::CardNetwork::CartesBancaires) { - match authn_data.message_extension.as_ref() { - Some(secret) => { - let exposed_value = secret.clone().expose(); - match serde_json::from_value::<Vec<MessageExtensionAttribute>>( - exposed_value, - ) { - Ok(exts) => extract_score_id(&exts), - Err(err) => { - router_env::logger::error!( - "Failed to deserialize message_extension: {:?}", - err - ); - None - } - } - } - None => None, - } - } else { - None - }; + let network_score = (ccard.card_network + == Some(common_enums::CardNetwork::CartesBancaires)) + .then_some(authn_data.message_extension.as_ref()) + .flatten() + .map(|secret| secret.clone().expose()) + .and_then(|exposed| { + serde_json::from_value::<Vec<MessageExtensionAttribute>>(exposed) + .map_err(|err| { + router_env::logger::error!( + "Failed to deserialize message_extension: {:?}", + err + ); + }) + .ok() + .and_then(|exts| extract_score_id(&exts)) + }); + CybersourceConsumerAuthInformation { pares_status, ucaf_collection_indicator, @@ -1566,29 +1560,23 @@ impl date_time::DateFormat::YYYYMMDDHHmmss, ) .ok(); - let network_score: Option<u32> = - if ccard.card_network == Some(common_enums::CardNetwork::CartesBancaires) { - match authn_data.message_extension.as_ref() { - Some(secret) => { - let exposed_value = secret.clone().expose(); - match serde_json::from_value::<Vec<MessageExtensionAttribute>>( - exposed_value, - ) { - Ok(exts) => extract_score_id(&exts), - Err(err) => { - router_env::logger::error!( - "Failed to deserialize message_extension: {:?}", - err - ); - None - } - } - } - None => None, - } - } else { - None - }; + let network_score = (ccard.card_network + == Some(common_enums::CardNetwork::CartesBancaires)) + .then_some(authn_data.message_extension.as_ref()) + .flatten() + .map(|secret| secret.clone().expose()) + .and_then(|exposed| { + serde_json::from_value::<Vec<MessageExtensionAttribute>>(exposed) + .map_err(|err| { + router_env::logger::error!( + "Failed to deserialize message_extension: {:?}", + err + ); + }) + .ok() + .and_then(|exts| extract_score_id(&exts)) + }); + CybersourceConsumerAuthInformation { pares_status, ucaf_collection_indicator, @@ -1697,30 +1685,23 @@ impl date_time::DateFormat::YYYYMMDDHHmmss, ) .ok(); - let network_score: Option<u32> = if token_data.card_network - == Some(common_enums::CardNetwork::CartesBancaires) - { - match authn_data.message_extension.as_ref() { - Some(secret) => { - let exposed_value = secret.clone().expose(); - match serde_json::from_value::<Vec<MessageExtensionAttribute>>( - exposed_value, - ) { - Ok(exts) => extract_score_id(&exts), - Err(err) => { - router_env::logger::error!( - "Failed to deserialize message_extension: {:?}", - err - ); - None - } - } - } - None => None, - } - } else { - None - }; + let network_score = (token_data.card_network + == Some(common_enums::CardNetwork::CartesBancaires)) + .then_some(authn_data.message_extension.as_ref()) + .flatten() + .map(|secret| secret.clone().expose()) + .and_then(|exposed| { + serde_json::from_value::<Vec<MessageExtensionAttribute>>(exposed) + .map_err(|err| { + router_env::logger::error!( + "Failed to deserialize message_extension: {:?}", + err + ); + }) + .ok() + .and_then(|exts| extract_score_id(&exts)) + }); + CybersourceConsumerAuthInformation { pares_status, ucaf_collection_indicator, diff --git a/crates/hyperswitch_connectors/src/connectors/netcetera.rs b/crates/hyperswitch_connectors/src/connectors/netcetera.rs index a2745dc4b08..60977d9b69b 100644 --- a/crates/hyperswitch_connectors/src/connectors/netcetera.rs +++ b/crates/hyperswitch_connectors/src/connectors/netcetera.rs @@ -214,14 +214,27 @@ impl IncomingWebhook for Netcetera { .body .parse_struct("netcetera ResultsResponseData") .change_context(ConnectorError::WebhookBodyDecodingFailed)?; + + let challenge_cancel = webhook_body + .results_request + .as_ref() + .and_then(|v| v.get("challengeCancel").and_then(|v| v.as_str())) + .map(|s| s.to_string()); + + let challenge_code_reason = webhook_body + .results_request + .as_ref() + .and_then(|v| v.get("transStatusReason").and_then(|v| v.as_str())) + .map(|s| s.to_string()); + Ok(ExternalAuthenticationPayload { trans_status: webhook_body .trans_status .unwrap_or(common_enums::TransactionStatus::InformationOnly), authentication_value: webhook_body.authentication_value, eci: webhook_body.eci, - challenge_cancel: webhook_body.challenge_cancel, - challenge_code_reason: webhook_body.trans_status_reason, + challenge_cancel, + challenge_code_reason, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs index 01189f6b926..1b8e2a65057 100644 --- a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs @@ -165,6 +165,21 @@ impl .and_then(|req| req.three_ds_requestor_challenge_ind.as_ref()) .and_then(|v| v.first().cloned()); + let message_extension = response + .authentication_request + .as_ref() + .and_then(|req| req.message_extension.as_ref()) + .and_then(|v| match serde_json::to_value(v) { + Ok(val) => Some(Secret::new(val)), + Err(e) => { + router_env::logger::error!( + "Failed to serialize message_extension: {:?}", + e + ); + None + } + }); + Ok(AuthenticationResponseData::AuthNResponse { authn_flow_type, authentication_value: response.authentication_value, @@ -173,20 +188,9 @@ impl ds_trans_id: response.authentication_response.ds_trans_id, eci: response.eci, challenge_code, - challenge_cancel: response.challenge_cancel, - challenge_code_reason: response.trans_status_reason, - message_extension: response.message_extension.and_then(|v| { - match serde_json::to_value(&v) { - Ok(val) => Some(Secret::new(val)), - Err(e) => { - router_env::logger::error!( - "Failed to serialize message_extension: {:?}", - e - ); - None - } - } - }), + challenge_cancel: None, // Note - challenge_cancel field is recieved in the RReq and updated in DB during external_authentication_incoming_webhook_flow + challenge_code_reason: response.authentication_response.trans_status_reason, + message_extension, }) } NetceteraAuthenticationResponse::Error(error_response) => Err(ErrorResponse { @@ -664,9 +668,6 @@ pub struct NetceteraAuthenticationSuccessResponse { pub authentication_response: AuthenticationResponse, #[serde(rename = "base64EncodedChallengeRequest")] pub encoded_challenge_request: Option<String>, - pub challenge_cancel: Option<String>, - pub trans_status_reason: Option<String>, - pub message_extension: Option<Vec<MessageExtensionAttribute>>, } #[derive(Debug, Deserialize, Serialize)] @@ -680,6 +681,7 @@ pub struct NetceteraAuthenticationFailureResponse { pub struct AuthenticationRequest { #[serde(rename = "threeDSRequestorChallengeInd")] pub three_ds_requestor_challenge_ind: Option<Vec<String>>, + pub message_extension: Option<serde_json::Value>, } #[derive(Debug, Deserialize, Serialize)] @@ -693,6 +695,7 @@ pub struct AuthenticationResponse { #[serde(rename = "dsTransID")] pub ds_trans_id: Option<String>, pub acs_signed_content: Option<String>, + pub trans_status_reason: Option<String>, } #[derive(Debug, Deserialize, Serialize, Clone)] @@ -742,6 +745,4 @@ pub struct ResultsResponseData { /// Optional object containing error details if any errors occurred during the process. pub error_details: Option<NetceteraErrorDetails>, - pub challenge_cancel: Option<String>, - pub trans_status_reason: Option<String>, }
2025-08-11T11:40:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [X] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Current structure ``` NetceteraAuthenticationSuccessResponse{ .... pub challenge_cancel: Option<String>, pub trans_status_reason: Option<String>, pub message_extension: Option<Vec<MessageExtensionAttribute>>, } ``` Correct structure ``` NetceteraAuthenticationSuccessResponse{ .... authentication_response: { pub trans_status_reason: Option<String>, }, authentication_request: { pub message_extension: Option<String>, } } ``` This PR introduces the above fix in the struct. Fixes summary: 1. Remove **challenge_cancel** field from NetceteraAuthenticationSuccessResponse 2. Move **trans_status_reason** inside AuthenticationResponse struct 3. Move **message_extension** inside AuthenticationRequest struct 4. Remove fields **challenge_cancel** and **challenge_code_reason** from ResultsResponseData, and consume **challenge_cancel** and **challenge_code_reason** from webhook's results_request field (RReq)." For your reference, please check the official specification of these attribute in 3DSecureio docs β€”it's clearer than what Netcetera currently provides https://docs.3dsecure.io/3dsv2/specification_220.html#attr-RReq-challengeCancel https://docs.3dsecure.io/3dsv2/specification_220.html#attr-ARes-transStatusReason https://docs.3dsecure.io/3dsv2/specification_220.html#attr-ARes-messageExtension ### 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` 4. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with 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)? --> With the code changes, the expected behaviour is to, 1. Receive message_extension and trans_status_reason fields in Netcetera’s authentication response and store them in the authentication table. 2. Receive the challenge_cancel field from the Netcetera notification payload and store it in the authentication table. ### Steps to verify field **trans_status_reason**: 1. Test Netcetera 3ds challenge flow via SDK. 2. Check in Authentication Table if **challenge_code_reason** is present. (trans_status_reason is mapped to challenge_code_reason in authentication table) **Query** `select challenge_code_reason from authentication where connector_authentication_id='82e5df02-d83f-4adf-b00b-d5c10c52d4cd';` <img width="1074" height="516" alt="Screenshot 2025-08-11 at 5 38 31β€―PM" src="https://github.com/user-attachments/assets/ffe93636-1630-4d75-b310-e28e9cdcab8a" /> ### Steps to verify field **challenge_cancel**: 1. Test Netcetera 3ds challenge flow via SDK. 2. Cancel the challenge from challenge iframe. 3. Check in Authentication Table if **challenge_cancel** is present. <img width="1319" height="585" alt="Screenshot 2025-08-11 at 5 40 31β€―PM" src="https://github.com/user-attachments/assets/612f21a1-2da1-472d-a844-d205024bc01f" /> **Query** `select challenge_cancel from authentication where connector_authentication_id='b51b6977-059d-4a59-92c9-1f3d37b43563';` <img width="1319" height="585" alt="Screenshot 2025-08-11 at 5 43 11β€―PM" src="https://github.com/user-attachments/assets/a441d352-4e7b-4c0a-ac82-09849dbcbc2f" /> Please note we cannot verify field **message_extension** in integ/sandbox, can only be tested in prod. ## 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.116.0
0e957854372f1e6a81ce72234b8a4fda16cb4b8d
0e957854372f1e6a81ce72234b8a4fda16cb4b8d
juspay/hyperswitch
juspay__hyperswitch-8892
Bug: add support to store signature_network and is_regulated in payment attempts Extended the AdditionalCardInfo struct to include new fields: is_regulated (indicates if the issuer is regulated under interchange fee caps) and signature_network (the card's primary global brand).
diff --git a/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql index 16815e9a33d..ffe706cab08 100644 --- a/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql +++ b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql @@ -45,6 +45,8 @@ CREATE TABLE payment_attempt_queue ( `card_network` Nullable(String), `routing_approach` LowCardinality(Nullable(String)), `debit_routing_savings` Nullable(UInt32), + `signature_network` Nullable(String), + `is_issuer_regulated` Nullable(Bool), `sign_flag` Int8 ) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', kafka_topic_list = 'hyperswitch-payment-attempt-events', @@ -100,6 +102,8 @@ CREATE TABLE payment_attempts ( `card_network` Nullable(String), `routing_approach` LowCardinality(Nullable(String)), `debit_routing_savings` Nullable(UInt32), + `signature_network` Nullable(String), + `is_issuer_regulated` Nullable(Bool), `sign_flag` Int8, INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1, INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1, @@ -158,6 +162,8 @@ CREATE MATERIALIZED VIEW payment_attempt_mv TO payment_attempts ( `card_network` Nullable(String), `routing_approach` LowCardinality(Nullable(String)), `debit_routing_savings` Nullable(UInt32), + `signature_network` Nullable(String), + `is_issuer_regulated` Nullable(Bool), `sign_flag` Int8 ) AS SELECT @@ -208,6 +214,8 @@ SELECT card_network, routing_approach, debit_routing_savings, + signature_network, + is_issuer_regulated, sign_flag FROM payment_attempt_queue diff --git a/crates/analytics/src/payments/accumulator.rs b/crates/analytics/src/payments/accumulator.rs index 6d7dca22a30..a266e1366af 100644 --- a/crates/analytics/src/payments/accumulator.rs +++ b/crates/analytics/src/payments/accumulator.rs @@ -63,6 +63,8 @@ pub struct ProcessedAmountAccumulator { pub struct DebitRoutingAccumulator { pub transaction_count: u64, pub savings_amount: u64, + pub signature_network: Option<String>, + pub is_issuer_regulated: Option<bool>, } #[derive(Debug, Default)] @@ -191,7 +193,13 @@ impl PaymentMetricAccumulator for SuccessRateAccumulator { } impl PaymentMetricAccumulator for DebitRoutingAccumulator { - type MetricOutput = (Option<u64>, Option<u64>, Option<u64>); + type MetricOutput = ( + Option<u64>, + Option<u64>, + Option<u64>, + Option<String>, + Option<bool>, + ); fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { if let Some(count) = metrics.count { @@ -200,6 +208,12 @@ impl PaymentMetricAccumulator for DebitRoutingAccumulator { if let Some(total) = metrics.total.as_ref().and_then(ToPrimitive::to_u64) { self.savings_amount += total; } + if let Some(signature_network) = &metrics.signature_network { + self.signature_network = Some(signature_network.clone()); + } + if let Some(is_issuer_regulated) = metrics.is_issuer_regulated { + self.is_issuer_regulated = Some(is_issuer_regulated); + } } fn collect(self) -> Self::MetricOutput { @@ -207,6 +221,8 @@ impl PaymentMetricAccumulator for DebitRoutingAccumulator { Some(self.transaction_count), Some(self.savings_amount), Some(0), + self.signature_network, + self.is_issuer_regulated, ) } } @@ -468,8 +484,13 @@ impl PaymentMetricsAccumulator { ) = self.payments_distribution.collect(); let (failure_reason_count, failure_reason_count_without_smart_retries) = self.failure_reasons_distribution.collect(); - let (debit_routed_transaction_count, debit_routing_savings, debit_routing_savings_in_usd) = - self.debit_routing.collect(); + let ( + debit_routed_transaction_count, + debit_routing_savings, + debit_routing_savings_in_usd, + signature_network, + is_issuer_regulated, + ) = self.debit_routing.collect(); PaymentMetricsBucketValue { payment_success_rate: self.payment_success_rate.collect(), @@ -497,6 +518,8 @@ impl PaymentMetricsAccumulator { debit_routed_transaction_count, debit_routing_savings, debit_routing_savings_in_usd, + signature_network, + is_issuer_regulated, } } } diff --git a/crates/analytics/src/payments/metrics.rs b/crates/analytics/src/payments/metrics.rs index b19c661322d..914eac7116b 100644 --- a/crates/analytics/src/payments/metrics.rs +++ b/crates/analytics/src/payments/metrics.rs @@ -53,6 +53,8 @@ pub struct PaymentMetricRow { pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, pub routing_approach: Option<DBEnumWrapper<storage_enums::RoutingApproach>>, + pub signature_network: Option<String>, + pub is_issuer_regulated: Option<bool>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub start_bucket: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] diff --git a/crates/analytics/src/payments/metrics/debit_routing.rs b/crates/analytics/src/payments/metrics/debit_routing.rs index 2caec813ec8..309b2131c63 100644 --- a/crates/analytics/src/payments/metrics/debit_routing.rs +++ b/crates/analytics/src/payments/metrics/debit_routing.rs @@ -56,6 +56,14 @@ where }) .switch()?; query_builder.add_select_column("currency").switch()?; + + query_builder + .add_select_column("signature_network") + .switch()?; + query_builder + .add_select_column("is_issuer_regulated") + .switch()?; + query_builder .add_select_column(Aggregate::Min { field: "created_at", @@ -85,6 +93,16 @@ where .switch()?; } + query_builder + .add_group_by_clause("signature_network") + .attach_printable("Error grouping by signature_network") + .switch()?; + + query_builder + .add_group_by_clause("is_issuer_regulated") + .attach_printable("Error grouping by is_issuer_regulated") + .switch()?; + query_builder .add_group_by_clause("currency") .attach_printable("Error grouping by currency") diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 10f039fcc72..38746ce5951 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -736,6 +736,16 @@ impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let signature_network: Option<String> = + row.try_get("signature_network").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let is_issuer_regulated: Option<bool> = + row.try_get("is_issuer_regulated").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -768,6 +778,8 @@ impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow { error_reason, first_attempt, routing_approach, + signature_network, + is_issuer_regulated, total, count, start_bucket, diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs index 193fdf26cc7..70583079930 100644 --- a/crates/api_models/src/analytics/payments.rs +++ b/crates/api_models/src/analytics/payments.rs @@ -319,6 +319,8 @@ pub struct PaymentMetricsBucketValue { pub debit_routed_transaction_count: Option<u64>, pub debit_routing_savings: Option<u64>, pub debit_routing_savings_in_usd: Option<u64>, + pub signature_network: Option<String>, + pub is_issuer_regulated: Option<bool>, } #[derive(Debug, serde::Serialize)] diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index 0365d4b6d50..c2e6bc76c06 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -124,6 +124,13 @@ impl CoBadgedCardNetworks { pub fn get_card_networks(&self) -> Vec<common_enums::CardNetwork> { self.0.iter().map(|info| info.network.clone()).collect() } + + pub fn get_signature_network(&self) -> Option<common_enums::CardNetwork> { + self.0 + .iter() + .find(|info| info.network.is_signature_network()) + .map(|info| info.network.clone()) + } } impl From<&DebitRoutingOutput> for payment_methods::CoBadgedCardData { diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index d3a502c877b..2e9478dc250 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -1229,6 +1229,8 @@ impl From<CardDetailFromLocker> for payments::AdditionalCardInfo { card_holder_name: item.card_holder_name, payment_checks: None, authentication_data: None, + is_regulated: None, + signature_network: None, } } } @@ -1252,6 +1254,8 @@ impl From<CardDetailFromLocker> for payments::AdditionalCardInfo { card_holder_name: item.card_holder_name, payment_checks: None, authentication_data: None, + is_regulated: None, + signature_network: None, } } } diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 714ad7cb50a..d757c6cfb6f 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -2970,6 +2970,15 @@ pub struct AdditionalCardInfo { /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, + + /// Indicates if the card issuer is regulated under government-imposed interchange fee caps. + /// In the United States, this includes debit cards that fall under the Durbin Amendment, + /// which imposes capped interchange fees. + pub is_regulated: Option<bool>, + + /// The global signature network under which the card is issued. + /// This represents the primary global card brand, even if the transaction uses a local network + pub signature_network: Option<api_enums::CardNetwork>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index a895f0710c4..ec8d55ed000 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2599,7 +2599,7 @@ pub enum DecisionEngineMerchantCategoryCode { } impl CardNetwork { - pub fn is_global_network(&self) -> bool { + pub fn is_signature_network(&self) -> bool { match self { Self::Interac | Self::Star diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index ceff3d161d6..a9d44566069 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -37,6 +37,8 @@ use error_stack::ResultExt; #[cfg(feature = "v2")] use masking::PeekInterface; use masking::Secret; +#[cfg(feature = "v1")] +use router_env::logger; #[cfg(feature = "v2")] use rustc_hash::FxHashMap; #[cfg(feature = "v1")] @@ -1109,6 +1111,19 @@ impl PaymentAttempt { .and_then(|data| data.get_additional_card_info()) .and_then(|card_info| card_info.card_network) } + + pub fn get_payment_method_data(&self) -> Option<api_models::payments::AdditionalPaymentData> { + self.payment_method_data + .clone() + .and_then(|data| match data { + serde_json::Value::Null => None, + _ => Some(data.parse_value("AdditionalPaymentData")), + }) + .transpose() + .map_err(|err| logger::error!("Failed to parse AdditionalPaymentData {err:?}")) + .ok() + .flatten() + } } #[derive(Clone, Debug, Eq, PartialEq)] diff --git a/crates/router/src/core/debit_routing.rs b/crates/router/src/core/debit_routing.rs index 0aeb2b9777b..34eaed42908 100644 --- a/crates/router/src/core/debit_routing.rs +++ b/crates/router/src/core/debit_routing.rs @@ -726,7 +726,7 @@ fn find_matching_networks( fee_sorted_debit_networks .iter() .filter(|network| merchant_debit_networks.contains(network)) - .filter(|network| is_routing_enabled || network.is_global_network()) + .filter(|network| is_routing_enabled || network.is_signature_network()) .map(|network| { if network.is_us_local_network() { *has_us_local_network = true; diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 8dd79f95d97..c8320bcc631 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -866,7 +866,7 @@ fn get_card_network_with_us_local_debit_network_override( data.co_badged_card_networks_info .0 .iter() - .find(|info| info.network.is_global_network()) + .find(|info| info.network.is_signature_network()) .cloned() }); info.map(|data| data.network) diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 87f47a9b2bb..1523a4b3c2b 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -4867,19 +4867,30 @@ pub async fn get_additional_payment_data( "Card cobadge check failed due to an invalid card network regex", )?; - let card_network = match ( - is_cobadged_based_on_regex, - card_data.co_badged_card_data.is_some(), - ) { - (false, false) => { + let (card_network, signature_network, is_regulated) = card_data + .co_badged_card_data + .as_ref() + .map(|co_badged_data| { + logger::debug!("Co-badged card data found"); + + ( + card_data.card_network.clone(), + co_badged_data + .co_badged_card_networks_info + .get_signature_network(), + Some(co_badged_data.is_regulated), + ) + }) + .or_else(|| { + is_cobadged_based_on_regex.then(|| { + logger::debug!("Card network is cobadged (regex-based detection)"); + (card_data.card_network.clone(), None, None) + }) + }) + .unwrap_or_else(|| { logger::debug!("Card network is not cobadged"); - None - } - _ => { - logger::debug!("Card network is cobadged"); - card_data.card_network.clone() - } - }; + (None, None, None) + }); let last4 = Some(card_data.card_number.get_last4()); if card_data.card_issuer.is_some() @@ -4904,6 +4915,8 @@ pub async fn get_additional_payment_data( // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, + is_regulated, + signature_network: signature_network.clone(), }), ))) } else { @@ -4934,6 +4947,8 @@ pub async fn get_additional_payment_data( // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, + is_regulated, + signature_network: signature_network.clone(), }, )) }); @@ -4954,6 +4969,8 @@ pub async fn get_additional_payment_data( // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, + is_regulated, + signature_network: signature_network.clone(), }, )) }))) @@ -5199,6 +5216,8 @@ pub async fn get_additional_payment_data( // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, + is_regulated: None, + signature_network: None, }), ))) } else { @@ -5229,6 +5248,8 @@ pub async fn get_additional_payment_data( // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, + is_regulated: None, + signature_network: None, }, )) }); @@ -5249,6 +5270,8 @@ pub async fn get_additional_payment_data( // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, + is_regulated: None, + signature_network: None, }, )) }))) diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs index 8a900019b7c..0d8dfd8704a 100644 --- a/crates/router/src/services/kafka/payment_attempt.rs +++ b/crates/router/src/services/kafka/payment_attempt.rs @@ -71,11 +71,16 @@ pub struct KafkaPaymentAttempt<'a> { pub card_discovery: Option<String>, pub routing_approach: Option<storage_enums::RoutingApproach>, pub debit_routing_savings: Option<MinorUnit>, + pub signature_network: Option<common_enums::CardNetwork>, + pub is_issuer_regulated: Option<bool>, } #[cfg(feature = "v1")] impl<'a> KafkaPaymentAttempt<'a> { pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { + let card_payment_method_data = attempt + .get_payment_method_data() + .and_then(|data| data.get_additional_card_info()); Self { payment_id: &attempt.payment_id, merchant_id: &attempt.merchant_id, @@ -134,6 +139,10 @@ impl<'a> KafkaPaymentAttempt<'a> { .map(|discovery| discovery.to_string()), routing_approach: attempt.routing_approach.clone(), debit_routing_savings: attempt.debit_routing_savings, + signature_network: card_payment_method_data + .as_ref() + .and_then(|data| data.signature_network.clone()), + is_issuer_regulated: card_payment_method_data.and_then(|data| data.is_regulated), } } } diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs index eea3916f803..5f87e017f85 100644 --- a/crates/router/src/services/kafka/payment_attempt_event.rs +++ b/crates/router/src/services/kafka/payment_attempt_event.rs @@ -72,11 +72,16 @@ pub struct KafkaPaymentAttemptEvent<'a> { pub card_discovery: Option<String>, pub routing_approach: Option<storage_enums::RoutingApproach>, pub debit_routing_savings: Option<MinorUnit>, + pub signature_network: Option<common_enums::CardNetwork>, + pub is_issuer_regulated: Option<bool>, } #[cfg(feature = "v1")] impl<'a> KafkaPaymentAttemptEvent<'a> { pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { + let card_payment_method_data = attempt + .get_payment_method_data() + .and_then(|data| data.get_additional_card_info()); Self { payment_id: &attempt.payment_id, merchant_id: &attempt.merchant_id, @@ -135,6 +140,10 @@ impl<'a> KafkaPaymentAttemptEvent<'a> { .map(|discovery| discovery.to_string()), routing_approach: attempt.routing_approach.clone(), debit_routing_savings: attempt.debit_routing_savings, + signature_network: card_payment_method_data + .as_ref() + .and_then(|data| data.signature_network.clone()), + is_issuer_regulated: card_payment_method_data.and_then(|data| data.is_regulated), } } }
2025-08-11T07:13: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 --> This pull request enhances how co-badged card information is handled, especially around identifying and propagating the card's "signature network" and whether the card issuer is regulated. * Extended the `AdditionalCardInfo` struct to include new fields: `is_regulated` (indicates if the issuer is regulated under interchange fee caps) and `signature_network` (the card's primary global brand). ### 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)? --> -> Enable debit routing for a profile -> Create adyen connector and enable local debit networks -> Make a card payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'x-tenant-id: hyperswitch' \ --header 'api-key: dev_5sRc7V4OXL2Qk52mr4qp5JLcgLPu3TlNOZ8M31eALWZcuOFaXhZX4FAZVT8VKgbX' \ --data-raw '{ "amount": 1000000, "amount_to_capture": 1000000, "currency": "USD", "confirm": true, "capture_method": "automatic", "setup_future_usage": "on_session", "capture_on": "2022-09-10T10:11:12Z", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "customer_id": "cu_1754896317", "return_url": "http://127.0.0.1:4040", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4400 0020 0000 0004", "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": "raj@gmail.com" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "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_C6Da6MjduSo3GYZD5Rv4", "merchant_id": "merchant_1754887772", "status": "processing", "amount": 1000000, "net_amount": 1000000, "shipping_cost": null, "amount_capturable": 1000000, "amount_received": null, "connector": "adyen", "client_secret": "pay_C6Da6MjduSo3GYZD5Rv4_secret_OnariiuxjA1PeO2GOpKW", "created": "2025-08-11T04:51:47.628Z", "currency": "USD", "customer_id": "cu_1754887908", "customer": { "id": "cu_1754887908", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0004", "card_type": null, "card_network": "Accel", "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, "origin_zip": 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", "origin_zip": null }, "phone": null, "email": "raj@gmail.com" }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": "905_1", "error_message": "Could not find an acquirer account for the provided txvariant (accel), currency (USD), and action (AUTH).", "unified_code": "UE_9000", "unified_message": "Something went wrong", "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_1754887908", "created_at": 1754887907, "expires": 1754891507, "secret": "epk_779c3dcfdc894107918575b408446962" }, "manual_retry_allowed": false, "connector_transaction_id": "SCTLC5JVNSRZ5TT5", "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_UsCIuOTX3On1bJUP7Dw3", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_HWuMPavh4o8pMXXypjKT", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-11T05:06:47.628Z", "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_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-11T04:51:48.673Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` Payment attempt db storage <img width="2206" height="891" alt="image" src="https://github.com/user-attachments/assets/d6cbb348-2f49-4603-b10a-a684df003232" /> -> Payment metric ``` curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --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 '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 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWQxMGYxOGUtZjMzNy00NDU5LWFhNTEtOTE3YWRiYTlmYWJiIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzU1MDA1MTY4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc1NTE3Nzk4Miwib3JnX2lkIjoib3JnX2NmYTlEaTJwdEN2YjFHU05jOXN1IiwicHJvZmlsZV9pZCI6InByb19NYTRrVzJjOFpobDJEeUFBQVZrTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.lP65o0BdE7w9La48HPn2MasV9MZaAaBp_WWI7A7iUdU' \ --data '[ { "timeRange": { "startTime": "2025-08-01T18:30:00Z", "endTime": "2025-09-30T09:22:00Z" }, "groupByNames": [ "card_network" ], "filters": { "routing_approach": [ "debit_routing" ] }, "source": "BATCH", "metrics": [ "debit_routing" ], "delta": true } ]' ``` ``` { "queryData": [ { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 0, "payment_processed_amount_in_usd": null, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": null, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_success_rate_distribution_with_only_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_with_only_retries": null, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "debit_routed_transaction_count": 1, "debit_routing_savings": 0, "debit_routing_savings_in_usd": null, "signature_network": "Visa", "is_issuer_regulated": true, "currency": "USD", "status": null, "connector": null, "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": "Accel", "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "routing_approach": null, "time_range": { "start_time": "2025-08-01T18:30:00.000Z", "end_time": "2025-09-30T09:22:00.000Z" }, "time_bucket": "2025-08-01 18:30:00" }, { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 0, "payment_processed_amount_in_usd": null, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": null, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_success_rate_distribution_with_only_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_with_only_retries": null, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "debit_routed_transaction_count": 4, "debit_routing_savings": 0, "debit_routing_savings_in_usd": null, "signature_network": "Visa", "is_issuer_regulated": true, "currency": "USD", "status": null, "connector": null, "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": "Star", "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "routing_approach": null, "time_range": { "start_time": "2025-08-01T18:30:00.000Z", "end_time": "2025-09-30T09:22:00.000Z" }, "time_bucket": "2025-08-01 18:30:00" } ], "metaData": [ { "total_payment_processed_amount": 0, "total_payment_processed_amount_in_usd": null, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_amount_without_smart_retries_usd": null, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0, "total_failure_reasons_count": 0, "total_failure_reasons_count_without_smart_retries": 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.116.0
5a09d7ec2ab66d901e29492521e63cc6a01281de
5a09d7ec2ab66d901e29492521e63cc6a01281de
juspay/hyperswitch
juspay__hyperswitch-8884
Bug: [FEATURE] Add Apple Pay Payment Method In Barclaycard ### Feature Description Add Apple Pay Payment Method In Barclaycard ### Possible Implementation Add Apple Pay Payment Method In Barclaycard ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index 00f7ba33a59..fdb5c2a0e5e 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -702,6 +702,7 @@ paze = { currency = "USD,SEK" } credit = { currency = "USD,GBP,EUR,PLN,SEK" } debit = { currency = "USD,GBP,EUR,PLN,SEK" } google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } +apple_pay = { currency = "ARS, CAD, CLP, COP, CNY, EUR, HKD, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, GBP, AED, USD, PLN, SEK" } [pm_filters.globepay] ali_pay = { country = "GB",currency = "GBP" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 40a0bdb137e..02b5a084f11 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -526,6 +526,7 @@ paze = { currency = "USD,SEK" } credit = { currency = "USD,GBP,EUR,PLN,SEK" } debit = { currency = "USD,GBP,EUR,PLN,SEK" } google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } +apple_pay = { currency = "ARS, CAD, CLP, COP, CNY, EUR, HKD, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, GBP, AED, USD, PLN, SEK" } [pm_filters.itaubank] pix = { country = "BR", currency = "BRL" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index c4c37289fa1..9bebc017d1a 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -443,6 +443,7 @@ paze = { currency = "USD,SEK" } credit = { currency = "USD,GBP,EUR,PLN,SEK" } debit = { currency = "USD,GBP,EUR,PLN,SEK" } google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } +apple_pay = { currency = "ARS, CAD, CLP, COP, CNY, EUR, HKD, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, GBP, AED, USD, PLN, SEK" } [pm_filters.itaubank] pix = { country = "BR", currency = "BRL" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 171b4bf0987..b01733d1ae4 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -455,6 +455,7 @@ paze = { currency = "USD,SEK" } credit = { currency = "USD,GBP,EUR,PLN,SEK" } debit = { currency = "USD,GBP,EUR,PLN,SEK" } google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } +apple_pay = { currency = "ARS, CAD, CLP, COP, CNY, EUR, HKD, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, GBP, AED, USD, PLN, SEK" } [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,AU,BR,US", 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" } diff --git a/config/development.toml b/config/development.toml index a2d06e7d28e..6ed294918b6 100644 --- a/config/development.toml +++ b/config/development.toml @@ -621,6 +621,7 @@ paze = { currency = "USD,SEK" } credit = { currency = "USD,GBP,EUR,PLN,SEK" } debit = { currency = "USD,GBP,EUR,PLN,SEK" } google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } +apple_pay = { currency = "ARS, CAD, CLP, COP, CNY, EUR, HKD, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, GBP, AED, USD, PLN, SEK" } [pm_filters.globepay] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 544caf4c9f2..5ab5b481905 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -669,6 +669,7 @@ paze = { currency = "USD,SEK" } credit = { currency = "USD,GBP,EUR,PLN,SEK" } debit = { currency = "USD,GBP,EUR,PLN,SEK" } google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } +apple_pay = { currency = "ARS, CAD, CLP, COP, CNY, EUR, HKD, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, GBP, AED, USD, PLN, SEK" } [pm_filters.globepay] ali_pay = { country = "GB",currency = "GBP,CNY" } diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index bdedcf9d1f7..daf0119b9fe 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -1028,11 +1028,65 @@ options=["visa","masterCard","amex","discover"] payment_method_type = "UnionPay" [[barclaycard.wallet]] payment_method_type = "google_pay" +[[barclaycard.wallet]] + payment_method_type = "apple_pay" [barclaycard.connector_auth.SignatureKey] api_key="Key" key1="Merchant ID" api_secret="Shared Secret" +[[barclaycard.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[barclaycard.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[barclaycard.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[barclaycard.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[barclaycard.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[barclaycard.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[barclaycard.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[barclaycard.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + [[barclaycard.metadata.google_pay]] name = "merchant_name" label = "Google Pay Merchant Name" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 21c9f20fedc..61e58a1cc32 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -1032,11 +1032,65 @@ payment_method_type = "CartesBancaires" payment_method_type = "UnionPay" [[barclaycard.wallet]] payment_method_type = "google_pay" +[[barclaycard.wallet]] + payment_method_type = "apple_pay" [barclaycard.connector_auth.SignatureKey] api_key = "Key" key1 = "Merchant ID" api_secret = "Shared Secret" +[[barclaycard.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[barclaycard.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[barclaycard.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[barclaycard.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[barclaycard.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[barclaycard.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[barclaycard.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[barclaycard.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + [[barclaycard.metadata.google_pay]] name = "merchant_name" label = "Google Pay Merchant Name" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 597c3fb7276..217203879d4 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -1028,11 +1028,65 @@ payment_method_type = "CartesBancaires" payment_method_type = "UnionPay" [[barclaycard.wallet]] payment_method_type = "google_pay" +[[barclaycard.wallet]] + payment_method_type = "apple_pay" [barclaycard.connector_auth.SignatureKey] api_key = "Key" key1 = "Merchant ID" api_secret = "Shared Secret" +[[barclaycard.metadata.apple_pay]] +name="certificate" +label="Merchant Certificate (Base64 Encoded)" +placeholder="Enter Merchant Certificate (Base64 Encoded)" +required=true +type="Text" +[[barclaycard.metadata.apple_pay]] +name="certificate_keys" +label="Merchant PrivateKey (Base64 Encoded)" +placeholder="Enter Merchant PrivateKey (Base64 Encoded)" +required=true +type="Text" +[[barclaycard.metadata.apple_pay]] +name="merchant_identifier" +label="Apple Merchant Identifier" +placeholder="Enter Apple Merchant Identifier" +required=true +type="Text" +[[barclaycard.metadata.apple_pay]] +name="display_name" +label="Display Name" +placeholder="Enter Display Name" +required=true +type="Text" +[[barclaycard.metadata.apple_pay]] +name="initiative" +label="Domain" +placeholder="Enter Domain" +required=true +type="Select" +options=["web","ios"] +[[barclaycard.metadata.apple_pay]] +name="initiative_context" +label="Domain Name" +placeholder="Enter Domain Name" +required=true +type="Text" +[[barclaycard.metadata.apple_pay]] +name="merchant_business_country" +label="Merchant Business Country" +placeholder="Enter Merchant Business Country" +required=true +type="Select" +options=[] +[[barclaycard.metadata.apple_pay]] +name="payment_processing_details_at" +label="Payment Processing Details At" +placeholder="Enter Payment Processing Details At" +required=true +type="Radio" +options=["Connector","Hyperswitch"] + [[barclaycard.metadata.google_pay]] name = "merchant_name" label = "Google Pay Merchant Name" diff --git a/crates/hyperswitch_connectors/src/connectors/barclaycard.rs b/crates/hyperswitch_connectors/src/connectors/barclaycard.rs index 98843a068f4..7a1e09a24f2 100644 --- a/crates/hyperswitch_connectors/src/connectors/barclaycard.rs +++ b/crates/hyperswitch_connectors/src/connectors/barclaycard.rs @@ -1315,6 +1315,17 @@ static BARCLAYCARD_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> barclaycard_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::GooglePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + barclaycard_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::ApplePay, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, diff --git a/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs b/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs index 9d78d9de9a4..6be869fa217 100644 --- a/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs @@ -1,5 +1,6 @@ use base64::Engine; use common_enums::enums; +use common_types::payments::ApplePayPredecryptData; use common_utils::{ consts, date_time, ext_traits::ValueExt, @@ -8,10 +9,10 @@ use common_utils::{ }; use error_stack::ResultExt; use hyperswitch_domain_models::{ - payment_method_data::{GooglePayWalletData, PaymentMethodData, WalletData}, + payment_method_data::{ApplePayWalletData, GooglePayWalletData, PaymentMethodData, WalletData}, router_data::{ AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, - ErrorResponse, RouterData, + ErrorResponse, PaymentMethodToken, RouterData, }, router_flow_types::refunds::{Execute, RSync}, router_request_types::{ @@ -33,6 +34,7 @@ use serde_json::Value; use crate::{ constants, types::{RefundsResponseRouterData, ResponseRouterData}, + unimplemented_payment_method, utils::{ self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, @@ -179,11 +181,44 @@ pub struct GooglePayPaymentInformation { fluid_data: FluidData, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TokenizedCard { + number: cards::CardNumber, + expiration_month: Secret<String>, + expiration_year: Secret<String>, + cryptogram: Option<Secret<String>>, + transaction_type: TransactionType, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ApplePayTokenizedCard { + transaction_type: TransactionType, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ApplePayTokenPaymentInformation { + fluid_data: FluidData, + tokenized_card: ApplePayTokenizedCard, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ApplePayPaymentInformation { + tokenized_card: TokenizedCard, +} + +pub const FLUID_DATA_DESCRIPTOR: &str = "RklEPUNPTU1PTi5BUFBMRS5JTkFQUC5QQVlNRU5U"; + #[derive(Debug, Serialize)] #[serde(untagged)] pub enum PaymentInformation { Cards(Box<CardPaymentInformation>), GooglePay(Box<GooglePayPaymentInformation>), + ApplePay(Box<ApplePayPaymentInformation>), + ApplePayToken(Box<ApplePayTokenPaymentInformation>), } #[derive(Debug, Serialize)] @@ -202,6 +237,8 @@ pub struct Card { #[serde(rename_all = "camelCase")] pub struct FluidData { value: Secret<String>, + #[serde(skip_serializing_if = "Option::is_none")] + descriptor: Option<String>, } #[derive(Debug, Serialize)] @@ -289,12 +326,20 @@ fn get_barclaycard_card_type(card_network: common_enums::CardNetwork) -> Option< #[derive(Debug, Serialize)] pub enum PaymentSolution { GooglePay, + ApplePay, +} + +#[derive(Debug, Serialize)] +pub enum TransactionType { + #[serde(rename = "1")] + InApp, } impl From<PaymentSolution> for String { fn from(solution: PaymentSolution) -> Self { let payment_solution = match solution { PaymentSolution::GooglePay => "012", + PaymentSolution::ApplePay => "001", }; payment_solution.to_string() } @@ -338,7 +383,23 @@ impl Option<String>, ), ) -> Result<Self, Self::Error> { - let commerce_indicator = get_commerce_indicator(network); + let commerce_indicator = solution + .as_ref() + .map(|pm_solution| match pm_solution { + PaymentSolution::ApplePay => network + .as_ref() + .map(|card_network| match card_network.to_lowercase().as_str() { + "amex" => "internet", + "discover" => "internet", + "mastercard" => "spa", + "visa" => "internet", + _ => "internet", + }) + .unwrap_or("internet"), + PaymentSolution::GooglePay => "internet", + }) + .unwrap_or("internet") + .to_string(); let cavv_algorithm = Some("2".to_string()); Ok(Self { capture: Some(matches!( @@ -1278,6 +1339,90 @@ impl } } +impl + TryFrom<( + &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, + Box<ApplePayPredecryptData>, + ApplePayWalletData, + )> for BarclaycardPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, apple_pay_data, apple_pay_wallet_data): ( + &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, + Box<ApplePayPredecryptData>, + ApplePayWalletData, + ), + ) -> Result<Self, Self::Error> { + let email = item + .router_data + .get_billing_email() + .or(item.router_data.request.get_email())?; + let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?; + let order_information = OrderInformationWithBill::from((item, Some(bill_to))); + let processing_information = + ProcessingInformation::try_from((item, Some(PaymentSolution::ApplePay), None))?; + let client_reference_information = ClientReferenceInformation::from(item); + let expiration_month = apple_pay_data.get_expiry_month().change_context( + errors::ConnectorError::InvalidDataFormat { + field_name: "expiration_month", + }, + )?; + let expiration_year = apple_pay_data.get_four_digit_expiry_year(); + let payment_information = + PaymentInformation::ApplePay(Box::new(ApplePayPaymentInformation { + tokenized_card: TokenizedCard { + number: apple_pay_data.application_primary_account_number, + cryptogram: Some(apple_pay_data.payment_data.online_payment_cryptogram), + transaction_type: TransactionType::InApp, + expiration_year, + expiration_month, + }, + })); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(convert_metadata_to_merchant_defined_info); + let ucaf_collection_indicator = match apple_pay_wallet_data + .payment_method + .network + .to_lowercase() + .as_str() + { + "mastercard" => Some("2".to_string()), + _ => None, + }; + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + consumer_authentication_information: Some(BarclaycardConsumerAuthInformation { + ucaf_collection_indicator, + cavv: None, + ucaf_authentication_data: None, + xid: None, + directory_server_transaction_id: None, + specification_version: None, + pa_specification_version: None, + veres_enrolled: None, + eci_raw: None, + pares_status: None, + authentication_date: None, + effective_authentication_type: None, + challenge_code: None, + pares_status_reason: None, + challenge_cancel_code: None, + network_score: None, + acs_transaction_id: None, + }), + merchant_defined_information, + }) + } +} + impl TryFrom<&BarclaycardRouterData<&PaymentsAuthorizeRouterData>> for BarclaycardPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( @@ -1287,11 +1432,105 @@ impl TryFrom<&BarclaycardRouterData<&PaymentsAuthorizeRouterData>> for Barclayca PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), PaymentMethodData::Wallet(wallet_data) => match wallet_data { WalletData::GooglePay(google_pay_data) => Self::try_from((item, google_pay_data)), + WalletData::ApplePay(apple_pay_data) => { + match item.router_data.payment_method_token.clone() { + Some(payment_method_token) => match payment_method_token { + PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { + Self::try_from((item, decrypt_data, apple_pay_data)) + } + PaymentMethodToken::Token(_) => Err(unimplemented_payment_method!( + "Apple Pay", + "Manual", + "Cybersource" + ))?, + PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Cybersource"))? + } + PaymentMethodToken::GooglePayDecrypt(_) => { + Err(unimplemented_payment_method!("Google Pay", "Cybersource"))? + } + }, + None => { + let transaction_type = TransactionType::InApp; + let email = item + .router_data + .get_billing_email() + .or(item.router_data.request.get_email())?; + let bill_to = + build_bill_to(item.router_data.get_billing_address()?, email)?; + let order_information = + OrderInformationWithBill::from((item, Some(bill_to))); + let processing_information = ProcessingInformation::try_from(( + item, + Some(PaymentSolution::ApplePay), + Some(apple_pay_data.payment_method.network.clone()), + ))?; + let client_reference_information = + ClientReferenceInformation::from(item); + + let apple_pay_encrypted_data = apple_pay_data + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + })?; + let payment_information = PaymentInformation::ApplePayToken(Box::new( + ApplePayTokenPaymentInformation { + fluid_data: FluidData { + value: Secret::from(apple_pay_encrypted_data.clone()), + descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()), + }, + tokenized_card: ApplePayTokenizedCard { transaction_type }, + }, + )); + let merchant_defined_information = + item.router_data.request.metadata.clone().map(|metadata| { + convert_metadata_to_merchant_defined_info(metadata) + }); + let ucaf_collection_indicator = match apple_pay_data + .payment_method + .network + .to_lowercase() + .as_str() + { + "mastercard" => Some("2".to_string()), + _ => None, + }; + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + merchant_defined_information, + consumer_authentication_information: Some( + BarclaycardConsumerAuthInformation { + ucaf_collection_indicator, + cavv: None, + ucaf_authentication_data: None, + xid: None, + directory_server_transaction_id: None, + specification_version: None, + pa_specification_version: None, + veres_enrolled: None, + eci_raw: None, + pares_status: None, + authentication_date: None, + effective_authentication_type: None, + challenge_code: None, + pares_status_reason: None, + challenge_cancel_code: None, + network_score: None, + acs_transaction_id: None, + }, + ), + }) + } + } + } WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::AmazonPayRedirect(_) - | WalletData::ApplePay(_) | WalletData::MomoRedirect(_) | WalletData::KakaoPayRedirect(_) | WalletData::GoPayRedirect(_) @@ -2671,6 +2910,7 @@ impl TryFrom<&GooglePayWalletData> for PaymentInformation { .clone(), ), ), + descriptor: None, }, }))) }
2025-08-08T20:13:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/8884) ## Description <!-- Describe your changes in detail --> Added Apple Pay Flow for Barclaycard ### 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 <details> <summary>Hyperswitch Decryption Flow </summary> 1. Payment Connector - Create Request: ``` curl --location 'http://localhost:8080/account/merchant_1755085109/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_taZoWveMbydxSkllyD5IB1sPHXNYOLLR2iveHgisLDodWCnHUkaXOF5k8RS8jMFC' \ --data '{ "connector_type": "payment_processor", "connector_name": "barclaycard", "connector_account_details": { "auth_type":"SignatureKey", "api_secret": API_SECRET "api_key": API_KEY, "key1": KEY1 }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false } ] } ], "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": CERTIFICATE, "display_name": "Applepay", "certificate_keys": CERTIFICATE_KEYS, "initiative_context": INITIATIVE_CONTEXT, "merchant_identifier": MERCHANT_IDENTIFIER "merchant_business_country": "US", "payment_processing_details_at": "Hyperswitch", "payment_processing_certificate": PAYMENT_PROCESSING_CERTIFICATE, "payment_processing_certificate_key": PAYMENT_PROCESSING_CERTIFICATE_KEY, }, "payment_request_data": { "label": "Applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } }, "business_country": "US", "business_label": "default" }' ``` Response: ``` { "connector_type": "payment_processor", "connector_name": "barclaycard", "connector_label": "barclaycard_US_default", "merchant_connector_id": "mca_eS9yhJMxUdKy4eZJ1Ea1", "profile_id": "pro_v4sNqtQqIhqC7zNvjBna", "connector_account_details": { "auth_type": "SignatureKey", "api_key": API_KEY, "key1": KEY1, "api_secret": API_SECRET }, "payment_methods_enabled": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "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": null, "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "web", "certificate": CERTIFICATE, "display_name": "Applepay", "certificate_keys": CERTIFICATE_KEYS, "initiative_context": INITIATIVE_CONTEXT, "merchant_identifier": MERCHANT_IDENTIFIER, "merchant_business_country": "US", "payment_processing_details_at": "Hyperswitch", "payment_processing_certificate": PAYMENT_PROCESSING_CERTIFICATE, "payment_processing_certificate_key": PAYMENT_PROCESSING_CERTIFICATE_KEY }, "payment_request_data": { "label": "Applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } }, "test_mode": true, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": { "apple_pay_combined": { "manual": { "payment_request_data": { "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ], "label": "Applepay" }, "session_token_data": { "certificate": CERTIFICATE, "certificate_keys": CERTIFICATE_KEYS, "merchant_identifier": MERCHANT_IDENTIFIER, "display_name": "Applepay", "initiative": "web", "initiative_context": INITIATIVE_CONTEXT, "merchant_business_country": "US", "payment_processing_details_at": "Hyperswitch", "payment_processing_certificate": PAYMENT_PROCESSING_CERTIFICATE, "payment_processing_certificate_key": PAYMENT_PROCESSING_CERTIFICATE_KEY } } } } } ``` 2. Payments - Create Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_taZoWveMbydxSkllyD5IB1sPHXNYOLLR2iveHgisLDodWCnHUkaXOF5k8RS8jMFC' \ --data-raw '{ "amount": 650, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 650, "customer_id": "cu_1752502119", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "setup_future_usage": "off_session", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "billing": { "address": { "line1": "1467", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": NUMBER "country_code": "+91" } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data": PAYMENT_DATA, "display_name": "MasterCard 0049", "network": "MasterCard", "type": "credit" }, "transaction_identifier": TRANSACTION_IDENTIFIER } } }, "shipping": { "phone": { "number": "4081234567" }, "email": EMAIL } }' ``` Response: ``` { "payment_id": "pay_ytnuQR2VsUo0pTAPUlvy", "merchant_id": "merchant_1755085109", "status": "succeeded", "amount": 650, "net_amount": 650, "shipping_cost": null, "amount_capturable": 0, "amount_received": 650, "connector": "barclaycard", "client_secret": "pay_ytnuQR2VsUo0pTAPUlvy_secret_pdWZPEULnUSv9XOzVUaF", "created": "2025-08-13T11:38:39.949Z", "currency": "USD", "customer_id": "cu_1752502119", "customer": { "id": "cu_1752502119", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "apple_pay": { "last4": "0049", "card_network": "MasterCard", "type": "credit" } }, "billing": null }, "payment_token": null, "shipping": { "address": null, "phone": { "number": "4081234567", "country_code": null }, "email": EMAIL }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": null, "line3": null, "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "phone": { "number": NUMBER, "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "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": "apple_pay", "connector_label": "barclaycard_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1752502119", "created_at": 1755085119, "expires": 1755088719, "secret": "SECRET }, "manual_retry_allowed": false, "connector_transaction_id": "7550851222606001203813", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_ytnuQR2VsUo0pTAPUlvy_1", "payment_link": null, "profile_id": "pro_v4sNqtQqIhqC7zNvjBna", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_eS9yhJMxUdKy4eZJ1Ea1", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-13T11:53:39.949Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-13T11:38:43.164Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details> <details> <summary>Connector Decryption Flow </summary> 1. Payment Connector - Create Request: ``` curl --location 'http://localhost:8080/account/merchant_1757312693/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_tO4QhL39rQMDHYzzbfwpngxQRd7PfKBjb3H9h0ngxbMUeLjNovXFBbIRDfRhBkKk' \ --data '{ "connector_type": "payment_processor", "connector_name": "barclaycard", "connector_account_details": { "auth_type": "SignatureKey", "api_secret": API_SECRET, "api_key": API_KEY, "key1": KEY1 }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false } ] } ], "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "ios", "certificate": CERTIFICATE, "display_name": "Barclaycard via Hyperswitch", "certificate_keys": CERTIFICATE_KEYS, "merchant_identifier": MERCHANT_IDENTIFIER, "merchant_business_country": MERCHANT_BUSINESS_COUNTRY, "payment_processing_details_at": "Connector" }, "payment_request_data": { "label": "Cybersource via Hyperswitch", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` Response: ``` { "connector_type": "payment_processor", "connector_name": "barclaycard", "connector_label": "barclaycard_US_default", "merchant_connector_id": "mca_dQAvxu5nKalC1YM9Nh4c", "profile_id": "pro_PbbZjjifqFiYwIXrlBjq", "connector_account_details": { "auth_type": "SignatureKey", "api_key": API_KEY, "key1": KEY1, "api_secret": API_SECRET }, "payment_methods_enabled": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "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": "MyWebhookSecret", "additional_secret": null }, "metadata": { "apple_pay_combined": { "manual": { "session_token_data": { "initiative": "ios", "certificate": CERTIFICATE, "display_name": "Barclaycard via Hyperswitch", "certificate_keys": CERTIFICATE_KEYS, "merchant_identifier": MERCHANT_IDENTIFIER, "merchant_business_country": MERCHANT_BUSINESS_COUNTRY, "payment_processing_details_at": "Connector" }, "payment_request_data": { "label": "Barclaycard via Hyperswitch", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } }, "test_mode": true, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": { "apple_pay_combined": { "manual": { "payment_request_data": { "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ], "label": "Barclaycard via Hyperswitch" }, "session_token_data": { "certificate": CERTIFICATE, "certificate_keys": CERTIFICATE_KEYS, "merchant_identifier": MERCHANT_IDENTIFIER, "display_name": MERCHANT_BUSINESS_COUNTRY, "initiative": "ios", "initiative_context": null, "merchant_business_country": MERCHANT_BUSINESS_COUNTRY, "payment_processing_details_at": "Connector" } } } } } ``` 2. Payments - Create Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_tO4QhL39rQMDHYzzbfwpngxQRd7PfKBjb3H9h0ngxbMUeLjNovXFBbIRDfRhBkKk' \ --data-raw '{ "amount": 2229, "currency": "USD", "confirm": true, "customer_id": "gmail", "email": "email@email.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "guest@example.com" }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data": PAYMENT_DATA, "payment_method": { "display_name": "MasterCard 0049", "network": "MasterCard", "type": "credit" }, "transaction_identifier": TRANSACTION_IDENTIFIER } } }, "payment_method": "wallet", "payment_method_type": "apple_pay" }' ``` Response: ``` { "payment_id": "pay_PGO6Zpfp4QqUUVrcV69m", "merchant_id": "merchant_1757312693", "status": "succeeded", "amount": 2229, "net_amount": 2229, "shipping_cost": null, "amount_capturable": 0, "amount_received": 2229, "connector": "barclaycard", "client_secret": "pay_PGO6Zpfp4QqUUVrcV69m_secret_4NqlDHVTMiECtyKhMRgN", "created": "2025-09-08T06:25:44.739Z", "currency": "USD", "customer_id": "gmail", "customer": { "id": "gmail", "name": null, "email": "email@email.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "wallet", "payment_method_data": { "wallet": { "apple_pay": { "last4": "0049", "card_network": "MasterCard", "type": "credit" } }, "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", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "guest@example.com" }, "order_details": null, "email": "email@email.com", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "apple_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "gmail", "created_at": 1757312744, "expires": 1757316344, "secret": "epk_972bbb09245349088a4f2eb20ffb472e" }, "manual_retry_allowed": false, "connector_transaction_id": "7573127477466909504807", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "pay_PGO6Zpfp4QqUUVrcV69m_1", "payment_link": null, "profile_id": "pro_PbbZjjifqFiYwIXrlBjq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_dQAvxu5nKalC1YM9Nh4c", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-09-08T06:40:44.739Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-09-08T06:25:48.784Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": 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.116.0
f5db00352b90e99e78b631fa8b9cde5800093a9d
f5db00352b90e99e78b631fa8b9cde5800093a9d
juspay/hyperswitch
juspay__hyperswitch-8893
Bug: [FEATURE] nuvie : Avs,cvv check, postConfirmVoid,0$ txn ### Feature Description Add / fix nuvie related features ### Possible Implementation - Avs,cvv check, - postConfirmVoid - 0$ txn ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei.rs b/crates/hyperswitch_connectors/src/connectors/nuvei.rs index 853b9fd968a..e02168e1f41 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei.rs @@ -18,13 +18,13 @@ use hyperswitch_domain_models::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, - AuthorizeSessionToken, CompleteAuthorize, PreProcessing, + AuthorizeSessionToken, CompleteAuthorize, PostCaptureVoid, PreProcessing, }, router_request_types::{ AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, - PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, - RefundsData, SetupMandateRequestData, + PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsPreProcessingData, + PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, @@ -32,8 +32,9 @@ use hyperswitch_domain_models::{ }, types::{ PaymentsAuthorizeRouterData, PaymentsAuthorizeSessionTokenRouterData, - PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, - PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundsRouterData, + PaymentsCancelPostCaptureRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, + PaymentsSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ @@ -131,7 +132,7 @@ impl api::RefundSync for Nuvei {} impl api::PaymentsCompleteAuthorize for Nuvei {} impl api::ConnectorAccessToken for Nuvei {} impl api::PaymentsPreProcessing for Nuvei {} - +impl api::PaymentPostCaptureVoid for Nuvei {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Nuvei { fn build_request( &self, @@ -175,7 +176,6 @@ impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResp ) -> CustomResult<RequestContent, errors::ConnectorError> { let meta: nuvei::NuveiMeta = utils::to_connector_meta(req.request.connector_meta.clone())?; let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, meta.session_token))?; - Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( @@ -209,7 +209,6 @@ impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResp .response .parse_struct("NuveiPaymentsResponse") .switch()?; - event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -309,6 +308,90 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nu } } +impl ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData> + for Nuvei +{ + fn get_headers( + &self, + req: &PaymentsCancelPostCaptureRouterData, + 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: &PaymentsCancelPostCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}ppp/api/v1/voidTransaction.do", + ConnectorCommon::base_url(self, connectors) + )) + } + + fn get_request_body( + &self, + req: &PaymentsCancelPostCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = nuvei::NuveiVoidRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsCancelPostCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsPostCaptureVoidType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsPostCaptureVoidType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsPostCaptureVoidType::get_request_body( + self, req, connectors, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &PaymentsCancelPostCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCancelPostCaptureRouterData, errors::ConnectorError> { + let response: nuvei::NuveiPaymentsResponse = res + .response + .parse_struct("NuveiPaymentsResponse") + .switch()?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nuvei {} impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nuvei { @@ -509,7 +592,6 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, req.get_session_token()?))?; - Ok(RequestContent::Json(Box::new(connector_req))) } @@ -545,7 +627,6 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData .response .parse_struct("NuveiPaymentsResponse") .switch()?; - event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -683,7 +764,6 @@ impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResp _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, req.get_session_token()?))?; - Ok(RequestContent::Json(Box::new(connector_req))) } @@ -719,7 +799,6 @@ impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResp .response .parse_struct("NuveiPaymentsResponse") .switch()?; - event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -802,7 +881,6 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nuvei { .response .parse_struct("NuveiPaymentsResponse") .switch()?; - event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -849,33 +927,75 @@ impl IncomingWebhook for Nuvei { _merchant_id: &id_type::MerchantId, connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - let body = serde_urlencoded::from_str::<nuvei::NuveiWebhookDetails>(&request.query_params) + // Parse the webhook payload + let webhook = serde_urlencoded::from_str::<nuvei::NuveiWebhook>(&request.query_params) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + let secret_str = std::str::from_utf8(&connector_webhook_secrets.secret) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - let status = format!("{:?}", body.status).to_uppercase(); - let to_sign = format!( - "{}{}{}{}{}{}{}", - secret_str, - body.total_amount, - body.currency, - body.response_time_stamp, - body.ppp_transaction_id, - status, - body.product_id - ); - Ok(to_sign.into_bytes()) + + // Generate signature based on webhook type + match webhook { + nuvei::NuveiWebhook::PaymentDmn(notification) => { + // For payment DMNs, use the same format as before + let status = notification + .transaction_status + .as_ref() + .map(|s| format!("{s:?}").to_uppercase()) + .unwrap_or_else(|| "UNKNOWN".to_string()); + + let to_sign = transformers::concat_strings(&[ + secret_str.to_string(), + notification.total_amount.unwrap_or_default(), + notification.currency.unwrap_or_default(), + notification.response_time_stamp.unwrap_or_default(), + notification.ppp_transaction_id.unwrap_or_default(), + status, + notification.product_id.unwrap_or_default(), + ]); + Ok(to_sign.into_bytes()) + } + nuvei::NuveiWebhook::Chargeback(notification) => { + // For chargeback notifications, use a different format based on Nuvei's documentation + // Note: This is a placeholder - you'll need to adjust based on Nuvei's actual chargeback signature format + let status = notification + .status + .as_ref() + .map(|s| format!("{s:?}").to_uppercase()) + .unwrap_or_else(|| "UNKNOWN".to_string()); + + let to_sign = transformers::concat_strings(&[ + secret_str.to_string(), + notification.chargeback_amount.unwrap_or_default(), + notification.chargeback_currency.unwrap_or_default(), + notification.ppp_transaction_id.unwrap_or_default(), + status, + ]); + Ok(to_sign.into_bytes()) + } + } } fn get_webhook_object_reference_id( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { - let body = - serde_urlencoded::from_str::<nuvei::NuveiWebhookTransactionId>(&request.query_params) - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + // Parse the webhook payload + let webhook = serde_urlencoded::from_str::<nuvei::NuveiWebhook>(&request.query_params) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + + // Extract transaction ID from the webhook + let transaction_id = match &webhook { + nuvei::NuveiWebhook::PaymentDmn(notification) => { + notification.ppp_transaction_id.clone().unwrap_or_default() + } + nuvei::NuveiWebhook::Chargeback(notification) => { + notification.ppp_transaction_id.clone().unwrap_or_default() + } + }; + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - PaymentIdType::ConnectorTransactionId(body.ppp_transaction_id), + PaymentIdType::ConnectorTransactionId(transaction_id), )) } @@ -883,15 +1003,29 @@ impl IncomingWebhook for Nuvei { &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { - let body = - serde_urlencoded::from_str::<nuvei::NuveiWebhookDataStatus>(&request.query_params) - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - match body.status { - nuvei::NuveiWebhookStatus::Approved => Ok(IncomingWebhookEvent::PaymentIntentSuccess), - nuvei::NuveiWebhookStatus::Declined => Ok(IncomingWebhookEvent::PaymentIntentFailure), - nuvei::NuveiWebhookStatus::Unknown - | nuvei::NuveiWebhookStatus::Pending - | nuvei::NuveiWebhookStatus::Update => Ok(IncomingWebhookEvent::EventNotSupported), + // Parse the webhook payload + let webhook = serde_urlencoded::from_str::<nuvei::NuveiWebhook>(&request.query_params) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + + // Map webhook type to event type + match webhook { + nuvei::NuveiWebhook::PaymentDmn(notification) => { + match notification.transaction_status { + Some(nuvei::TransactionStatus::Approved) + | Some(nuvei::TransactionStatus::Settled) => { + Ok(IncomingWebhookEvent::PaymentIntentSuccess) + } + Some(nuvei::TransactionStatus::Declined) + | Some(nuvei::TransactionStatus::Error) => { + Ok(IncomingWebhookEvent::PaymentIntentFailure) + } + _ => Ok(IncomingWebhookEvent::EventNotSupported), + } + } + nuvei::NuveiWebhook::Chargeback(_) => { + // Chargeback notifications always map to dispute opened + Ok(IncomingWebhookEvent::DisputeOpened) + } } } @@ -899,9 +1033,12 @@ impl IncomingWebhook for Nuvei { &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - let body = serde_urlencoded::from_str::<nuvei::NuveiWebhookDetails>(&request.query_params) + // Parse the webhook payload + let webhook = serde_urlencoded::from_str::<nuvei::NuveiWebhook>(&request.query_params) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - let payment_response = nuvei::NuveiPaymentsResponse::from(body); + + // Convert webhook to payments response + let payment_response = nuvei::NuveiPaymentsResponse::from(webhook); Ok(Box::new(payment_response)) } diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 9cc8476a4f4..6a2e26bc056 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -1,9 +1,10 @@ -use common_enums::enums; +use common_enums::{enums, CaptureMethod, PaymentChannel}; use common_utils::{ crypto::{self, GenerateDigest}, date_time, ext_traits::{Encode, OptionExt}, fp_utils, + id_type::CustomerId, pii::{Email, IpAddress}, request::Method, }; @@ -14,10 +15,13 @@ use hyperswitch_domain_models::{ self, ApplePayWalletData, BankRedirectData, GooglePayWalletData, PayLaterData, PaymentMethodData, WalletData, }, - router_data::{ConnectorAuthType, ErrorResponse, RouterData}, + router_data::{ + AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, + ErrorResponse, RouterData, + }, router_flow_types::{ refunds::{Execute, RSync}, - Authorize, Capture, CompleteAuthorize, PSync, Void, + Authorize, Capture, CompleteAuthorize, PSync, PostCaptureVoid, Void, }, router_request_types::{ authentication::MessageExtensionAttribute, BrowserInformation, PaymentsAuthorizeData, @@ -41,7 +45,7 @@ use crate::{ PaymentsPreprocessingResponseRouterData, RefundsResponseRouterData, ResponseRouterData, }, utils::{ - self, AddressDetailsData, BrowserInformationData, ForeignTryFrom, + self, missing_field_err, AddressDetailsData, BrowserInformationData, ForeignTryFrom, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, PaymentsPreProcessingRequestData, RouterData as _, }, @@ -61,21 +65,26 @@ fn to_boolean(string: String) -> bool { trait NuveiAuthorizePreprocessingCommon { fn get_browser_info(&self) -> Option<BrowserInformation>; fn get_related_transaction_id(&self) -> Option<String>; - fn get_email_required(&self) -> Result<Email, error_stack::Report<errors::ConnectorError>>; fn get_setup_mandate_details(&self) -> Option<MandateData>; fn get_complete_authorize_url(&self) -> Option<String>; + fn get_is_moto(&self) -> Option<bool>; fn get_connector_mandate_id(&self) -> Option<String>; fn get_return_url_required( &self, ) -> Result<String, error_stack::Report<errors::ConnectorError>>; - fn get_capture_method(&self) -> Option<enums::CaptureMethod>; + fn get_capture_method(&self) -> Option<CaptureMethod>; fn get_amount_required(&self) -> Result<i64, error_stack::Report<errors::ConnectorError>>; + fn get_customer_id_required(&self) -> Option<CustomerId>; + fn get_email_required(&self) -> Result<Email, error_stack::Report<errors::ConnectorError>>; fn get_currency_required( &self, ) -> Result<enums::Currency, error_stack::Report<errors::ConnectorError>>; fn get_payment_method_data_required( &self, ) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>>; + fn get_order_tax_amount( + &self, + ) -> Result<Option<i64>, error_stack::Report<errors::ConnectorError>>; } impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData { @@ -86,9 +95,15 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData { fn get_related_transaction_id(&self) -> Option<String> { self.related_transaction_id.clone() } + fn get_is_moto(&self) -> Option<bool> { + match self.payment_channel { + Some(PaymentChannel::MailOrder) | Some(PaymentChannel::TelephoneOrder) => Some(true), + _ => None, + } + } - fn get_email_required(&self) -> Result<Email, error_stack::Report<errors::ConnectorError>> { - self.get_email() + fn get_customer_id_required(&self) -> Option<CustomerId> { + self.customer_id.clone() } fn get_setup_mandate_details(&self) -> Option<MandateData> { @@ -109,7 +124,7 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData { self.get_router_return_url() } - fn get_capture_method(&self) -> Option<enums::CaptureMethod> { + fn get_capture_method(&self) -> Option<CaptureMethod> { self.capture_method } @@ -127,6 +142,15 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData { ) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>> { Ok(self.payment_method_data.clone()) } + fn get_order_tax_amount( + &self, + ) -> Result<Option<i64>, error_stack::Report<errors::ConnectorError>> { + Ok(self.order_tax_amount.map(|tax| tax.get_amount_as_i64())) + } + + fn get_email_required(&self) -> Result<Email, error_stack::Report<errors::ConnectorError>> { + self.get_email() + } } impl NuveiAuthorizePreprocessingCommon for PaymentsPreProcessingData { @@ -138,10 +162,16 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsPreProcessingData { self.related_transaction_id.clone() } + fn get_is_moto(&self) -> Option<bool> { + None + } + + fn get_customer_id_required(&self) -> Option<CustomerId> { + None + } fn get_email_required(&self) -> Result<Email, error_stack::Report<errors::ConnectorError>> { self.get_email() } - fn get_setup_mandate_details(&self) -> Option<MandateData> { self.setup_mandate_details.clone() } @@ -160,7 +190,7 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsPreProcessingData { self.get_router_return_url() } - fn get_capture_method(&self) -> Option<enums::CaptureMethod> { + fn get_capture_method(&self) -> Option<CaptureMethod> { self.capture_method } @@ -183,6 +213,11 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsPreProcessingData { .into(), ) } + fn get_order_tax_amount( + &self, + ) -> Result<Option<i64>, error_stack::Report<errors::ConnectorError>> { + Ok(None) + } } #[derive(Debug, Serialize, Default, Deserialize)] @@ -219,6 +254,11 @@ pub struct NuveiSessionResponse { pub client_request_id: String, } +#[derive(Debug, Serialize, Default)] +#[serde(rename_all = "camelCase")] +pub struct NuvieAmountDetails { + total_tax: Option<String>, +} #[serde_with::skip_serializing_none] #[derive(Debug, Serialize, Default)] #[serde(rename_all = "camelCase")] @@ -231,16 +271,19 @@ pub struct NuveiPaymentsRequest { pub amount: String, pub currency: enums::Currency, /// This ID uniquely identifies your consumer/user in your system. - pub user_token_id: Option<Email>, + pub user_token_id: Option<CustomerId>, + //unique transaction id pub client_unique_id: String, pub transaction_type: TransactionType, pub is_rebilling: Option<String>, pub payment_option: PaymentOption, - pub device_details: Option<DeviceDetails>, + pub is_moto: Option<bool>, + pub device_details: DeviceDetails, pub checksum: Secret<String>, pub billing_address: Option<BillingAddress>, pub related_transaction_id: Option<String>, pub url_details: Option<UrlDetails>, + pub amount_details: Option<NuvieAmountDetails>, } #[derive(Debug, Serialize, Default)] @@ -421,11 +464,24 @@ pub struct ThreeD { #[serde(rename = "merchantURL")] pub merchant_url: Option<String>, pub acs_url: Option<String>, + pub acs_challenge_mandate: Option<String>, pub c_req: Option<Secret<String>>, + pub three_d_flow: Option<String>, + pub external_transaction_id: Option<String>, + pub transaction_id: Option<String>, + pub three_d_reason_id: Option<String>, + pub three_d_reason: Option<String>, + pub challenge_preference_reason: Option<String>, + pub challenge_cancel_reason_id: Option<String>, + pub challenge_cancel_reason: Option<String>, + pub is_liability_on_issuer: Option<String>, + pub is_exemption_request_in_authentication: Option<String>, + pub flow: Option<String>, + pub acquirer_decision: Option<String>, + pub decision_reason: Option<String>, pub platform_type: Option<PlatformType>, pub v2supported: Option<String>, pub v2_additional_params: Option<V2AdditionalParams>, - pub is_liability_on_issuer: Option<LiabilityShift>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] @@ -479,11 +535,16 @@ pub struct DeviceDetails { pub ip_address: Secret<String, IpAddress>, } -impl From<enums::CaptureMethod> for TransactionType { - fn from(value: enums::CaptureMethod) -> Self { - match value { - enums::CaptureMethod::Manual => Self::Auth, - _ => Self::Sale, +impl TransactionType { + fn get_from_capture_method_and_amount_string( + capture_method: CaptureMethod, + amount: &str, + ) -> Self { + let amount_value = amount.parse::<f64>(); + if capture_method == CaptureMethod::Manual || amount_value == Ok(0.0) { + Self::Auth + } else { + Self::Sale } } } @@ -514,12 +575,14 @@ pub enum LiabilityShift { Failed, } -fn encode_payload(payload: &[&str]) -> Result<String, error_stack::Report<errors::ConnectorError>> { +pub fn encode_payload( + payload: &[&str], +) -> Result<String, error_stack::Report<errors::ConnectorError>> { let data = payload.join(""); let digest = crypto::Sha256 .generate_digest(data.as_bytes()) .change_context(errors::ConnectorError::RequestEncodingFailed) - .attach_printable("error encoding the payload")?; + .attach_printable("error encoding nuvie payload")?; Ok(hex::encode(digest)) } @@ -874,7 +937,7 @@ where .get_billing()? .address .as_ref() - .ok_or_else(utils::missing_field_err("billing.address"))?; + .ok_or_else(missing_field_err("billing.address"))?; let first_name = address.get_first_name()?; let payment_method = payment_method_type; Ok(NuveiPaymentsRequest { @@ -1041,9 +1104,16 @@ where ..Default::default() })?; let return_url = item.request.get_return_url_required()?; + + let amount_details = match item.request.get_order_tax_amount()? { + Some(tax) => Some(NuvieAmountDetails { + total_tax: Some(utils::to_currency_base_unit(tax, currency)?), + }), + None => None, + }; Ok(Self { is_rebilling: request_data.is_rebilling, - user_token_id: request_data.user_token_id, + user_token_id: item.customer_id.clone(), related_transaction_id: request_data.related_transaction_id, payment_option: request_data.payment_option, billing_address: request_data.billing_address, @@ -1051,8 +1121,10 @@ where url_details: Some(UrlDetails { success_url: return_url.clone(), failure_url: return_url.clone(), - pending_url: return_url, + pending_url: return_url.clone(), }), + amount_details, + ..request }) } @@ -1105,7 +1177,7 @@ where } }; let mandate_meta: NuveiMandateMeta = utils::to_connector_meta_from_secret(Some( - details.get_metadata().ok_or_else(utils::missing_field_err( + details.get_metadata().ok_or_else(missing_field_err( "mandate_data.mandate_type.{multi_use|single_use}.metadata", ))?, ))?; @@ -1116,14 +1188,14 @@ where details .get_end_date(date_time::DateFormat::YYYYMMDD) .change_context(errors::ConnectorError::DateFormattingFailed)? - .ok_or_else(utils::missing_field_err( + .ok_or_else(missing_field_err( "mandate_data.mandate_type.{multi_use|single_use}.end_date", ))?, ), rebill_frequency: Some(mandate_meta.frequency), challenge_window_size: None, }), - Some(item.request.get_email_required()?), + item.request.get_customer_id_required(), ) } _ => (None, None, None), @@ -1159,20 +1231,19 @@ where } else { None }; - + let is_moto = item.request.get_is_moto(); Ok(NuveiPaymentsRequest { related_transaction_id, is_rebilling, user_token_id, - device_details: Option::<DeviceDetails>::foreign_try_from( - &item.request.get_browser_info().clone(), - )?, + device_details: DeviceDetails::foreign_try_from(&item.request.get_browser_info().clone())?, payment_option: PaymentOption::from(NuveiCardDetails { card: card_details.clone(), three_d, card_holder_name: item.get_optional_billing_full_name(), }), billing_address, + is_moto, ..Default::default() }) } @@ -1265,16 +1336,17 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentsRequest { date_time::format_date(date_time::now(), date_time::DateFormat::YYYYMMDDHHmmss) .change_context(errors::ConnectorError::RequestEncodingFailed)?; let merchant_secret = connector_meta.merchant_secret; + let transaction_type = TransactionType::get_from_capture_method_and_amount_string( + request.capture_method.unwrap_or_default(), + &request.amount, + ); Ok(Self { merchant_id: merchant_id.clone(), merchant_site_id: merchant_site_id.clone(), client_request_id: Secret::new(client_request_id.clone()), time_stamp: time_stamp.clone(), session_token, - transaction_type: request - .capture_method - .map(TransactionType::from) - .unwrap_or_default(), + transaction_type, checksum: Secret::new(encode_payload(&[ merchant_id.peek(), merchant_site_id.peek(), @@ -1285,6 +1357,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentsRequest { merchant_secret.peek(), ])?), amount: request.amount, + user_token_id: None, currency: request.currency, ..Default::default() }) @@ -1332,7 +1405,7 @@ pub struct NuveiPaymentRequestData { pub client_request_id: String, pub connector_auth_type: ConnectorAuthType, pub session_token: Secret<String>, - pub capture_method: Option<enums::CaptureMethod>, + pub capture_method: Option<CaptureMethod>, } impl TryFrom<&types::PaymentsCaptureRouterData> for NuveiPaymentFlowRequest { @@ -1378,6 +1451,57 @@ impl TryFrom<&types::PaymentsSyncRouterData> for NuveiPaymentSyncRequest { } } +#[derive(Debug, Serialize, Default)] +#[serde(rename_all = "camelCase")] +pub struct NuveiVoidRequest { + pub merchant_id: Secret<String>, + pub merchant_site_id: Secret<String>, + pub client_unique_id: String, + pub related_transaction_id: String, + pub time_stamp: String, + pub checksum: Secret<String>, + pub client_request_id: String, +} + +impl TryFrom<&types::PaymentsCancelPostCaptureRouterData> for NuveiVoidRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsCancelPostCaptureRouterData) -> Result<Self, Self::Error> { + let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&item.connector_auth_type)?; + let merchant_id = connector_meta.merchant_id.clone(); + let merchant_site_id = connector_meta.merchant_site_id.clone(); + let merchant_secret = connector_meta.merchant_secret.clone(); + let client_unique_id = item.connector_request_reference_id.clone(); + let related_transaction_id = item.request.connector_transaction_id.clone(); + let client_request_id = item.connector_request_reference_id.clone(); + let time_stamp = + date_time::format_date(date_time::now(), date_time::DateFormat::YYYYMMDDHHmmss) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let checksum = Secret::new(encode_payload(&[ + merchant_id.peek(), + merchant_site_id.peek(), + &client_request_id, + &client_unique_id, + "", // amount (empty for void) + "", // currency (empty for void) + &related_transaction_id, + "", // authCode (empty) + "", // comment (empty) + &time_stamp, + merchant_secret.peek(), + ])?); + + Ok(Self { + merchant_id, + merchant_site_id, + client_unique_id, + related_transaction_id, + time_stamp, + checksum, + client_request_id, + }) + } +} + impl TryFrom<&types::PaymentsCancelRouterData> for NuveiPaymentFlowRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { @@ -1484,9 +1608,10 @@ pub struct NuveiPaymentsResponse { pub merchant_site_id: Option<Secret<String>>, pub version: Option<String>, pub client_request_id: Option<String>, + pub merchant_advice_code: Option<String>, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum NuveiTransactionType { Auth, Sale, @@ -1503,7 +1628,29 @@ pub struct FraudDetails { pub final_decision: String, } -fn get_payment_status(response: &NuveiPaymentsResponse) -> enums::AttemptStatus { +fn get_payment_status( + response: &NuveiPaymentsResponse, + amount: Option<i64>, +) -> enums::AttemptStatus { + // ZERO dollar authorization + if amount == Some(0) && response.transaction_type.clone() == Some(NuveiTransactionType::Auth) { + return match response.transaction_status.clone() { + Some(NuveiTransactionStatus::Approved) => enums::AttemptStatus::Charged, + Some(NuveiTransactionStatus::Declined) | Some(NuveiTransactionStatus::Error) => { + enums::AttemptStatus::AuthorizationFailed + } + Some(NuveiTransactionStatus::Pending) | Some(NuveiTransactionStatus::Processing) => { + enums::AttemptStatus::Pending + } + Some(NuveiTransactionStatus::Redirect) => enums::AttemptStatus::AuthenticationPending, + None => match response.status { + NuveiPaymentStatus::Failed | NuveiPaymentStatus::Error => { + enums::AttemptStatus::Failure + } + _ => enums::AttemptStatus::Pending, + }, + }; + } match response.transaction_status.clone() { Some(status) => match status { NuveiTransactionStatus::Approved => match response.transaction_type { @@ -1539,15 +1686,32 @@ fn get_payment_status(response: &NuveiPaymentsResponse) -> enums::AttemptStatus fn build_error_response<T>( response: &NuveiPaymentsResponse, http_code: u16, -) -> Option<Result<T, ErrorResponse>> { +) -> Option<Result<T, error_stack::Report<errors::ConnectorError>>> { match response.status { NuveiPaymentStatus::Error => Some( - get_error_response(response.err_code, &response.reason, http_code).map_err(|err| *err), + get_error_response( + response.err_code, + &response.reason, + http_code, + &response.merchant_advice_code, + &response.gw_error_code.map(|e| e.to_string()), + &response.gw_error_reason, + ) + .map_err(|_err| error_stack::report!(errors::ConnectorError::ResponseHandlingFailed)), ), _ => { let err = Some( - get_error_response(response.gw_error_code, &response.gw_error_reason, http_code) - .map_err(|err| *err), + get_error_response( + response.gw_error_code, + &response.gw_error_reason, + http_code, + &response.merchant_advice_code, + &response.gw_error_code.map(|e| e.to_string()), + &response.gw_error_reason, + ) + .map_err(|_err| { + error_stack::report!(errors::ConnectorError::ResponseHandlingFailed) + }), ); match response.transaction_status { Some(NuveiTransactionStatus::Error) | Some(NuveiTransactionStatus::Declined) => err, @@ -1566,86 +1730,174 @@ fn build_error_response<T>( pub trait NuveiPaymentsGenericResponse {} -impl NuveiPaymentsGenericResponse for Authorize {} impl NuveiPaymentsGenericResponse for CompleteAuthorize {} impl NuveiPaymentsGenericResponse for Void {} impl NuveiPaymentsGenericResponse for PSync {} impl NuveiPaymentsGenericResponse for Capture {} +impl NuveiPaymentsGenericResponse for PostCaptureVoid {} + +// Helper function to process Nuvei payment response + +fn process_nuvei_payment_response<F, T>( + item: &ResponseRouterData<F, NuveiPaymentsResponse, T, PaymentsResponseData>, + amount: Option<i64>, +) -> Result< + ( + enums::AttemptStatus, + Option<RedirectForm>, + Option<ConnectorResponseData>, + ), + error_stack::Report<errors::ConnectorError>, +> +where + F: std::fmt::Debug, + T: std::fmt::Debug, +{ + let redirection_data = match item.data.payment_method { + enums::PaymentMethod::Wallet | enums::PaymentMethod::BankRedirect => item + .response + .payment_option + .as_ref() + .and_then(|po| po.redirect_url.clone()) + .map(|base_url| RedirectForm::from((base_url, Method::Get))), + _ => item + .response + .payment_option + .as_ref() + .and_then(|o| o.card.clone()) + .and_then(|card| card.three_d) + .and_then(|three_ds| three_ds.acs_url.zip(three_ds.c_req)) + .map(|(base_url, creq)| RedirectForm::Form { + endpoint: base_url, + method: Method::Post, + form_fields: std::collections::HashMap::from([("creq".to_string(), creq.expose())]), + }), + }; + + let connector_response_data = + convert_to_additional_payment_method_connector_response(&item.response) + .map(ConnectorResponseData::with_additional_payment_method_data); + + let status = get_payment_status(&item.response, amount); + + Ok((status, redirection_data, connector_response_data)) +} + +// Helper function to create transaction response +fn create_transaction_response( + response: &NuveiPaymentsResponse, + redirection_data: Option<RedirectForm>, + http_code: u16, +) -> Result<PaymentsResponseData, error_stack::Report<errors::ConnectorError>> { + if let Some(err) = build_error_response(response, http_code) { + return err; + } + + Ok(PaymentsResponseData::TransactionResponse { + resource_id: response + .transaction_id + .clone() + .map_or(response.order_id.clone(), Some) // For paypal there will be no transaction_id, only order_id will be present + .map(ResponseId::ConnectorTransactionId) + .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new( + response + .payment_option + .as_ref() + .and_then(|po| po.user_payment_option_id.clone()) + .map(|id| MandateReference { + connector_mandate_id: Some(id), + payment_method_id: None, + mandate_metadata: None, + connector_mandate_request_reference_id: None, + }), + ), + // we don't need to save session token for capture, void flow so ignoring if it is not present + connector_metadata: if let Some(token) = response.session_token.clone() { + Some( + serde_json::to_value(NuveiMeta { + session_token: token, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed)?, + ) + } else { + None + }, + network_txn_id: None, + connector_response_reference_id: response.order_id.clone(), + incremental_authorization_allowed: None, + charges: None, + }) +} +// Specialized implementation for Authorize +impl + TryFrom< + ResponseRouterData< + Authorize, + NuveiPaymentsResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + Authorize, + NuveiPaymentsResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + // Get amount directly from the authorize data + let amount = Some(item.data.request.amount); + + let (status, redirection_data, connector_response_data) = + process_nuvei_payment_response(&item, amount)?; + + Ok(Self { + status, + response: Ok(create_transaction_response( + &item.response, + redirection_data, + item.http_code, + )?), + connector_response: connector_response_data, + ..item.data + }) + } +} + +// Generic implementation for other flow types impl<F, T> TryFrom<ResponseRouterData<F, NuveiPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> where - F: NuveiPaymentsGenericResponse, + F: NuveiPaymentsGenericResponse + std::fmt::Debug, + T: std::fmt::Debug, + F: std::any::Any, { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, NuveiPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { - let redirection_data = match item.data.payment_method { - enums::PaymentMethod::Wallet | enums::PaymentMethod::BankRedirect => item - .response - .payment_option - .as_ref() - .and_then(|po| po.redirect_url.clone()) - .map(|base_url| RedirectForm::from((base_url, Method::Get))), - _ => item - .response - .payment_option - .as_ref() - .and_then(|o| o.card.clone()) - .and_then(|card| card.three_d) - .and_then(|three_ds| three_ds.acs_url.zip(three_ds.c_req)) - .map(|(base_url, creq)| RedirectForm::Form { - endpoint: base_url, - method: Method::Post, - form_fields: std::collections::HashMap::from([( - "creq".to_string(), - creq.expose(), - )]), - }), - }; + let amount = item + .data + .minor_amount_capturable + .map(|amount| amount.get_amount_as_i64()); + + let (status, redirection_data, connector_response_data) = + process_nuvei_payment_response(&item, amount)?; - let response = item.response; Ok(Self { - status: get_payment_status(&response), - response: if let Some(err) = build_error_response(&response, item.http_code) { - err - } else { - Ok(PaymentsResponseData::TransactionResponse { - resource_id: response - .transaction_id - .map_or(response.order_id.clone(), Some) // For paypal there will be no transaction_id, only order_id will be present - .map(ResponseId::ConnectorTransactionId) - .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, - redirection_data: Box::new(redirection_data), - mandate_reference: Box::new( - response - .payment_option - .and_then(|po| po.user_payment_option_id) - .map(|id| MandateReference { - connector_mandate_id: Some(id), - payment_method_id: None, - mandate_metadata: None, - connector_mandate_request_reference_id: None, - }), - ), - // we don't need to save session token for capture, void flow so ignoring if it is not present - connector_metadata: if let Some(token) = response.session_token { - Some( - serde_json::to_value(NuveiMeta { - session_token: token, - }) - .change_context(errors::ConnectorError::ResponseHandlingFailed)?, - ) - } else { - None - }, - network_txn_id: None, - connector_response_reference_id: response.order_id, - incremental_authorization_allowed: None, - charges: None, - }) - }, + status, + response: Ok(create_transaction_response( + &item.response, + redirection_data, + item.http_code, + )?), + connector_response: connector_response_data, ..item.data }) } @@ -1668,11 +1920,12 @@ impl TryFrom<PaymentsPreprocessingResponseRouterData<NuveiPaymentsResponse>> .map(to_boolean) .unwrap_or_default(); Ok(Self { - status: get_payment_status(&response), + status: get_payment_status(&response, item.data.request.amount), response: Ok(PaymentsResponseData::ThreeDSEnrollmentResponse { enrolled_v2: is_enrolled_for_3ds, related_transaction_id: response.transaction_id, }), + ..item.data }) } @@ -1697,15 +1950,17 @@ impl TryFrom<RefundsResponseRouterData<Execute, NuveiPaymentsResponse>> fn try_from( item: RefundsResponseRouterData<Execute, NuveiPaymentsResponse>, ) -> Result<Self, Self::Error> { + let transaction_id = item + .response + .transaction_id + .clone() + .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?; + + let refund_response = + get_refund_response(item.response.clone(), item.http_code, transaction_id)?; + Ok(Self { - response: get_refund_response( - item.response.clone(), - item.http_code, - item.response - .transaction_id - .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, - ) - .map_err(|err| *err), + response: Ok(refund_response), ..item.data }) } @@ -1718,15 +1973,17 @@ impl TryFrom<RefundsResponseRouterData<RSync, NuveiPaymentsResponse>> fn try_from( item: RefundsResponseRouterData<RSync, NuveiPaymentsResponse>, ) -> Result<Self, Self::Error> { + let transaction_id = item + .response + .transaction_id + .clone() + .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?; + + let refund_response = + get_refund_response(item.response.clone(), item.http_code, transaction_id)?; + Ok(Self { - response: get_refund_response( - item.response.clone(), - item.http_code, - item.response - .transaction_id - .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, - ) - .map_err(|err| *err), + response: Ok(refund_response), ..item.data }) } @@ -1741,6 +1998,10 @@ where { let item = data; let connector_mandate_id = &item.request.get_connector_mandate_id(); + let customer_id = item + .request + .get_customer_id_required() + .ok_or(missing_field_err("customer_id")())?; let related_transaction_id = if item.is_three_ds() { item.request.get_related_transaction_id().clone() } else { @@ -1748,11 +2009,11 @@ where }; Ok(Self { related_transaction_id, - device_details: Option::<DeviceDetails>::foreign_try_from( + device_details: DeviceDetails::foreign_try_from( &item.request.get_browser_info().clone(), )?, is_rebilling: Some("1".to_string()), // In case of second installment, rebilling should be 1 - user_token_id: Some(item.request.get_email_required()?), + user_token_id: Some(customer_id), payment_option: PaymentOption { user_payment_option_id: connector_mandate_id.clone(), ..Default::default() @@ -1763,16 +2024,15 @@ where } } -impl ForeignTryFrom<&Option<BrowserInformation>> for Option<DeviceDetails> { +impl ForeignTryFrom<&Option<BrowserInformation>> for DeviceDetails { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(browser_info: &Option<BrowserInformation>) -> Result<Self, Self::Error> { - let device_details = match browser_info { - Some(browser_info) => Some(DeviceDetails { - ip_address: browser_info.get_ip_address()?, - }), - None => None, - }; - Ok(device_details) + let browser_info = browser_info + .as_ref() + .ok_or_else(missing_field_err("browser_info"))?; + Ok(Self { + ip_address: browser_info.get_ip_address()?, + }) } } @@ -1780,20 +2040,32 @@ fn get_refund_response( response: NuveiPaymentsResponse, http_code: u16, txn_id: String, -) -> Result<RefundsResponseData, Box<ErrorResponse>> { +) -> Result<RefundsResponseData, error_stack::Report<errors::ConnectorError>> { let refund_status = response .transaction_status .clone() .map(enums::RefundStatus::from) .unwrap_or(enums::RefundStatus::Failure); match response.status { - NuveiPaymentStatus::Error => { - get_error_response(response.err_code, &response.reason, http_code) - } + NuveiPaymentStatus::Error => get_error_response( + response.err_code, + &response.reason, + http_code, + &response.merchant_advice_code, + &response.gw_error_code.map(|e| e.to_string()), + &response.gw_error_reason, + ) + .map_err(|_err| error_stack::report!(errors::ConnectorError::ResponseHandlingFailed)), _ => match response.transaction_status { - Some(NuveiTransactionStatus::Error) => { - get_error_response(response.gw_error_code, &response.gw_error_reason, http_code) - } + Some(NuveiTransactionStatus::Error) => get_error_response( + response.err_code, + &response.reason, + http_code, + &response.merchant_advice_code, + &response.gw_error_code.map(|e| e.to_string()), + &response.gw_error_reason, + ) + .map_err(|_err| error_stack::report!(errors::ConnectorError::ResponseHandlingFailed)), _ => Ok(RefundsResponseData { connector_refund_id: txn_id, refund_status, @@ -1806,6 +2078,9 @@ fn get_error_response<T>( error_code: Option<i64>, error_msg: &Option<String>, http_code: u16, + network_advice_code: &Option<String>, + network_decline_code: &Option<String>, + network_error_message: &Option<String>, ) -> Result<T, Box<ErrorResponse>> { Err(Box::new(ErrorResponse { code: error_code @@ -1818,80 +2093,299 @@ fn get_error_response<T>( status_code: http_code, attempt_status: None, connector_transaction_id: None, - network_advice_code: None, - network_decline_code: None, - network_error_message: None, + network_advice_code: network_advice_code.clone(), + network_decline_code: network_decline_code.clone(), + network_error_message: network_error_message.clone(), })) } -#[derive(Debug, Default, Serialize, Deserialize)] -pub struct NuveiWebhookDetails { - pub ppp_status: Option<String>, +/// Represents any possible webhook notification from Nuvei. +#[derive(Debug, Serialize, Deserialize)] +#[serde(untagged)] +pub enum NuveiWebhook { + PaymentDmn(PaymentDmnNotification), + Chargeback(ChargebackNotification), +} + +/// Represents the status of a chargeback event. +#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] +pub enum ChargebackStatus { + RetrievalRequest, + Chargeback, + Representment, + SecondChargeback, + Arbitration, + #[serde(other)] + Unknown, +} + +/// Represents a Chargeback webhook notification from the Nuvei Control Panel. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ChargebackNotification { #[serde(rename = "ppp_TransactionID")] - pub ppp_transaction_id: String, - #[serde(rename = "TransactionId")] + pub ppp_transaction_id: Option<String>, + pub merchant_unique_id: Option<String>, + pub merchant_id: Option<String>, + pub merchant_site_id: Option<String>, + pub request_version: Option<String>, + pub message: Option<String>, + pub status: Option<ChargebackStatus>, + pub reason: Option<String>, + pub case_id: Option<String>, + pub processor_case_id: Option<String>, + pub arn: Option<String>, + pub retrieval_request_date: Option<String>, + pub chargeback_date: Option<String>, + pub chargeback_amount: Option<String>, + pub chargeback_currency: Option<String>, + pub original_amount: Option<String>, + pub original_currency: Option<String>, + #[serde(rename = "transactionID")] + pub transaction_id: Option<String>, + pub user_token_id: Option<String>, +} + +/// Represents the overall status of the DMN. +#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "UPPERCASE")] +pub enum DmnStatus { + Success, + Error, + Pending, +} + +/// Represents the status of the transaction itself. +#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "UPPERCASE")] +pub enum TransactionStatus { + Approved, + Declined, + Error, + Cancelled, + Pending, + #[serde(rename = "Settle")] + Settled, +} + +/// Represents the type of transaction. +#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "PascalCase")] +pub enum PaymentTransactionType { + Auth, + Sale, + Settle, + Credit, + Void, + Auth3D, + Sale3D, + Verif, +} + +/// Represents a Payment Direct Merchant Notification (DMN) webhook. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentDmnNotification { + #[serde(rename = "PPP_TransactionID")] + pub ppp_transaction_id: Option<String>, + #[serde(rename = "TransactionID")] pub transaction_id: Option<String>, - pub userid: Option<String>, + pub status: Option<DmnStatus>, + #[serde(rename = "ErrCode")] + pub err_code: Option<String>, + #[serde(rename = "ExErrCode")] + pub ex_err_code: Option<String>, + pub desc: Option<String>, pub merchant_unique_id: Option<String>, - #[serde(rename = "customData")] pub custom_data: Option<String>, - #[serde(rename = "productId")] - pub product_id: String, + pub product_id: Option<String>, pub first_name: Option<String>, pub last_name: Option<String>, pub email: Option<String>, - #[serde(rename = "totalAmount")] - pub total_amount: String, - pub currency: String, + pub total_amount: Option<String>, + pub currency: Option<String>, + pub fee: Option<String>, + #[serde(rename = "AuthCode")] + pub auth_code: Option<String>, + pub transaction_status: Option<TransactionStatus>, + pub transaction_type: Option<PaymentTransactionType>, + #[serde(rename = "user_token_id")] + pub user_token_id: Option<String>, + #[serde(rename = "payment_method")] + pub payment_method: Option<String>, #[serde(rename = "responseTimeStamp")] - pub response_time_stamp: String, - #[serde(rename = "Status")] - pub status: NuveiWebhookStatus, - #[serde(rename = "transactionType")] - pub transaction_type: Option<NuveiTransactionType>, -} - + pub response_time_stamp: Option<String>, + #[serde(rename = "invoice_id")] + pub invoice_id: Option<String>, + #[serde(rename = "merchant_id")] + pub merchant_id: Option<String>, + #[serde(rename = "merchant_site_id")] + pub merchant_site_id: Option<String>, + #[serde(rename = "responsechecksum")] + pub response_checksum: Option<String>, + #[serde(rename = "advanceResponseChecksum")] + pub advance_response_checksum: Option<String>, +} + +// For backward compatibility with existing code #[derive(Debug, Default, Serialize, Deserialize)] pub struct NuveiWebhookTransactionId { #[serde(rename = "ppp_TransactionID")] pub ppp_transaction_id: String, } -#[derive(Debug, Default, Serialize, Deserialize)] -pub struct NuveiWebhookDataStatus { - #[serde(rename = "Status")] - pub status: NuveiWebhookStatus, +// Helper struct to extract transaction ID from either webhook type +impl From<&NuveiWebhook> for NuveiWebhookTransactionId { + fn from(webhook: &NuveiWebhook) -> Self { + match webhook { + NuveiWebhook::Chargeback(notification) => Self { + ppp_transaction_id: notification.ppp_transaction_id.clone().unwrap_or_default(), + }, + NuveiWebhook::PaymentDmn(notification) => Self { + ppp_transaction_id: notification.ppp_transaction_id.clone().unwrap_or_default(), + }, + } + } } -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "UPPERCASE")] -pub enum NuveiWebhookStatus { - Approved, - Declined, - #[default] - Pending, - Update, - #[serde(other)] - Unknown, +// Convert webhook to payments response for further processing +impl From<NuveiWebhook> for NuveiPaymentsResponse { + fn from(webhook: NuveiWebhook) -> Self { + match webhook { + NuveiWebhook::Chargeback(notification) => Self { + transaction_status: Some(NuveiTransactionStatus::Processing), + transaction_id: notification.transaction_id, + transaction_type: Some(NuveiTransactionType::Credit), // Using Credit as placeholder for chargeback + ..Default::default() + }, + NuveiWebhook::PaymentDmn(notification) => { + let transaction_type = notification.transaction_type.map(|tt| match tt { + PaymentTransactionType::Auth => NuveiTransactionType::Auth, + PaymentTransactionType::Sale => NuveiTransactionType::Sale, + PaymentTransactionType::Settle => NuveiTransactionType::Settle, + PaymentTransactionType::Credit => NuveiTransactionType::Credit, + PaymentTransactionType::Void => NuveiTransactionType::Void, + PaymentTransactionType::Auth3D => NuveiTransactionType::Auth3D, + PaymentTransactionType::Sale3D => NuveiTransactionType::Auth3D, // Map to closest equivalent + PaymentTransactionType::Verif => NuveiTransactionType::Auth, // Map to closest equivalent + }); + + Self { + transaction_status: notification.transaction_status.map(|ts| match ts { + TransactionStatus::Approved => NuveiTransactionStatus::Approved, + TransactionStatus::Declined => NuveiTransactionStatus::Declined, + TransactionStatus::Error => NuveiTransactionStatus::Error, + TransactionStatus::Settled => NuveiTransactionStatus::Approved, + _ => NuveiTransactionStatus::Processing, + }), + transaction_id: notification.transaction_id, + transaction_type, + ..Default::default() + } + } + } + } } -impl From<NuveiWebhookStatus> for NuveiTransactionStatus { - fn from(status: NuveiWebhookStatus) -> Self { - match status { - NuveiWebhookStatus::Approved => Self::Approved, - NuveiWebhookStatus::Declined => Self::Declined, - _ => Self::Processing, - } +fn get_cvv2_response_description(code: &str) -> Option<&str> { + match code { + "M" => Some("CVV2 Match"), + "N" => Some("CVV2 No Match"), + "P" => Some("Not Processed. For EU card-on-file (COF) and ecommerce (ECOM) network token transactions, Visa removes any CVV and sends P. If you have fraud or security concerns, Visa recommends using 3DS."), + "U" => Some("Issuer is not certified and/or has not provided Visa the encryption keys"), + "S" => Some("CVV2 processor is unavailable."), + _=> None, } } -impl From<NuveiWebhookDetails> for NuveiPaymentsResponse { - fn from(item: NuveiWebhookDetails) -> Self { - Self { - transaction_status: Some(NuveiTransactionStatus::from(item.status)), - transaction_id: item.transaction_id, - transaction_type: item.transaction_type, - ..Default::default() - } +fn get_avs_response_description(code: &str) -> Option<&str> { + match code { + "A" => Some("The street address matches, the ZIP code does not."), + "W" => Some("Postal code matches, the street address does not."), + "Y" => Some("Postal code and the street address match."), + "X" => Some("An exact match of both the 9-digit ZIP code and the street address."), + "Z" => Some("Postal code matches, the street code does not."), + "U" => Some("Issuer is unavailable."), + "S" => Some("AVS not supported by issuer."), + "R" => Some("Retry."), + "B" => Some("Not authorized (declined)."), + "N" => Some("Both the street address and postal code do not match."), + _ => None, + } +} + +fn get_merchant_advice_code_description(code: &str) -> Option<&str> { + match code { + "01" => Some("New Account Information Available"), + "02" => Some("Cannot approve at this time, try again later"), + "03" => Some("Do Not Try Again"), + "04" => Some("Token requirements not fulfilled for this token type"), + "21" => Some("Payment Cancellation, do not try again"), + "24" => Some("Retry after 1 hour"), + "25" => Some("Retry after 24 hours"), + "26" => Some("Retry after 2 days"), + "27" => Some("Retry after 4 days"), + "28" => Some("Retry after 6 days"), + "29" => Some("Retry after 8 days"), + "30" => Some("Retry after 10 days"), + "40" => Some("Card is a consumer non-reloadable prepaid card"), + "41" => Some("Card is a consumer single-use virtual card number"), + "42" => Some("Transaction type exceeds issuer's risk threshold. Please retry with another payment account."), + "43" => Some("Card is a consumer multi-use virtual card number"), + _ => None, + } +} + +/// Concatenates a vector of strings without any separator +/// This is useful for creating verification messages for webhooks +pub fn concat_strings(strings: &[String]) -> String { + strings.join("") +} + +fn convert_to_additional_payment_method_connector_response( + transaction_response: &NuveiPaymentsResponse, +) -> Option<AdditionalPaymentMethodConnectorResponse> { + let card = transaction_response + .payment_option + .as_ref()? + .card + .as_ref()?; + let avs_code = card.avs_code.as_ref(); + let cvv2_code = card.cvv2_reply.as_ref(); + let merchant_advice_code = transaction_response.merchant_advice_code.as_ref(); + + let avs_description = avs_code.and_then(|code| get_avs_response_description(code)); + let cvv_description = cvv2_code.and_then(|code| get_cvv2_response_description(code)); + let merchant_advice_description = + merchant_advice_code.and_then(|code| get_merchant_advice_code_description(code)); + + let payment_checks = serde_json::json!({ + "avs_result_code": avs_code, + "avs_description": avs_description, + "cvv_2_reply_code": cvv2_code, + "cvv_2_description": cvv_description, + "merchant_advice_code": merchant_advice_code, + "merchant_advice_code_description": merchant_advice_description + }); + + let card_network = card.card_brand.clone(); + let three_ds_data = card + .three_d + .clone() + .map(|three_d| { + serde_json::to_value(three_d) + .map_err(|_| errors::ConnectorError::ResponseHandlingFailed) + .attach_printable("threeDs encoding failed Nuvei") + }) + .transpose(); + + match three_ds_data { + Ok(authentication_data) => Some(AdditionalPaymentMethodConnectorResponse::Card { + authentication_data, + payment_checks: Some(payment_checks), + card_network, + domestic_network: None, + }), + Err(_) => None, } } diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 22c87d08323..2ecdf1f4de1 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -1058,7 +1058,6 @@ default_imp_for_cancel_post_capture!( connectors::Nexixpay, connectors::Opayo, connectors::Opennode, - connectors::Nuvei, connectors::Nmi, connectors::Paybox, connectors::Payeezy,
2025-07-28T08:38:26Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Added few Nuvie features - AVC,CVV : pass the response of AVC , CVV checks from Nuvie to Hypserswitch payment resonse (check in any below responses) ```json "payment_checks": { "avs_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, ``` - Post Capture Void : After capture of successful amount we should be able to make void (typically before 24 hours) - 0$ transaction : Allow 0$ transaction // We are going to change this to setup mandate flow in upcomming pr rightnow its routing through AUTHORIZE flow itself . We can skip the test for this as of now. <!-- Describe your changes in detail --> ## zero dollar transaction <details> <summary> Get connector mandate id with 0 transaction initization `/payments` </summary> ## Request ```json { "amount": 0, "currency": "EUR", "confirm": true, "customer_acceptance": { "acceptance_type": "online", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, // "order_tax_amount": 100, "setup_future_usage": "off_session", // "payment_type":"setup_mandate", "customer_id": "nithxxinn", "return_url": "https://www.google.com", "capture_method": "automatic", "payment_method": "card", "payment_method_type": "credit", "authentication_type": "no_three_ds", "description": "hellow world", "billing": { "address": { "zip": "560095", "country": "US", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" } }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "hello@gmail.com", "payment_method_data": { "card": { "card_number": "4000000000009995", "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "card_cvc": "100" } } } ``` ## response ```json { "payment_id": "pay_bnO3yXpju09Ws8oBUR9w", "merchant_id": "merchant_1754498214", "status": "requires_capture", "amount": 0, "net_amount": 0, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "nuvei", "client_secret": "pay_bnO3yXpju09Ws8oBUR9w_secret_Y6WO2DC3Uidzbeb7WyWa", "created": "2025-08-06T17:23:41.192Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "hello@gmail.com", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "9995", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": { "avs_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "challengePreferenceReason": "12" } }, "billing": null }, "payment_token": "token_rO5qEPT5099xgR6E600V", "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "hello@gmail.com", "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nithxxinn", "created_at": 1754501021, "expires": 1754504621, "secret": "epk_6fb49f9cdabd42dd9d33789fb584df66" }, "manual_retry_allowed": false, "connector_transaction_id": "7110000000016293888", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "7657741111", "payment_link": null, "profile_id": "pro_Lm9uDS83De6QX5EHQNMy", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_BgWz2Uy3MgHlzzgy7W7H", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-06T17:38:41.192Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": "pm_Ku0TdAhmkKDiX9TqhomL", "network_transaction_id": null, "payment_method_status": "active", "updated": "2025-08-06T17:23:46.105Z", "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": "2073997111", // connector mandate id "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` </details> <details> <summary> Mandates triggered using 0 transcation payment method id </summary> ## Request ```json curl --location 'localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_gvwtxVj8XLUh0di5xt8yUkxS187Wlr733tSxZh7Aof45gYnrteTvmP2aJvFD8vdj' \ --data '{ "amount": 333, "currency": "EUR", "customer_id": "nithxxinn", "confirm": true, "off_session": true, "recurring_details": { "type": "payment_method_id", "data": "pm_Ku0TdAhmkKDiX9TqhomL" }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" } }' ``` ##response ```json { "payment_id": "pay_eW2XRbgGai3X3RpAVVGD", "merchant_id": "merchant_1754498214", "status": "succeeded", "amount": 333, "net_amount": 333, "shipping_cost": null, "amount_capturable": 0, "amount_received": 333, "connector": "nuvei", "client_secret": "pay_eW2XRbgGai3X3RpAVVGD_secret_H6pCfoxWHonNwkXzyHD2", "created": "2025-08-06T17:34:58.537Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "hello@gmail.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "9995", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "hello@gmail.com", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nithxxinn", "created_at": 1754501698, "expires": 1754505298, "secret": "epk_7e35c394cdc94bc59e5184173d3fa385" }, "manual_retry_allowed": false, "connector_transaction_id": "7110000000016294501", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "7658013111", "payment_link": null, "profile_id": "pro_Lm9uDS83De6QX5EHQNMy", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_BgWz2Uy3MgHlzzgy7W7H", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-06T17:49:58.537Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": "pm_Ku0TdAhmkKDiX9TqhomL", "network_transaction_id": null, "payment_method_status": "active", "updated": "2025-08-06T17:35:01.823Z", "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": "2073997111", "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` </details> ## Post capture cancel - original txn: 7110000000016291163 - void: 7110000000016291191 <details> <summary> /payments/:id/cancel_post_capture </summary> ```json curl --location 'localhost:8080/payments/pay_MyZex1y0W8JtlkJ4E8sX/cancel_post_capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_gvwtxVj8XLUh0di5xt8yUkxS187Wlr733tSxZh7Aof45gYnrteTvmP2aJvFD8vdj' \ --data '{ "cancellation_reason": "requested_by_customer" }' ``` ### Response ```json { "payment_id": "pay_MyZex1y0W8JtlkJ4E8sX", "merchant_id": "merchant_1754498214", "status": "partially_captured", "amount": 21, "net_amount": 21, "shipping_cost": null, "amount_capturable": 0, "amount_received": 21, "connector": "nuvei", "client_secret": "pay_MyZex1y0W8JtlkJ4E8sX_secret_Ih4q9iGVVaUNIM69pSHv", "created": "2025-08-06T16:45:05.230Z", "currency": "EUR", "customer_id": null, "customer": { "id": null, "name": null, "email": "hello@gmail.com", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "9995", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": { "avs_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "challengePreferenceReason": "12" } }, "billing": null }, "payment_token": "token_IpZOPBQT3Cr7UWNqtKFT", "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7110000000016291191", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "7656640111", "payment_link": null, "profile_id": "pro_Lm9uDS83De6QX5EHQNMy", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_BgWz2Uy3MgHlzzgy7W7H", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-06T17:00:05.230Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": "pm_IINXjPD3GBVwSFS5jrNS", "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-06T16:45:23.093Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` For AVS , cvv and MAC you can check in the above payment resopnses ``` json "payment_checks": { "avs_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, ``` </details> <img width="647" height="703" alt="Screenshot 2025-08-08 at 7 37 41β€―PM" src="https://github.com/user-attachments/assets/cb4aa3b0-4908-46c2-b4f7-f231d3d9f044" /> <img width="775" height="892" alt="Screenshot 2025-08-08 at 7 38 07β€―PM" src="https://github.com/user-attachments/assets/829f417f-859e-4712-936f-fa9d3165dc10" /> <img width="643" height="699" alt="Screenshot 2025-08-08 at 7 38 22β€―PM" src="https://github.com/user-attachments/assets/8bc337eb-b79b-4f62-8170-74bd5b3a3d6a" /> - [ ] 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.116.0
4a8eea9aa559a4fff6013a13c0defec4796e922c
4a8eea9aa559a4fff6013a13c0defec4796e922c
juspay/hyperswitch
juspay__hyperswitch-8895
Bug: [FEATURE] Googlepay , applepay and partial authorization integration for nuvei ### Feature Description Add nuvie features ### Possible Implementation Add and fix the following features in nuvie Google pay decrypt flow Apple pay decrypt flow Google pay direct Partial Authorization Send shipping address for nuvei (previously not sent) ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei.rs b/crates/hyperswitch_connectors/src/connectors/nuvei.rs index 3701a814103..7943479730d 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei.rs @@ -1,5 +1,5 @@ pub mod transformers; -use std::{fmt::Debug, sync::LazyLock}; +use std::sync::LazyLock; use api_models::{payments::PaymentIdType, webhooks::IncomingWebhookEvent}; use common_enums::{enums, CallConnectorAction, PaymentAction}; @@ -9,6 +9,7 @@ use common_utils::{ ext_traits::{ByteSliceExt, BytesExt, ValueExt}, id_type, request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ @@ -57,8 +58,17 @@ use crate::{ utils::{self, is_mandate_supported, PaymentMethodDataType, RouterData as _}, }; -#[derive(Debug, Clone)] -pub struct Nuvei; +#[derive(Clone)] +pub struct Nuvei { + pub amount_convertor: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), +} +impl Nuvei { + pub fn new() -> &'static Self { + &Self { + amount_convertor: &StringMajorUnitForConnector, + } + } +} impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nuvei where @@ -592,6 +602,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, req.get_session_token()?))?; + Ok(RequestContent::Json(Box::new(connector_req))) } @@ -629,7 +640,6 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData .switch()?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - RouterData::try_from(ResponseRouterData { response, data: data.clone(), diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index c20b97d78a2..2280bbb707c 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -1,4 +1,5 @@ use common_enums::{enums, CaptureMethod, PaymentChannel}; +use common_types::payments::{ApplePayPaymentData, GpayTokenizationData}; use common_utils::{ crypto::{self, GenerateDigest}, date_time, @@ -7,9 +8,11 @@ use common_utils::{ id_type::CustomerId, pii::{Email, IpAddress}, request::Method, + types::{MinorUnit, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ + address::Address, mandates::{MandateData, MandateDataType}, payment_method_data::{ self, ApplePayWalletData, BankRedirectData, GooglePayWalletData, PayLaterData, @@ -34,7 +37,7 @@ use hyperswitch_domain_models::{ }; use hyperswitch_interfaces::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, - errors, + errors::{self}, }; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; @@ -45,12 +48,14 @@ use crate::{ PaymentsPreprocessingResponseRouterData, RefundsResponseRouterData, ResponseRouterData, }, utils::{ - self, missing_field_err, AddressDetailsData, BrowserInformationData, ForeignTryFrom, - PaymentsAuthorizeRequestData, PaymentsCancelRequestData, PaymentsPreProcessingRequestData, - RouterData as _, + self, convert_amount, missing_field_err, AddressData, AddressDetailsData, + BrowserInformationData, ForeignTryFrom, PaymentsAuthorizeRequestData, + PaymentsCancelRequestData, PaymentsPreProcessingRequestData, RouterData as _, }, }; +pub static NUVEI_AMOUNT_CONVERTOR: &StringMajorUnitForConnector = &StringMajorUnitForConnector; + fn to_boolean(string: String) -> bool { let str = string.as_str(); match str { @@ -78,7 +83,9 @@ trait NuveiAuthorizePreprocessingCommon { &self, ) -> Result<String, error_stack::Report<errors::ConnectorError>>; fn get_capture_method(&self) -> Option<CaptureMethod>; - fn get_amount_required(&self) -> Result<i64, error_stack::Report<errors::ConnectorError>>; + fn get_minor_amount_required( + &self, + ) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>>; fn get_customer_id_required(&self) -> Option<CustomerId>; fn get_email_required(&self) -> Result<Email, error_stack::Report<errors::ConnectorError>>; fn get_currency_required( @@ -87,9 +94,10 @@ trait NuveiAuthorizePreprocessingCommon { fn get_payment_method_data_required( &self, ) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>>; + fn get_is_partial_approval(&self) -> Option<PartialApprovalFlag>; fn get_order_tax_amount( &self, - ) -> Result<Option<i64>, error_stack::Report<errors::ConnectorError>>; + ) -> Result<Option<MinorUnit>, error_stack::Report<errors::ConnectorError>>; } impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData { @@ -133,8 +141,10 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData { self.capture_method } - fn get_amount_required(&self) -> Result<i64, error_stack::Report<errors::ConnectorError>> { - Ok(self.amount) + fn get_minor_amount_required( + &self, + ) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>> { + Ok(self.minor_amount) } fn get_currency_required( @@ -149,13 +159,18 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsAuthorizeData { } fn get_order_tax_amount( &self, - ) -> Result<Option<i64>, error_stack::Report<errors::ConnectorError>> { - Ok(self.order_tax_amount.map(|tax| tax.get_amount_as_i64())) + ) -> Result<Option<MinorUnit>, error_stack::Report<errors::ConnectorError>> { + Ok(self.order_tax_amount) } fn get_email_required(&self) -> Result<Email, error_stack::Report<errors::ConnectorError>> { self.get_email() } + + fn get_is_partial_approval(&self) -> Option<PartialApprovalFlag> { + self.enable_partial_authorization + .map(PartialApprovalFlag::from) + } } impl NuveiAuthorizePreprocessingCommon for PaymentsPreProcessingData { @@ -199,8 +214,10 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsPreProcessingData { self.capture_method } - fn get_amount_required(&self) -> Result<i64, error_stack::Report<errors::ConnectorError>> { - self.get_amount() + fn get_minor_amount_required( + &self, + ) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>> { + self.get_minor_amount() } fn get_currency_required( @@ -220,9 +237,13 @@ impl NuveiAuthorizePreprocessingCommon for PaymentsPreProcessingData { } fn get_order_tax_amount( &self, - ) -> Result<Option<i64>, error_stack::Report<errors::ConnectorError>> { + ) -> Result<Option<MinorUnit>, error_stack::Report<errors::ConnectorError>> { Ok(None) } + + fn get_is_partial_approval(&self) -> Option<PartialApprovalFlag> { + None + } } #[derive(Debug, Serialize, Default, Deserialize)] @@ -262,7 +283,7 @@ pub struct NuveiSessionResponse { #[derive(Debug, Serialize, Default)] #[serde(rename_all = "camelCase")] pub struct NuvieAmountDetails { - total_tax: Option<String>, + total_tax: Option<StringMajorUnit>, } #[serde_with::skip_serializing_none] #[derive(Debug, Serialize, Default)] @@ -273,7 +294,7 @@ pub struct NuveiPaymentsRequest { pub merchant_id: Secret<String>, pub merchant_site_id: Secret<String>, pub client_request_id: Secret<String>, - pub amount: String, + pub amount: StringMajorUnit, pub currency: enums::Currency, /// This ID uniquely identifies your consumer/user in your system. pub user_token_id: Option<CustomerId>, @@ -286,9 +307,30 @@ pub struct NuveiPaymentsRequest { pub device_details: DeviceDetails, pub checksum: Secret<String>, pub billing_address: Option<BillingAddress>, + pub shipping_address: Option<ShippingAddress>, pub related_transaction_id: Option<String>, pub url_details: Option<UrlDetails>, pub amount_details: Option<NuvieAmountDetails>, + pub is_partial_approval: Option<PartialApprovalFlag>, +} + +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] +#[serde(rename_all = "UPPERCASE")] +pub enum PartialApprovalFlag { + #[serde(rename = "1")] + Enabled, + #[serde(rename = "0")] + Disabled, +} + +impl From<bool> for PartialApprovalFlag { + fn from(value: bool) -> Self { + if value { + Self::Enabled + } else { + Self::Disabled + } + } } #[derive(Debug, Serialize, Default)] @@ -305,7 +347,7 @@ pub struct NuveiInitPaymentRequest { pub merchant_id: Secret<String>, pub merchant_site_id: Secret<String>, pub client_request_id: String, - pub amount: String, + pub amount: StringMajorUnit, pub currency: String, pub payment_option: PaymentOption, pub checksum: Secret<String>, @@ -319,7 +361,7 @@ pub struct NuveiPaymentFlowRequest { pub merchant_id: Secret<String>, pub merchant_site_id: Secret<String>, pub client_request_id: String, - pub amount: String, + pub amount: StringMajorUnit, pub currency: enums::Currency, pub related_transaction_id: Option<String>, pub checksum: Secret<String>, @@ -347,6 +389,7 @@ pub struct PaymentOption { pub user_payment_option_id: Option<String>, pub alternative_payment_method: Option<AlternativePaymentMethod>, pub billing_address: Option<BillingAddress>, + pub shipping_address: Option<BillingAddress>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -413,8 +456,104 @@ pub struct BillingAddress { pub first_name: Option<Secret<String>>, pub last_name: Option<Secret<String>>, pub country: api_models::enums::CountryAlpha2, + pub phone: Option<Secret<String>>, + pub city: Option<Secret<String>>, + pub address: Option<Secret<String>>, + pub street_number: Option<Secret<String>>, + pub zip: Option<Secret<String>>, + pub state: Option<Secret<String>>, + pub cell: Option<Secret<String>>, + pub address_match: Option<Secret<String>>, + pub address_line2: Option<Secret<String>>, + pub address_line3: Option<Secret<String>>, + pub home_phone: Option<Secret<String>>, + pub work_phone: Option<Secret<String>>, +} + +#[serde_with::skip_serializing_none] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ShippingAddress { + pub salutation: Option<Secret<String>>, + pub first_name: Option<Secret<String>>, + pub last_name: Option<Secret<String>>, + pub address: Option<Secret<String>>, + pub cell: Option<Secret<String>>, + pub phone: Option<Secret<String>>, + pub zip: Option<Secret<String>>, + pub city: Option<Secret<String>>, + pub country: api_models::enums::CountryAlpha2, + pub state: Option<Secret<String>>, + pub email: Email, + pub county: Option<Secret<String>>, + pub address_line2: Option<Secret<String>>, + pub address_line3: Option<Secret<String>>, + pub street_number: Option<Secret<String>>, + pub company_name: Option<Secret<String>>, + pub care_of: Option<Secret<String>>, } +impl From<&Address> for BillingAddress { + fn from(address: &Address) -> Self { + let address_details = address.address.as_ref(); + Self { + email: address.email.clone().unwrap_or_default(), + first_name: address.get_optional_first_name(), + last_name: address_details.and_then(|address| address.get_optional_last_name()), + country: address_details + .and_then(|address| address.get_optional_country()) + .unwrap_or_default(), + phone: address + .phone + .as_ref() + .and_then(|phone| phone.number.clone()), + city: address_details + .and_then(|address| address.get_optional_city().map(|city| city.into())), + address: address_details.and_then(|address| address.get_optional_line1()), + street_number: None, + zip: address_details.and_then(|details| details.get_optional_zip()), + state: None, + cell: None, + address_match: None, + address_line2: address_details.and_then(|address| address.get_optional_line2()), + address_line3: address_details.and_then(|address| address.get_optional_line3()), + home_phone: None, + work_phone: None, + } + } +} + +impl From<&Address> for ShippingAddress { + fn from(address: &Address) -> Self { + let address_details = address.address.as_ref(); + + Self { + email: address.email.clone().unwrap_or_default(), + first_name: address_details.and_then(|details| details.get_optional_first_name()), + last_name: address_details.and_then(|details| details.get_optional_last_name()), + country: address_details + .and_then(|details| details.get_optional_country()) + .unwrap_or_default(), + phone: address + .phone + .as_ref() + .and_then(|phone| phone.number.clone()), + city: address_details + .and_then(|details| details.get_optional_city().map(|city| city.into())), + address: address_details.and_then(|details| details.get_optional_line1()), + street_number: None, + zip: address_details.and_then(|details| details.get_optional_zip()), + state: None, + cell: None, + address_line2: address_details.and_then(|details| details.get_optional_line2()), + address_line3: address_details.and_then(|details| details.get_optional_line3()), + county: None, + company_name: None, + care_of: None, + salutation: None, + } + } +} #[serde_with::skip_serializing_none] #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -435,7 +574,7 @@ pub struct Card { pub cvv2_reply: Option<String>, pub avs_code: Option<String>, pub card_type: Option<String>, - pub card_brand: Option<String>, + pub brand: Option<String>, pub issuer_bank_name: Option<String>, pub issuer_country: Option<String>, pub is_prepaid: Option<String>, @@ -446,7 +585,9 @@ pub struct Card { #[serde(rename_all = "camelCase")] pub struct ExternalToken { pub external_token_provider: ExternalTokenProvider, - pub mobile_token: Secret<String>, + pub mobile_token: Option<Secret<String>>, + pub cryptogram: Option<Secret<String>>, + pub eci_provider: Option<String>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] @@ -644,53 +785,226 @@ pub struct NuveiCardDetails { card_holder_name: Option<Secret<String>>, } +// Define new structs with camelCase serialization +#[derive(Serialize, Debug)] +#[serde(rename_all = "camelCase")] +struct GooglePayCamelCase { + pm_type: Secret<String>, + description: Secret<String>, + info: GooglePayInfoCamelCase, + tokenization_data: GooglePayTokenizationDataCamelCase, +} + +#[derive(Serialize, Debug)] +#[serde(rename_all = "camelCase")] +struct GooglePayInfoCamelCase { + card_network: Secret<String>, + card_details: Secret<String>, + assurance_details: Option<GooglePayAssuranceDetailsCamelCase>, +} + +#[derive(Serialize, Debug)] +#[serde(rename_all = "camelCase")] +struct GooglePayAssuranceDetailsCamelCase { + card_holder_authenticated: bool, + account_verified: bool, +} + +#[derive(Serialize, Debug)] +#[serde(rename_all = "camelCase")] +struct GooglePayTokenizationDataCamelCase { + #[serde(rename = "type")] + token_type: Secret<String>, + token: Secret<String>, +} + +// Define ApplePay structs with camelCase serialization +#[derive(Serialize, Debug)] +#[serde(rename_all = "camelCase")] +struct ApplePayCamelCase { + payment_data: Secret<String>, + payment_method: ApplePayPaymentMethodCamelCase, + transaction_identifier: Secret<String>, +} + +#[derive(Serialize, Debug)] +#[serde(rename_all = "camelCase")] +struct ApplePayPaymentMethodCamelCase { + display_name: Secret<String>, + network: Secret<String>, + #[serde(rename = "type")] + pm_type: Secret<String>, +} + impl TryFrom<GooglePayWalletData> for NuveiPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(gpay_data: GooglePayWalletData) -> Result<Self, Self::Error> { - Ok(Self { - payment_option: PaymentOption { - card: Some(Card { - external_token: Some(ExternalToken { - external_token_provider: ExternalTokenProvider::GooglePay, - mobile_token: Secret::new( - utils::GooglePayWalletData::try_from(gpay_data) - .change_context(errors::ConnectorError::InvalidDataFormat { - field_name: "google_pay_data", - })? - .encode_to_string_of_json() - .change_context(errors::ConnectorError::RequestEncodingFailed)?, + match gpay_data.tokenization_data { + GpayTokenizationData::Decrypted(ref gpay_predecrypt_data) => Ok(Self { + payment_option: PaymentOption { + card: Some(Card { + brand: Some(gpay_data.info.card_network.clone()), + card_number: Some( + gpay_predecrypt_data + .application_primary_account_number + .clone(), ), + last4_digits: Some(Secret::new( + gpay_predecrypt_data + .application_primary_account_number + .clone() + .get_last4(), + )), + expiration_month: Some(gpay_predecrypt_data.card_exp_month.clone()), + expiration_year: Some(gpay_predecrypt_data.card_exp_year.clone()), + external_token: Some(ExternalToken { + external_token_provider: ExternalTokenProvider::GooglePay, + mobile_token: None, + cryptogram: gpay_predecrypt_data.cryptogram.clone(), + eci_provider: gpay_predecrypt_data.eci_indicator.clone(), + }), + ..Default::default() }), ..Default::default() - }), + }, ..Default::default() - }, - ..Default::default() - }) + }), + GpayTokenizationData::Encrypted(encrypted_data) => Ok(Self { + payment_option: PaymentOption { + card: Some(Card { + external_token: Some(ExternalToken { + external_token_provider: ExternalTokenProvider::GooglePay, + + mobile_token: { + let (token_type, token) = ( + encrypted_data.token_type.clone(), + encrypted_data.token.clone(), + ); + + let google_pay: GooglePayCamelCase = GooglePayCamelCase { + pm_type: Secret::new(gpay_data.pm_type.clone()), + description: Secret::new(gpay_data.description.clone()), + info: GooglePayInfoCamelCase { + card_network: Secret::new( + gpay_data.info.card_network.clone(), + ), + card_details: Secret::new( + gpay_data.info.card_details.clone(), + ), + assurance_details: gpay_data + .info + .assurance_details + .as_ref() + .map(|details| GooglePayAssuranceDetailsCamelCase { + card_holder_authenticated: details + .card_holder_authenticated, + account_verified: details.account_verified, + }), + }, + tokenization_data: GooglePayTokenizationDataCamelCase { + token_type: token_type.into(), + token: token.into(), + }, + }; + Some(Secret::new( + google_pay.encode_to_string_of_json().change_context( + errors::ConnectorError::RequestEncodingFailed, + )?, + )) + }, + cryptogram: None, + eci_provider: None, + }), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }), + } } } impl TryFrom<ApplePayWalletData> for NuveiPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(apple_pay_data: ApplePayWalletData) -> Result<Self, Self::Error> { - let apple_pay_encrypted_data = apple_pay_data - .payment_data - .get_encrypted_apple_pay_payment_data_mandatory() - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "Apple pay encrypted data", - })?; - Ok(Self { - payment_option: PaymentOption { - card: Some(Card { - external_token: Some(ExternalToken { - external_token_provider: ExternalTokenProvider::ApplePay, - mobile_token: Secret::new(apple_pay_encrypted_data.clone()), + match apple_pay_data.payment_data { + ApplePayPaymentData::Decrypted(apple_pay_predecrypt_data) => Ok(Self { + payment_option: PaymentOption { + card: Some(Card { + brand:Some(apple_pay_data.payment_method.network.clone()), + card_number: Some( + apple_pay_predecrypt_data + .application_primary_account_number + .clone(), + ), + last4_digits: Some(Secret::new( + apple_pay_predecrypt_data + .application_primary_account_number + .get_last4(), + )), + expiration_month: Some( + apple_pay_predecrypt_data + .application_expiration_month + .clone(), + ), + expiration_year: Some( + apple_pay_predecrypt_data + .application_expiration_year + .clone(), + ), + external_token: Some(ExternalToken { + external_token_provider: ExternalTokenProvider::ApplePay, + mobile_token: None, + cryptogram: Some( + apple_pay_predecrypt_data + .payment_data + .online_payment_cryptogram, + ), + eci_provider: Some( + apple_pay_predecrypt_data + .payment_data + .eci_indicator + .ok_or_else(missing_field_err("payment_method_data.wallet.apple_pay.payment_data.eci_indicator"))?, + ), + }), + ..Default::default() }), ..Default::default() - }), + }, ..Default::default() - }, - ..Default::default() - }) + }), + ApplePayPaymentData::Encrypted(encrypted_data) => Ok(Self { + payment_option: PaymentOption { + card: Some(Card { + external_token: Some(ExternalToken { + external_token_provider: ExternalTokenProvider::ApplePay, + mobile_token: { + let apple_pay: ApplePayCamelCase = ApplePayCamelCase { + payment_data:encrypted_data.into(), + payment_method: ApplePayPaymentMethodCamelCase { + display_name: Secret::new(apple_pay_data.payment_method.display_name.clone()), + network: Secret::new(apple_pay_data.payment_method.network.clone()), + pm_type: Secret::new(apple_pay_data.payment_method.pm_type.clone()), + }, + transaction_identifier: Secret::new(apple_pay_data.transaction_identifier.clone()), + }; + + Some(Secret::new( + apple_pay.encode_to_string_of_json().change_context( + errors::ConnectorError::RequestEncodingFailed, + )?, + )) + }, + cryptogram: None, + eci_provider: None, + }), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }), + } } } @@ -869,58 +1183,32 @@ where ), ) -> Result<Self, Self::Error> { let (payment_method, redirect, item) = data; - let (billing_address, bank_id) = match (&payment_method, redirect) { - (AlternativePaymentMethodType::Expresscheckout, _) => ( - Some(BillingAddress { - email: item.request.get_email_required()?, - country: item.get_billing_country()?, - ..Default::default() - }), - None, - ), - (AlternativePaymentMethodType::Giropay, _) => ( - Some(BillingAddress { - email: item.request.get_email_required()?, - country: item.get_billing_country()?, - ..Default::default() - }), - None, - ), + let bank_id = match (&payment_method, redirect) { + (AlternativePaymentMethodType::Expresscheckout, _) => None, + (AlternativePaymentMethodType::Giropay, _) => None, (AlternativePaymentMethodType::Sofort, _) | (AlternativePaymentMethodType::Eps, _) => { let address = item.get_billing_address()?; - let first_name = address.get_first_name()?; - ( - Some(BillingAddress { - first_name: Some(first_name.clone()), - last_name: Some(address.get_last_name().unwrap_or(first_name).clone()), - email: item.request.get_email_required()?, - country: item.get_billing_country()?, - }), - None, - ) + address.get_first_name()?; + item.request.get_email_required()?; + item.get_billing_country()?; + None } ( AlternativePaymentMethodType::Ideal, Some(BankRedirectData::Ideal { bank_name, .. }), ) => { let address = item.get_billing_address()?; - let first_name = address.get_first_name()?.clone(); - ( - Some(BillingAddress { - first_name: Some(first_name.clone()), - last_name: Some( - address.get_last_name().ok().unwrap_or(&first_name).clone(), - ), - email: item.request.get_email_required()?, - country: item.get_billing_country()?, - }), - bank_name.map(NuveiBIC::try_from).transpose()?, - ) + address.get_first_name()?; + item.request.get_email_required()?; + item.get_billing_country()?; + bank_name.map(NuveiBIC::try_from).transpose()? } _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Nuvei"), ))?, }; + let billing_address: Option<BillingAddress> = + item.get_billing().ok().map(|billing| billing.into()); Ok(Self { payment_option: PaymentOption { alternative_payment_method: Some(AlternativePaymentMethod { @@ -947,20 +1235,17 @@ where .address .as_ref() .ok_or_else(missing_field_err("billing.address"))?; - let first_name = address.get_first_name()?; + address.get_first_name()?; let payment_method = payment_method_type; + address.get_country()?; //country is necessary check + item.request.get_email_required()?; Ok(NuveiPaymentsRequest { payment_option: PaymentOption { alternative_payment_method: Some(AlternativePaymentMethod { payment_method, ..Default::default() }), - billing_address: Some(BillingAddress { - email: item.request.get_email_required()?, - first_name: Some(first_name.clone()), - last_name: Some(address.get_last_name().unwrap_or(first_name).clone()), - country: address.get_country()?.to_owned(), - }), + billing_address: item.get_billing().ok().map(|billing| billing.into()), ..Default::default() }, ..Default::default() @@ -1104,36 +1389,64 @@ where }?; let currency = item.request.get_currency_required()?; let request = Self::try_from(NuveiPaymentRequestData { - amount: utils::to_currency_base_unit(item.request.get_amount_required()?, currency)?, + amount: convert_amount( + NUVEI_AMOUNT_CONVERTOR, + item.request.get_minor_amount_required()?, + currency, + )?, currency, connector_auth_type: item.connector_auth_type.clone(), client_request_id: item.connector_request_reference_id.clone(), session_token: Secret::new(data.1), capture_method: item.request.get_capture_method(), + ..Default::default() })?; let return_url = item.request.get_return_url_required()?; let amount_details = match item.request.get_order_tax_amount()? { Some(tax) => Some(NuvieAmountDetails { - total_tax: Some(utils::to_currency_base_unit(tax, currency)?), + total_tax: Some(convert_amount(NUVEI_AMOUNT_CONVERTOR, tax, currency)?), }), None => None, }; + let address = { + if let Some(billing_address) = item.get_optional_billing() { + let mut billing_address = billing_address.clone(); + item.get_billing_first_name()?; + billing_address.email = match item.get_billing_email() { + Ok(email) => Some(email), + Err(_) => Some(item.request.get_email_required()?), + }; + item.get_billing_country()?; + + Some(billing_address) + } else { + None + } + }; + + let shipping_address: Option<ShippingAddress> = + item.get_optional_shipping().map(|address| address.into()); + + let billing_address: Option<BillingAddress> = address.map(|ref address| address.into()); Ok(Self { is_rebilling: request_data.is_rebilling, user_token_id: item.customer_id.clone(), related_transaction_id: request_data.related_transaction_id, payment_option: request_data.payment_option, - billing_address: request_data.billing_address, - device_details: request_data.device_details, + billing_address, + shipping_address, + device_details: DeviceDetails::foreign_try_from( + &item.request.get_browser_info().clone(), + )?, url_details: Some(UrlDetails { success_url: return_url.clone(), failure_url: return_url.clone(), pending_url: return_url.clone(), }), amount_details, - + is_partial_approval: item.request.get_is_partial_approval(), ..request }) } @@ -1157,18 +1470,13 @@ where .get_optional_billing() .and_then(|billing_details| billing_details.address.as_ref()); - let billing_address = match address { - Some(address) => { - let first_name = address.get_first_name()?.clone(); - Some(BillingAddress { - first_name: Some(first_name.clone()), - last_name: Some(address.get_last_name().ok().unwrap_or(&first_name).clone()), - email: item.request.get_email_required()?, - country: item.get_billing_country()?, - }) - } - None => None, - }; + if let Some(address) = address { + // mandatory feilds check + address.get_first_name()?; + item.request.get_email_required()?; + item.get_billing_country()?; + } + let (is_rebilling, additional_params, user_token_id) = match item.request.get_setup_mandate_details().clone() { Some(mandate_data) => { @@ -1262,7 +1570,7 @@ where three_d, card_holder_name: item.get_optional_billing_full_name(), }), - billing_address, + is_moto, ..Default::default() }) @@ -1329,7 +1637,11 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, Secret<String>)> )), }?; let request = Self::try_from(NuveiPaymentRequestData { - amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, + amount: convert_amount( + NUVEI_AMOUNT_CONVERTOR, + item.request.minor_amount, + item.request.currency, + )?, currency: item.request.currency, connector_auth_type: item.connector_auth_type.clone(), client_request_id: item.connector_request_reference_id.clone(), @@ -1363,7 +1675,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentsRequest { let merchant_secret = connector_meta.merchant_secret; let transaction_type = TransactionType::get_from_capture_method_and_amount_string( request.capture_method.unwrap_or_default(), - &request.amount, + &request.amount.get_amount_as_string(), ); Ok(Self { merchant_id: merchant_id.clone(), @@ -1376,7 +1688,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentsRequest { merchant_id.peek(), merchant_site_id.peek(), &client_request_id, - &request.amount.clone(), + &request.amount.get_amount_as_string(), &request.currency.to_string(), &time_stamp, merchant_secret.peek(), @@ -1409,7 +1721,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentFlowRequest { merchant_id.peek(), merchant_site_id.peek(), &client_request_id, - &request.amount.clone(), + &request.amount.get_amount_as_string(), &request.currency.to_string(), &request.related_transaction_id.clone().unwrap_or_default(), &time_stamp, @@ -1424,7 +1736,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentFlowRequest { #[derive(Debug, Clone, Default)] pub struct NuveiPaymentRequestData { - pub amount: String, + pub amount: StringMajorUnit, pub currency: enums::Currency, pub related_transaction_id: Option<String>, pub client_request_id: String, @@ -1439,8 +1751,9 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for NuveiPaymentFlowRequest { Self::try_from(NuveiPaymentRequestData { client_request_id: item.connector_request_reference_id.clone(), connector_auth_type: item.connector_auth_type.clone(), - amount: utils::to_currency_base_unit( - item.request.amount_to_capture, + amount: convert_amount( + NUVEI_AMOUNT_CONVERTOR, + item.request.minor_amount_to_capture, item.request.currency, )?, currency: item.request.currency, @@ -1455,8 +1768,9 @@ impl TryFrom<&types::RefundExecuteRouterData> for NuveiPaymentFlowRequest { Self::try_from(NuveiPaymentRequestData { client_request_id: item.connector_request_reference_id.clone(), connector_auth_type: item.connector_auth_type.clone(), - amount: utils::to_currency_base_unit( - item.request.refund_amount, + amount: convert_amount( + NUVEI_AMOUNT_CONVERTOR, + item.request.minor_refund_amount, item.request.currency, )?, currency: item.request.currency, @@ -1533,8 +1847,11 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NuveiPaymentFlowRequest { Self::try_from(NuveiPaymentRequestData { client_request_id: item.connector_request_reference_id.clone(), connector_auth_type: item.connector_auth_type.clone(), - amount: utils::to_currency_base_unit( - item.request.get_amount()?, + amount: convert_amount( + NUVEI_AMOUNT_CONVERTOR, + item.request + .minor_amount + .ok_or_else(missing_field_err("amount"))?, item.request.get_currency()?, )?, currency: item.request.get_currency()?, @@ -1603,6 +1920,15 @@ impl From<NuveiTransactionStatus> for enums::AttemptStatus { } } +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NuveiPartialApproval { + pub requested_amount: StringMajorUnit, + pub requested_currency: enums::Currency, + pub processed_amount: StringMajorUnit, + pub processed_currency: enums::Currency, +} + #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NuveiPaymentsResponse { @@ -1623,6 +1949,7 @@ pub struct NuveiPaymentsResponse { pub fraud_details: Option<FraudDetails>, pub external_scheme_transaction_id: Option<Secret<String>>, pub session_token: Option<Secret<String>>, + pub partial_approval: Option<NuveiPartialApproval>, //The ID of the transaction in the merchant’s system. pub client_unique_id: Option<String>, pub internal_request_id: Option<i64>, @@ -1635,6 +1962,37 @@ pub struct NuveiPaymentsResponse { pub client_request_id: Option<String>, pub merchant_advice_code: Option<String>, } +impl NuveiPaymentsResponse { + /// returns amount_captured and minor_amount_capturable + pub fn get_amount_captured( + &self, + ) -> Result<(Option<i64>, Option<MinorUnit>), error_stack::Report<errors::ConnectorError>> { + match &self.partial_approval { + Some(partial_approval) => { + let amount = utils::convert_back_amount_to_minor_units( + NUVEI_AMOUNT_CONVERTOR, + partial_approval.processed_amount.clone(), + partial_approval.processed_currency, + )?; + match self.transaction_type { + None => Ok((None, None)), + Some(NuveiTransactionType::Sale) => { + Ok((Some(MinorUnit::get_amount_as_i64(amount)), None)) + } + Some(NuveiTransactionType::Auth) => Ok((None, Some(amount))), + Some(NuveiTransactionType::Auth3D) => { + Ok((Some(MinorUnit::get_amount_as_i64(amount)), None)) + } + Some(NuveiTransactionType::InitAuth3D) => Ok((None, Some(amount))), + Some(NuveiTransactionType::Credit) => Ok((None, None)), + Some(NuveiTransactionType::Void) => Ok((None, None)), + Some(NuveiTransactionType::Settle) => Ok((None, None)), + } + } + None => Ok((None, None)), + } + } +} #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum NuveiTransactionType { @@ -1708,36 +2066,27 @@ fn get_payment_status( } } -fn build_error_response<T>( - response: &NuveiPaymentsResponse, - http_code: u16, -) -> Option<Result<T, error_stack::Report<errors::ConnectorError>>> { +fn build_error_response(response: &NuveiPaymentsResponse, http_code: u16) -> Option<ErrorResponse> { match response.status { - NuveiPaymentStatus::Error => Some( - get_error_response( - response.err_code, - &response.reason, + NuveiPaymentStatus::Error => Some(get_error_response( + response.err_code, + &response.reason, + http_code, + &response.merchant_advice_code, + &response.gw_error_code.map(|e| e.to_string()), + &response.gw_error_reason, + )), + + _ => { + let err = Some(get_error_response( + response.gw_error_code, + &response.gw_error_reason, http_code, &response.merchant_advice_code, &response.gw_error_code.map(|e| e.to_string()), &response.gw_error_reason, - ) - .map_err(|_err| error_stack::report!(errors::ConnectorError::ResponseHandlingFailed)), - ), - _ => { - let err = Some( - get_error_response( - response.gw_error_code, - &response.gw_error_reason, - http_code, - &response.merchant_advice_code, - &response.gw_error_code.map(|e| e.to_string()), - &response.gw_error_reason, - ) - .map_err(|_err| { - error_stack::report!(errors::ConnectorError::ResponseHandlingFailed) - }), - ); + )); + match response.transaction_status { Some(NuveiTransactionStatus::Error) | Some(NuveiTransactionStatus::Declined) => err, _ => match response @@ -1798,7 +2147,6 @@ where form_fields: std::collections::HashMap::from([("creq".to_string(), creq.expose())]), }), }; - let connector_response_data = convert_to_additional_payment_method_connector_response(&item.response) .map(ConnectorResponseData::with_additional_payment_method_data); @@ -1812,12 +2160,7 @@ where fn create_transaction_response( response: &NuveiPaymentsResponse, redirection_data: Option<RedirectForm>, - http_code: u16, ) -> Result<PaymentsResponseData, error_stack::Report<errors::ConnectorError>> { - if let Some(err) = build_error_response(response, http_code) { - return err; - } - Ok(PaymentsResponseData::TransactionResponse { resource_id: response .transaction_id @@ -1882,13 +2225,19 @@ impl let (status, redirection_data, connector_response_data) = process_nuvei_payment_response(&item, amount)?; + let (amount_captured, minor_amount_capturable) = item.response.get_amount_captured()?; Ok(Self { status, - response: Ok(create_transaction_response( - &item.response, - redirection_data, - item.http_code, - )?), + response: if let Some(err) = build_error_response(&item.response, item.http_code) { + Err(err) + } else { + Ok(create_transaction_response( + &item.response, + redirection_data, + )?) + }, + amount_captured, + minor_amount_capturable, connector_response: connector_response_data, ..item.data }) @@ -1915,13 +2264,19 @@ where let (status, redirection_data, connector_response_data) = process_nuvei_payment_response(&item, amount)?; + let (amount_captured, minor_amount_capturable) = item.response.get_amount_captured()?; Ok(Self { status, - response: Ok(create_transaction_response( - &item.response, - redirection_data, - item.http_code, - )?), + response: if let Some(err) = build_error_response(&item.response, item.http_code) { + Err(err) + } else { + Ok(create_transaction_response( + &item.response, + redirection_data, + )?) + }, + amount_captured, + minor_amount_capturable, connector_response: connector_response_data, ..item.data }) @@ -1982,10 +2337,10 @@ impl TryFrom<RefundsResponseRouterData<Execute, NuveiPaymentsResponse>> .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?; let refund_response = - get_refund_response(item.response.clone(), item.http_code, transaction_id)?; + get_refund_response(item.response.clone(), item.http_code, transaction_id); Ok(Self { - response: Ok(refund_response), + response: refund_response.map_err(|err| *err), ..item.data }) } @@ -2005,10 +2360,10 @@ impl TryFrom<RefundsResponseRouterData<RSync, NuveiPaymentsResponse>> .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?; let refund_response = - get_refund_response(item.response.clone(), item.http_code, transaction_id)?; + get_refund_response(item.response.clone(), item.http_code, transaction_id); Ok(Self { - response: Ok(refund_response), + response: refund_response.map_err(|err| *err), ..item.data }) } @@ -2032,6 +2387,7 @@ where } else { None }; + Ok(Self { related_transaction_id, device_details: DeviceDetails::foreign_try_from( @@ -2065,32 +2421,30 @@ fn get_refund_response( response: NuveiPaymentsResponse, http_code: u16, txn_id: String, -) -> Result<RefundsResponseData, error_stack::Report<errors::ConnectorError>> { +) -> Result<RefundsResponseData, Box<ErrorResponse>> { let refund_status = response .transaction_status .clone() .map(enums::RefundStatus::from) .unwrap_or(enums::RefundStatus::Failure); match response.status { - NuveiPaymentStatus::Error => get_error_response( + NuveiPaymentStatus::Error => Err(Box::new(get_error_response( response.err_code, &response.reason, http_code, &response.merchant_advice_code, &response.gw_error_code.map(|e| e.to_string()), &response.gw_error_reason, - ) - .map_err(|_err| error_stack::report!(errors::ConnectorError::ResponseHandlingFailed)), + ))), _ => match response.transaction_status { - Some(NuveiTransactionStatus::Error) => get_error_response( + Some(NuveiTransactionStatus::Error) => Err(Box::new(get_error_response( response.err_code, &response.reason, http_code, &response.merchant_advice_code, &response.gw_error_code.map(|e| e.to_string()), &response.gw_error_reason, - ) - .map_err(|_err| error_stack::report!(errors::ConnectorError::ResponseHandlingFailed)), + ))), _ => Ok(RefundsResponseData { connector_refund_id: txn_id, refund_status, @@ -2099,15 +2453,15 @@ fn get_refund_response( } } -fn get_error_response<T>( +fn get_error_response( error_code: Option<i64>, error_msg: &Option<String>, http_code: u16, network_advice_code: &Option<String>, network_decline_code: &Option<String>, network_error_message: &Option<String>, -) -> Result<T, Box<ErrorResponse>> { - Err(Box::new(ErrorResponse { +) -> ErrorResponse { + ErrorResponse { code: error_code .map(|c| c.to_string()) .unwrap_or_else(|| NO_ERROR_CODE.to_string()), @@ -2122,7 +2476,7 @@ fn get_error_response<T>( network_decline_code: network_decline_code.clone(), network_error_message: network_error_message.clone(), connector_metadata: None, - })) + } } /// Represents any possible webhook notification from Nuvei. @@ -2394,7 +2748,7 @@ fn convert_to_additional_payment_method_connector_response( "merchant_advice_code_description": merchant_advice_description }); - let card_network = card.card_brand.clone(); + let card_network = card.brand.clone(); let three_ds_data = card .three_d .clone() diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs index c184c9db8dd..29f14f79432 100644 --- a/crates/router/src/types/api/connector_mapping.rs +++ b/crates/router/src/types/api/connector_mapping.rs @@ -322,7 +322,9 @@ impl ConnectorData { enums::Connector::Novalnet => { Ok(ConnectorEnum::Old(Box::new(connector::Novalnet::new()))) } - enums::Connector::Nuvei => Ok(ConnectorEnum::Old(Box::new(&connector::Nuvei))), + enums::Connector::Nuvei => { + Ok(ConnectorEnum::Old(Box::new(connector::Nuvei::new()))) + } enums::Connector::Opennode => { Ok(ConnectorEnum::Old(Box::new(connector::Opennode::new()))) } diff --git a/crates/router/src/types/api/feature_matrix.rs b/crates/router/src/types/api/feature_matrix.rs index ac7754faa30..d7307e7ab68 100644 --- a/crates/router/src/types/api/feature_matrix.rs +++ b/crates/router/src/types/api/feature_matrix.rs @@ -239,7 +239,9 @@ impl FeatureMatrixConnectorData { enums::Connector::Novalnet => { Ok(ConnectorEnum::Old(Box::new(connector::Novalnet::new()))) } - enums::Connector::Nuvei => Ok(ConnectorEnum::Old(Box::new(&connector::Nuvei))), + enums::Connector::Nuvei => { + Ok(ConnectorEnum::Old(Box::new(connector::Nuvei::new()))) + } enums::Connector::Opennode => { Ok(ConnectorEnum::Old(Box::new(connector::Opennode::new()))) } diff --git a/crates/router/tests/connectors/nuvei.rs b/crates/router/tests/connectors/nuvei.rs index f2db3c94a4d..395ad1d1ea9 100644 --- a/crates/router/tests/connectors/nuvei.rs +++ b/crates/router/tests/connectors/nuvei.rs @@ -16,7 +16,7 @@ impl utils::Connector for NuveiTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Nuvei; utils::construct_connector_data_old( - Box::new(&Nuvei), + Box::new(Nuvei::new()), types::Connector::Nuvei, types::api::GetToken::Connector, None,
2025-08-19T07:19:30Z
## 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 --> Add the following features in nuvie 1. Google pay decrypt flow S2S 2. Apple pay decrypt flow S2S 3. Google pay encrypt flow 4. Partial Authorization 5. Send shipping address for nuvei (previously not sent) ## Test attachment <details> <summary> <b>APPLE PAY DECRYPT FLOW </b> </summary> # Request ```json { "amount": 1, "currency": "EUR", "confirm": true, // "order_tax_amount": 100, "setup_future_usage": "off_session", // "payment_type":"setup_mandate", "customer_id": "nithxxinn", "return_url": "https://www.google.com", "capture_method": "automatic", "payment_method": "wallet", "payment_method_type": "apple_pay", "authentication_type": "no_three_ds", "description": "hellow world", "billing": { "address": { "zip": "560095", "country": "US", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" }, "email":"nithingowdan77@gmail.com" }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "hello@gmail.com", "payment_method_data": { "wallet": { "apple_pay": { "payment_data": { "application_primary_account_number": "4242424242424242", "application_expiration_month": "09", "application_expiration_year": "30", "application_brand":"VISA", "payment_data": { "online_payment_cryptogram": "ArSx8**************************", "eci_indicator": "7" } }, "payment_method": { "display_name": "Discover 9319", "network": "VISA", "type": "debit" }, "transaction_identifier": "c635c5b3af900d7bd81fecd7028f1262f9d030754ee65ec7afd988a678194751" } } } } ``` # Response ```json { "payment_id": "pay_MgXkheRylOHLMUllc1Mw", "merchant_id": "merchant_1755589543", "status": "succeeded", "amount": 1, "net_amount": 1, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1, "connector": "nuvei", "client_secret": "pay_MgXkheRylOHLMUllc1Mw_secret_swUebKaDNEsP4Qo5BMxe", "created": "2025-08-19T08:05:14.847Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "hello@gmail.com", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": { "apple_pay": { "last4": "9319", "card_network": "VISA", "type": "debit" } }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": "nithin*****@gmail.com" }, "order_details": null, "email": "hello@gmail.com", "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "apple_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nithxxinn", "created_at": 1755590714, "expires": 1755594314, "secret": "epk_ad5c941cff3a4404ab38dee084e575d0" }, "manual_retry_allowed": false, "connector_transaction_id": "8110000000012650848", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8027431111", "payment_link": null, "profile_id": "pro_o6xLMNfkFwAWH1U1zimF", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_8DFDwR4GryN3qQQOh8bq", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-19T08:20:14.847Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-19T08:05:17.249Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details> <details> <summary> Google pay Decrypt </summary> ## Request ```json { "amount": 1, "currency": "EUR", "confirm": true, "customer_id": "nithxxinn", "return_url": "https://www.google.com", "capture_method": "automatic", "payment_method": "wallet", "payment_method_type": "google_pay", "authentication_type": "no_three_ds", "description": "hellow world", "billing": { "address": { "zip": "560095", "country": "UA", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" }, "email":"test@gmail.com" }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "hello@gmail.com", "payment_method_data": { "wallet": { "google_pay": { "type": "CARD", "tokenization_data": { "application_primary_account_number": "4761344136141390", "card_exp_month": "12", "card_exp_year": "25", "cryptogram": "ejJR********************U=", "eci_indicator": "5" }, "info": { "card_details": "Discover 9319", "card_network": "VISA" }, "description": "something" } } } } ``` Response ```json { "payment_id": "pay_0i5TBkizYCY8JIwAPB1H", "merchant_id": "merchant_1755589543", "status": "succeeded", "amount": 1, "net_amount": 1, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1, "connector": "nuvei", "client_secret": "pay_0i5TBkizYCY8JIwAPB1H_secret_7O5zdgMiNJxFdZolSjIJ", "created": "2025-08-19T08:07:18.648Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "hello@gmail.com", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "Discover 9319", "card_network": "VISA", "type": "CARD" } }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "UA", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": "test@gmail.com" }, "order_details": null, "email": "hello@gmail.com", "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "google_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nithxxinn", "created_at": 1755590838, "expires": 1755594438, "secret": "epk_8d9994d7f5594c2a8fb10ebf6c3fdc27" }, "manual_retry_allowed": false, "connector_transaction_id": "8110000000012650994", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8027476111", "payment_link": null, "profile_id": "pro_o6xLMNfkFwAWH1U1zimF", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_8DFDwR4GryN3qQQOh8bq", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-19T08:22:18.648Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-19T08:07:21.259Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details> <details> <summary> GOOGLE PAY DIRECT </summary> ```js const tokenizationSpecification = { type: "PAYMENT_GATEWAY", parameters: { "gateway": "nuveidigital", "gatewayMerchantId": "googletest" } }; ``` ## Request ```json { "amount": 1, "currency": "EUR", "confirm": true, "customer_id": "nithxxinn", "return_url": "https://www.google.com", "capture_method": "automatic", "payment_method": "wallet", "payment_method_type": "google_pay", "authentication_type": "no_three_ds", "description": "hellow world", "billing": { "address": { "zip": "560095", "country": "UA", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" }, "email":"nithin@test.com" }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "hello@gmail.com", "payment_method_data": { "wallet": { "google_pay": { "description": "SG Visa Success: Visa ‒‒‒‒ 1390", "info": { "assuranceDetails": { "account_verified": true, "card_holder_authenticated": false }, "card_details": "1390", "card_network": "VISA" }, "tokenization_data": { "token": "{\"signature\":\"MEUCIG7saL2k07Szf8ezokemD5jAJTwpcWwpy+ajTJot7u+nAiEAzvcuwAoj47r8oMh3a6eUKeZB2lFyDLEzZt2R2lpezo0\\u003d\",\"intermediateSigningKey\":{\"signedKey\":\"{\\\"keyValue\\\":\\\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE9ByUUgcs6d9rtJA3svCKaGZQjfsbMQAAwWZ6YNIpJkg/NR9HAkMT1sdhkKMRxtcFp1k5y01dr/JpEU2Pj3XyYw\\\\u003d\\\\u003d\\\",\\\"keyExpiration\\\":\\\"1756245691797\\\"}\",\"signatures\":[\"MEQCIFAS8NBh7J4rz00iRDjScYizAfRV+pVnCfsmsFgrehMVAiBpxHFUu6wG3UVNhDMmudb6sZeZHXDJonLkkKOWgzN4TA\\u003d\\u003d\"]},\"protocolVersion\":\"ECv2\",\"signedMessage\":\"{\\\"encryptedMessage\\\":\\\"hJxayhOT/y4ekX9Ub14X6nl7Xm0h3b1nu8FKv7WDulloondBA+kk9sYnNomQx+ZPANrGES4CBGbmptqW5gR6TjdvENXbSUrTjzU8k++Klw/AwAJBcID+dL+EgyIvgmqIYesLyKzITkZr9zSxtd0zuB9ewcta8gHgBzlZmJSWmdvanv4xiBQgjriKolnw4IiOXXAzN+X0GGXkPqcQnlLIrUzjn/9oCgwhFDltl1EJjkUH8Ji2Rzx62FUexxY6RHHrkoq3pCoirc+KNRXPu3+gC06iloRTR48gmmayFKH5s3Kyw0j9Oypu7fx/AgSqrFKkFzVUmCV0yLwGQSI2vyVdKOFLgLay8dDbEHKvF5X+ZP7diunVh0QwZUTT7yRmgyQUaZAbQhd+uRHrev6SYXcmWdSu8E+8H6A7jtITaZN2eHI7u9ciW82/AcIx3gPkTocKGyXdYRB07+GaFIqyWwxT+9TwLW49oq7hbj978APK1vy4f8x6v2h1tCj6StH6md7xJpn+U47n8rKmJhQiXqRyzfKFcCekndvs0YpgEVbcoZEKKl0E\\\",\\\"ephemeralPublicKey\\\":\\\"BKvkUFUZmpa0BgifTbr2ZTNBK7D74Fg8RMsk2Txta+Vf+vX1/BZLUaITfjpgJ5Xqt3rz+AmrkFe+XRvT5E4R7nc\\\\u003d\\\",\\\"tag\\\":\\\"cGNVu61W/PvTC89JXVMUcsKaZIOpt92oexc+aztsKqw\\\\u003d\\\"}\"}", "type": "PAYMENT_GATEWAY" }, "type": "CARD" } }} } ``` ## response ```json { "payment_id": "pay_UGldGh1QW8CTJJJ22CMJ", "merchant_id": "merchant_1755589543", "status": "succeeded", "amount": 1, "net_amount": 1, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1, "connector": "nuvei", "client_secret": "pay_UGldGh1QW8CTJJJ22CMJ_secret_nKqyqNJ02RgcaMsBBz51", "created": "2025-08-19T09:08:25.037Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "hello@gmail.com", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "1390", "card_network": "VISA", "type": "CARD" } }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "UA", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": "nithin@test.com" }, "order_details": null, "email": "hello@gmail.com", "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "google_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nithxxinn", "created_at": 1755594505, "expires": 1755598105, "secret": "epk_d3dbd5a8b4c04958b6fb4c959cbc67a1" }, "manual_retry_allowed": false, "connector_transaction_id": "8110000000012655452", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8029357111", "payment_link": null, "profile_id": "pro_o6xLMNfkFwAWH1U1zimF", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_8DFDwR4GryN3qQQOh8bq", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-19T09:23:25.037Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-19T09:08:29.510Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` </details> <details> <summary>Partial auth </summary> ## Request ```json { "amount": 300, "currency": "EUR", "confirm": true, "customer_id": "nithxxinn", "return_url": "https://www.google.com", "capture_method": "automatic", "enable_partial_authorization":true, "payment_method": "card", "payment_method_type": "credit", "authentication_type": "no_three_ds", "description": "hellow world", "billing": { "address": { "zip": "560095", "country": "US", "first_name": "Sakil", "last_name": "Mostak", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" }, "email":"nithin@gmail.com" }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "ip_address": "192.168.1.1", "java_enabled": false, "java_script_enabled": true, "language": "en-US", "color_depth": 24, "screen_height": 1080, "screen_width": 1920, "time_zone": 330, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" }, "email": "hello@gmail.com", "payment_method_data": { "card": { "card_number": "4531739335817394", "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "card_cvc": "100" } } } ``` ## Response ```json { "payment_id": "pay_hieZ9MkK4v1qbqiXKEor", "merchant_id": "merchant_1755589543", "status": "partially_captured", "amount": 300, "net_amount": 300, "shipping_cost": null, "amount_capturable": 300, "amount_received": 150, "connector": "nuvei", "client_secret": "pay_hieZ9MkK4v1qbqiXKEor_secret_KN9DE1LjGlbxEIDGpzFT", "created": "2025-08-19T09:21:17.091Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "hello@gmail.com", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "7394", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "453173", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": { "avs_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "challengePreferenceReason": "12" } }, "billing": null }, "payment_token": "token_7PrpuuSVcta1g2qFHYtC", "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": "nithin@gmail.com" }, "order_details": null, "email": "hello@gmail.com", "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nithxxinn", "created_at": 1755595277, "expires": 1755598877, "secret": "epk_8003507abbdb427788e1fa089e75c59c" }, "manual_retry_allowed": false, "connector_transaction_id": "8110000000012656330", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8029726111", "payment_link": null, "profile_id": "pro_o6xLMNfkFwAWH1U1zimF", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_8DFDwR4GryN3qQQOh8bq", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-19T09:36:17.091Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-19T09:21:19.648Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": true } ``` ## partial-auth manual payment response ```json { "payment_id": "pay_t82V58k4cohYq87gBvGL", "merchant_id": "merchant_1755675958", "status": "partially_authorized_and_requires_capture", "amount": 300, "net_amount": 300, "shipping_cost": null, "amount_capturable": 150, "amount_received": null, "connector": "nuvei", "client_secret": "pay_t82V58k4cohYq87gBvGL_secret_CHN75ZbLuZWVBKYTITqg", "created": "2025-08-21T08:37:13.180Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "hello@gmail.com", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "7394", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "453173", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": { "avs_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "challengePreferenceReason": "12" } }, "billing": null }, "payment_token": "token_yUVtqVsfxyKqmAM4fl1H", "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "hello@gmail.com", "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "nithxxinn", "created_at": 1755765433, "expires": 1755769033, "secret": "epk_c7ea65af285e4db69a3bd6fbcb553bf4" }, "manual_retry_allowed": false, "connector_transaction_id": "8110000000012833076", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8101170111", "payment_link": null, "profile_id": "pro_8OqPL5PekR8mRXU8WZZs", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_48b4pLXImpTC9wJALk91", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-21T08:52:13.180Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-21T08:37:15.983Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": true } ``` ### capture partial ```json { "payment_id": "pay_t82V58k4cohYq87gBvGL", "merchant_id": "merchant_1755675958", "status": "partially_captured", "amount": 300, "net_amount": 300, "shipping_cost": null, "amount_capturable": 0, "amount_received": 150, "connector": "nuvei", "client_secret": "pay_t82V58k4cohYq87gBvGL_secret_CHN75ZbLuZWVBKYTITqg", "created": "2025-08-21T08:37:13.180Z", "currency": "EUR", "customer_id": "nithxxinn", "customer": { "id": "nithxxinn", "name": null, "email": "hello@gmail.com", "phone": null, "phone_country_code": null }, "description": "hellow world", "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": "7394", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "453173", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "John Smith", "payment_checks": { "avs_description": null, "avs_result_code": "", "cvv_2_reply_code": "", "cvv_2_description": null, "merchant_advice_code": "", "merchant_advice_code_description": null }, "authentication_data": { "challengePreferenceReason": "12" } }, "billing": null }, "payment_token": "token_yUVtqVsfxyKqmAM4fl1H", "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak", "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "hello@gmail.com", "name": null, "phone": null, "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "8110000000012833218", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "direct" }, "reference_id": "8101170111", "payment_link": null, "profile_id": "pro_8OqPL5PekR8mRXU8WZZs", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_48b4pLXImpTC9wJALk91", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-21T08:52:13.180Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": 330, "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "color_depth": 24, "java_enabled": false, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-21T08:37:57.428Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": true } ``` </details> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables - [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.116.0
c90625a4ea163e03895276a04ec3a23d4117413d
c90625a4ea163e03895276a04ec3a23d4117413d
juspay/hyperswitch
juspay__hyperswitch-8874
Bug: chore: address Rust 1.89.0 clippy lints Address the clippy lints occurring due to new rust version 1.89.0 See https://github.com/juspay/hyperswitch/issues/3391 for more information.
diff --git a/crates/euclid_macros/src/inner/knowledge.rs b/crates/euclid_macros/src/inner/knowledge.rs index 49d645be72a..837a511f02d 100644 --- a/crates/euclid_macros/src/inner/knowledge.rs +++ b/crates/euclid_macros/src/inner/knowledge.rs @@ -301,35 +301,6 @@ impl Parse for Rule { } } -#[derive(Clone)] -enum Scope { - Crate, - Extern, -} - -impl Parse for Scope { - fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { - let lookahead = input.lookahead1(); - if lookahead.peek(Token![crate]) { - input.parse::<Token![crate]>()?; - Ok(Self::Crate) - } else if lookahead.peek(Token![extern]) { - input.parse::<Token![extern]>()?; - Ok(Self::Extern) - } else { - Err(lookahead.error()) - } - } -} - -impl Display for Scope { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - match self { - Self::Crate => write!(f, "crate"), - Self::Extern => write!(f, "euclid"), - } - } -} #[derive(Clone)] struct Program { rules: Vec<Rc<Rule>>, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index d70dc7933b4..50d703ba6a5 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -782,10 +782,11 @@ where payment_data = match connector_details { ConnectorCallType::PreDetermined(ref connector) => { #[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( + std::slice::from_ref(connector), + ) + .map_err(|e| logger::error!(routable_connector_error=?e)) + .unwrap_or_default(); let schedule_time = if should_add_task_to_process_tracker { payment_sync::get_sync_process_schedule_time( &*state.store, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 6554ec1b016..837b0bcf9fc 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -400,12 +400,12 @@ pub async fn connect_account( logger::info!(?welcome_email_result); } - return Ok(ApplicationResponse::Json( + Ok(ApplicationResponse::Json( user_api::ConnectAccountResponse { is_email_sent: magic_link_result.is_ok(), user_id: user_from_db.get_user_id().to_string(), }, - )); + )) } else { Err(find_user .err()
2025-08-08T07:57:33Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR addresses the clippy lints occurring due to new rust version 1.89.0 ### 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. just clippy <img width="552" height="237" alt="image" src="https://github.com/user-attachments/assets/11c34b90-2697-48c2-ad08-7436e83f6799" /> 2. just clippy_v2 <img width="548" height="223" alt="image" src="https://github.com/user-attachments/assets/42da0048-5e03-4302-8f1c-fd0885ce882d" /> ## 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.116.0
838de443d1ed8d0d509e86d75e3220bedc9121e8
838de443d1ed8d0d509e86d75e3220bedc9121e8
juspay/hyperswitch
juspay__hyperswitch-8872
Bug: [FEATURE]: add support of passing metadata in adyen payment request add support of passing metadata in adyen payment request
diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index 53ecbf882e6..df98be4c684 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -292,6 +292,7 @@ pub struct AdyenPaymentRequest<'a> { device_fingerprint: Option<Secret<String>>, #[serde(with = "common_utils::custom_serde::iso8601::option")] session_validity: Option<PrimitiveDateTime>, + metadata: Option<serde_json::Value>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -2936,6 +2937,7 @@ impl splits, device_fingerprint, session_validity: None, + metadata: item.router_data.request.metadata.clone(), }) } } @@ -3020,6 +3022,7 @@ impl TryFrom<(&AdyenRouterData<&PaymentsAuthorizeRouterData>, &Card)> for AdyenP splits, device_fingerprint, session_validity: None, + metadata: item.router_data.request.metadata.clone(), }) } } @@ -3108,6 +3111,7 @@ impl splits, device_fingerprint, session_validity: None, + metadata: item.router_data.request.metadata.clone(), }; Ok(request) } @@ -3184,6 +3188,7 @@ impl TryFrom<(&AdyenRouterData<&PaymentsAuthorizeRouterData>, &VoucherData)> splits, device_fingerprint, session_validity: None, + metadata: item.router_data.request.metadata.clone(), }; Ok(request) } @@ -3302,6 +3307,7 @@ impl splits, device_fingerprint, session_validity, + metadata: item.router_data.request.metadata.clone(), }; Ok(request) } @@ -3379,6 +3385,7 @@ impl splits, device_fingerprint, session_validity: None, + metadata: item.router_data.request.metadata.clone(), }; Ok(request) } @@ -3460,6 +3467,7 @@ impl splits, device_fingerprint, session_validity: None, + metadata: item.router_data.request.metadata.clone(), }) } } @@ -3591,6 +3599,7 @@ impl TryFrom<(&AdyenRouterData<&PaymentsAuthorizeRouterData>, &WalletData)> splits, device_fingerprint, session_validity: None, + metadata: item.router_data.request.metadata.clone(), }) } } @@ -3681,6 +3690,7 @@ impl splits, device_fingerprint, session_validity: None, + metadata: item.router_data.request.metadata.clone(), }) } } @@ -3763,6 +3773,7 @@ impl splits, device_fingerprint, session_validity: None, + metadata: item.router_data.request.metadata.clone(), }) } } @@ -6018,6 +6029,7 @@ impl splits, device_fingerprint, session_validity: None, + metadata: item.router_data.request.metadata.clone(), }) } }
2025-08-08T07:20:47Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Make a adyen payment request by passing metadata ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_gfSvA66FtTOYRAET2roFlwpZII7Im5qV58tVCQ8nmgfvCGW34H7KOatZrmImGpJi' \ --data-raw '{ "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4917610000000000", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "metadata": { "order_id": "ORD-12345", "customer_segment": "premium", "purchase_platform": "web_store" }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "merchant_order_reference_id" : "order_narvar12", "browser_info": { "os_type": "macOS", "language": "en-GB", "time_zone": -330, "ip_address": "103.159.11.202", "os_version": "10.15.7", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36", "color_depth": 24, "device_model": "Macintosh", "java_enabled": true, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1080, "accept_language": "en", "java_script_enabled": true }, "profile_id": "pro_16j8JOCurimvr2XXG9EE" }' ``` Response ``` { "payment_id": "pay_hzlcxXX8nyJI66W4kWqV", "merchant_id": "merchant_1754636642", "status": "requires_customer_action", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "adyen", "client_secret": "pay_hzlcxXX8nyJI66W4kWqV_secret_nCpTSGcFPShUZCI00wx1", "created": "2025-08-08T07:04:25.612Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0000", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "491761", "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, "origin_zip": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null, "origin_zip": null }, "phone": null, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_hzlcxXX8nyJI66W4kWqV/merchant_1754636642/pay_hzlcxXX8nyJI66W4kWqV_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": "StripeCustomer", "created_at": 1754636665, "expires": 1754640265, "secret": "epk_4fc117f853654c8289fb1024aa8dbeed" }, "manual_retry_allowed": null, "connector_transaction_id": "SPD59ZTRRZ9TPM75", "frm_message": null, "metadata": { "order_id": "ORD-12345", "customer_segment": "premium", "purchase_platform": "web_store" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "SPD59ZTRRZ9TPM75", "payment_link": null, "profile_id": "pro_BkMsi4kLNDDn7Occ4u2v", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_hwPRKWHa1C2kQQ9Y86sr", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-08T07:19:25.612Z", "fingerprint": null, "browser_info": { "os_type": "macOS", "language": "en-GB", "time_zone": -330, "ip_address": "103.159.11.202", "os_version": "10.15.7", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36", "color_depth": 24, "device_model": "Macintosh", "java_enabled": true, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1080, "accept_language": "en", "java_script_enabled": true }, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-08T07:04:26.048Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": "order_narvar12", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null, "enable_partial_authorization": null } ``` In adyen dashboard it should show up like this: <img width="696" height="210" alt="Screenshot 2025-08-08 at 12 50 13β€―PM" src="https://github.com/user-attachments/assets/5cee3d27-a810-49fe-a1d3-42fe43caac83" /> Cypress test <img width="1912" height="1880" alt="Screenshot 2025-08-08 at 8 36 49β€―PM" src="https://github.com/user-attachments/assets/b012d628-f74d-4e3a-bd3c-3893bae9115a" /> ## 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.116.0
838de443d1ed8d0d509e86d75e3220bedc9121e8
838de443d1ed8d0d509e86d75e3220bedc9121e8
juspay/hyperswitch
juspay__hyperswitch-8880
Bug: [FEATURE]: Add support for Webhooks through UCS ### Feature Description the Webhooks should go to Unified connector service and should be handled there ### Possible Implementation add webhook integration in hyperswitch ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs index 8db71c930f3..4f6313ea31a 100644 --- a/crates/external_services/src/grpc_client/unified_connector_service.rs +++ b/crates/external_services/src/grpc_client/unified_connector_service.rs @@ -9,7 +9,8 @@ use tonic::{ }; use unified_connector_service_client::payments::{ self as payments_grpc, payment_service_client::PaymentServiceClient, - PaymentServiceAuthorizeResponse, + PaymentServiceAuthorizeResponse, PaymentServiceTransformRequest, + PaymentServiceTransformResponse, }; use crate::{ @@ -96,6 +97,10 @@ pub enum UnifiedConnectorServiceError { /// Failed to perform Payment Repeat Payment from gRPC Server #[error("Failed to perform Repeat Payment from gRPC Server")] PaymentRepeatEverythingFailure, + + /// Failed to transform incoming webhook from gRPC Server + #[error("Failed to transform incoming webhook from gRPC Server")] + WebhookTransformFailure, } /// Result type for Dynamic Routing @@ -194,6 +199,7 @@ impl UnifiedConnectorServiceClient { ) -> UnifiedConnectorServiceResult<tonic::Response<PaymentServiceAuthorizeResponse>> { let mut request = tonic::Request::new(payment_authorize_request); + let connector_name = connector_auth_metadata.connector_name.clone(); let metadata = build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?; *request.metadata_mut() = metadata; @@ -203,7 +209,14 @@ impl UnifiedConnectorServiceClient { .authorize(request) .await .change_context(UnifiedConnectorServiceError::PaymentAuthorizeFailure) - .inspect_err(|error| logger::error!(?error)) + .inspect_err(|error| { + logger::error!( + grpc_error=?error, + method="payment_authorize", + connector_name=?connector_name, + "UCS payment authorize gRPC call failed" + ) + }) } /// Performs Payment Sync/Get @@ -216,6 +229,7 @@ impl UnifiedConnectorServiceClient { { let mut request = tonic::Request::new(payment_get_request); + let connector_name = connector_auth_metadata.connector_name.clone(); let metadata = build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?; *request.metadata_mut() = metadata; @@ -225,7 +239,14 @@ impl UnifiedConnectorServiceClient { .get(request) .await .change_context(UnifiedConnectorServiceError::PaymentGetFailure) - .inspect_err(|error| logger::error!(?error)) + .inspect_err(|error| { + logger::error!( + grpc_error=?error, + method="payment_get", + connector_name=?connector_name, + "UCS payment get/sync gRPC call failed" + ) + }) } /// Performs Payment Setup Mandate @@ -238,6 +259,7 @@ impl UnifiedConnectorServiceClient { { let mut request = tonic::Request::new(payment_register_request); + let connector_name = connector_auth_metadata.connector_name.clone(); let metadata = build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?; *request.metadata_mut() = metadata; @@ -247,7 +269,14 @@ impl UnifiedConnectorServiceClient { .register(request) .await .change_context(UnifiedConnectorServiceError::PaymentRegisterFailure) - .inspect_err(|error| logger::error!(?error)) + .inspect_err(|error| { + logger::error!( + grpc_error=?error, + method="payment_setup_mandate", + connector_name=?connector_name, + "UCS payment setup mandate gRPC call failed" + ) + }) } /// Performs Payment repeat (MIT - Merchant Initiated Transaction). @@ -261,6 +290,7 @@ impl UnifiedConnectorServiceClient { > { let mut request = tonic::Request::new(payment_repeat_request); + let connector_name = connector_auth_metadata.connector_name.clone(); let metadata = build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?; *request.metadata_mut() = metadata; @@ -270,7 +300,43 @@ impl UnifiedConnectorServiceClient { .repeat_everything(request) .await .change_context(UnifiedConnectorServiceError::PaymentRepeatEverythingFailure) - .inspect_err(|error| logger::error!(?error)) + .inspect_err(|error| { + logger::error!( + grpc_error=?error, + method="payment_repeat", + connector_name=?connector_name, + "UCS payment repeat gRPC call failed" + ) + }) + } + + /// Transforms incoming webhook through UCS + pub async fn transform_incoming_webhook( + &self, + webhook_transform_request: PaymentServiceTransformRequest, + connector_auth_metadata: ConnectorAuthMetadata, + grpc_headers: GrpcHeaders, + ) -> UnifiedConnectorServiceResult<tonic::Response<PaymentServiceTransformResponse>> { + let mut request = tonic::Request::new(webhook_transform_request); + + let connector_name = connector_auth_metadata.connector_name.clone(); + let metadata = + build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?; + *request.metadata_mut() = metadata; + + self.client + .clone() + .transform(request) + .await + .change_context(UnifiedConnectorServiceError::WebhookTransformFailure) + .inspect_err(|error| { + logger::error!( + grpc_error=?error, + method="transform_incoming_webhook", + connector_name=?connector_name, + "UCS webhook transform gRPC call failed" + ) + }) } } @@ -318,17 +384,18 @@ pub fn build_unified_connector_service_grpc_headers( parse(common_utils_consts::X_MERCHANT_ID, meta.merchant_id.peek())?, ); - grpc_headers.tenant_id - .parse() - .map(|tenant_id| { - metadata.append( - common_utils_consts::TENANT_HEADER, - tenant_id) - }) - .inspect_err( - |err| logger::warn!(header_parse_error=?err,"invalid {} received",common_utils_consts::TENANT_HEADER), - ) - .ok(); + if let Err(err) = grpc_headers + .tenant_id + .parse() + .map(|tenant_id| metadata.append(common_utils_consts::TENANT_HEADER, tenant_id)) + { + logger::error!( + header_parse_error=?err, + tenant_id=?grpc_headers.tenant_id, + "Failed to parse tenant_id header for UCS gRPC request: {}", + common_utils_consts::TENANT_HEADER + ); + } Ok(metadata) } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index a6be59c8114..87f47a9b2bb 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -4188,6 +4188,15 @@ impl MerchantConnectorAccountType { Self::CacheVal(_) => None, } } + + pub fn get_webhook_details( + &self, + ) -> CustomResult<Option<&masking::Secret<serde_json::Value>>, errors::ApiErrorResponse> { + match self { + Self::DbVal(db_val) => Ok(db_val.connector_webhook_details.as_ref()), + Self::CacheVal(_) => Ok(None), + } + } } /// Query for merchant connector account either by business label or profile id diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs index 107b6e7e7a2..4e32095dea7 100644 --- a/crates/router/src/core/unified_connector_service.rs +++ b/crates/router/src/core/unified_connector_service.rs @@ -1,3 +1,4 @@ +use api_models::admin; use common_enums::{AttemptStatus, PaymentMethodType}; use common_utils::{errors::CustomResult, ext_traits::ValueExt}; use error_stack::ResultExt; @@ -13,6 +14,7 @@ use hyperswitch_domain_models::{ router_response_types::PaymentsResponseData, }; use masking::{ExposeInterface, PeekInterface, Secret}; +use router_env::logger; use unified_connector_service_client::payments::{ self as payments_grpc, payment_method::PaymentMethod, CardDetails, CardPaymentMethodType, PaymentServiceAuthorizeResponse, @@ -21,7 +23,7 @@ use unified_connector_service_client::payments::{ use crate::{ consts, core::{ - errors::RouterResult, + errors::{ApiErrorResponse, RouterResult}, payments::helpers::{ is_ucs_enabled, should_execute_based_on_rollout, MerchantConnectorAccountType, }, @@ -29,9 +31,13 @@ use crate::{ }, routes::SessionState, types::transformers::ForeignTryFrom, + utils, }; -mod transformers; +pub mod transformers; + +// Re-export webhook transformer types for easier access +pub use transformers::WebhookTransformData; pub async fn should_call_unified_connector_service<F: Clone, T>( state: &SessionState, @@ -80,6 +86,42 @@ pub async fn should_call_unified_connector_service<F: Clone, T>( Ok(should_execute) } +pub async fn should_call_unified_connector_service_for_webhooks( + state: &SessionState, + merchant_context: &MerchantContext, + connector_name: &str, +) -> RouterResult<bool> { + if state.grpc_client.unified_connector_service_client.is_none() { + logger::debug!( + connector = connector_name.to_string(), + "Unified Connector Service client is not available for webhooks" + ); + return Ok(false); + } + + let ucs_config_key = consts::UCS_ENABLED; + + if !is_ucs_enabled(state, ucs_config_key).await { + return Ok(false); + } + + let merchant_id = merchant_context + .get_merchant_account() + .get_id() + .get_string_repr(); + + let config_key = format!( + "{}_{}_{}_Webhooks", + consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX, + merchant_id, + connector_name + ); + + let should_execute = should_execute_based_on_rollout(state, &config_key).await?; + + Ok(should_execute) +} + pub fn build_unified_connector_service_payment_method( payment_method_data: hyperswitch_domain_models::payment_method_data::PaymentMethodData, payment_method_type: PaymentMethodType, @@ -317,3 +359,161 @@ pub fn handle_unified_connector_service_response_for_payment_repeat( Ok((status, router_data_response, status_code)) } + +pub fn build_webhook_secrets_from_merchant_connector_account( + #[cfg(feature = "v1")] merchant_connector_account: &MerchantConnectorAccountType, + #[cfg(feature = "v2")] merchant_connector_account: &MerchantConnectorAccountTypeDetails, +) -> CustomResult<Option<payments_grpc::WebhookSecrets>, UnifiedConnectorServiceError> { + // Extract webhook credentials from merchant connector account + // This depends on how webhook secrets are stored in the merchant connector account + + #[cfg(feature = "v1")] + let webhook_details = merchant_connector_account + .get_webhook_details() + .map_err(|_| UnifiedConnectorServiceError::FailedToObtainAuthType)?; + + #[cfg(feature = "v2")] + let webhook_details = match merchant_connector_account { + MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => { + mca.connector_webhook_details.as_ref() + } + MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None, + }; + + match webhook_details { + Some(details) => { + // Parse the webhook details JSON to extract secrets + let webhook_details: admin::MerchantConnectorWebhookDetails = details + .clone() + .parse_value("MerchantConnectorWebhookDetails") + .change_context(UnifiedConnectorServiceError::FailedToObtainAuthType) + .attach_printable("Failed to parse MerchantConnectorWebhookDetails")?; + + // Build gRPC WebhookSecrets from parsed details + Ok(Some(payments_grpc::WebhookSecrets { + secret: webhook_details.merchant_secret.expose().to_string(), + additional_secret: webhook_details + .additional_secret + .map(|secret| secret.expose().to_string()), + })) + } + None => Ok(None), + } +} + +/// High-level abstraction for calling UCS webhook transformation +/// This provides a clean interface similar to payment flow UCS calls +pub async fn call_unified_connector_service_for_webhook( + state: &SessionState, + merchant_context: &MerchantContext, + connector_name: &str, + body: &actix_web::web::Bytes, + request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, + merchant_connector_account: Option< + &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, + >, +) -> RouterResult<( + api_models::webhooks::IncomingWebhookEvent, + bool, + WebhookTransformData, +)> { + let ucs_client = state + .grpc_client + .unified_connector_service_client + .as_ref() + .ok_or_else(|| { + error_stack::report!(ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("UCS client is not available for webhook processing") + })?; + + // Build webhook secrets from merchant connector account + let webhook_secrets = merchant_connector_account.and_then(|mca| { + #[cfg(feature = "v1")] + let mca_type = MerchantConnectorAccountType::DbVal(Box::new(mca.clone())); + #[cfg(feature = "v2")] + let mca_type = + MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(mca.clone())); + + build_webhook_secrets_from_merchant_connector_account(&mca_type) + .map_err(|e| { + logger::warn!( + build_error=?e, + connector_name=connector_name, + "Failed to build webhook secrets from merchant connector account in call_unified_connector_service_for_webhook" + ); + e + }) + .ok() + .flatten() + }); + + // Build UCS transform request using new webhook transformers + let transform_request = transformers::build_webhook_transform_request( + body, + request_details, + webhook_secrets, + merchant_context + .get_merchant_account() + .get_id() + .get_string_repr(), + connector_name, + )?; + + // Build connector auth metadata + let connector_auth_metadata = merchant_connector_account + .map(|mca| { + #[cfg(feature = "v1")] + let mca_type = MerchantConnectorAccountType::DbVal(Box::new(mca.clone())); + #[cfg(feature = "v2")] + let mca_type = MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( + mca.clone(), + )); + + build_unified_connector_service_auth_metadata(mca_type, merchant_context) + }) + .transpose() + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to build UCS auth metadata")? + .ok_or_else(|| { + error_stack::report!(ApiErrorResponse::InternalServerError).attach_printable( + "Missing merchant connector account for UCS webhook transformation", + ) + })?; + + // Build gRPC headers + let grpc_headers = external_services::grpc_client::GrpcHeaders { + tenant_id: state.tenant.tenant_id.get_string_repr().to_string(), + request_id: Some(utils::generate_id(consts::ID_LENGTH, "webhook_req")), + }; + + // Make UCS call - client availability already verified + match ucs_client + .transform_incoming_webhook(transform_request, connector_auth_metadata, grpc_headers) + .await + { + Ok(response) => { + let transform_response = response.into_inner(); + let transform_data = transformers::transform_ucs_webhook_response(transform_response)?; + + // UCS handles everything internally - event type, source verification, decoding + Ok(( + transform_data.event_type, + transform_data.source_verified, + transform_data, + )) + } + Err(err) => { + // When UCS is configured, we don't fall back to direct connector processing + Err(ApiErrorResponse::WebhookProcessingFailure) + .attach_printable(format!("UCS webhook processing failed: {err}")) + } + } +} + +/// Extract webhook content from UCS response for further processing +/// This provides a helper function to extract specific data from UCS responses +pub fn extract_webhook_content_from_ucs_response( + transform_data: &WebhookTransformData, +) -> Option<&unified_connector_service_client::payments::WebhookResponseContent> { + transform_data.webhook_content.as_ref() +} diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs index 9f8ad6c128e..a6559abc2d4 100644 --- a/crates/router/src/core/unified_connector_service/transformers.rs +++ b/crates/router/src/core/unified_connector_service/transformers.rs @@ -17,11 +17,14 @@ use hyperswitch_domain_models::{ }; use masking::{ExposeInterface, PeekInterface}; use router_env::tracing; -use unified_connector_service_client::payments::{self as payments_grpc, Identifier}; +use unified_connector_service_client::payments::{ + self as payments_grpc, Identifier, PaymentServiceTransformRequest, + PaymentServiceTransformResponse, +}; use url::Url; use crate::{ - core::unified_connector_service::build_unified_connector_service_payment_method, + core::{errors, unified_connector_service::build_unified_connector_service_payment_method}, types::transformers::ForeignTryFrom, }; impl ForeignTryFrom<&RouterData<PSync, PaymentsSyncData, PaymentsResponseData>> @@ -39,6 +42,13 @@ impl ForeignTryFrom<&RouterData<PSync, PaymentsSyncData, PaymentsResponseData>> .map(|id| Identifier { id_type: Some(payments_grpc::identifier::IdType::Id(id)), }) + .map_err(|e| { + tracing::debug!( + transaction_id_error=?e, + "Failed to extract connector transaction ID for UCS payment sync request" + ); + e + }) .ok(); let connector_ref_id = router_data @@ -670,6 +680,7 @@ impl ForeignTryFrom<common_enums::CardNetwork> for payments_grpc::CardNetwork { common_enums::CardNetwork::UnionPay => Ok(Self::Unionpay), common_enums::CardNetwork::RuPay => Ok(Self::Rupay), common_enums::CardNetwork::Maestro => Ok(Self::Maestro), + common_enums::CardNetwork::AmericanExpress => Ok(Self::Amex), _ => Err( UnifiedConnectorServiceError::RequestEncodingFailedWithReason( "Card Network not supported".to_string(), @@ -1003,6 +1014,113 @@ impl ForeignTryFrom<common_types::payments::CustomerAcceptance> } } +impl ForeignTryFrom<&hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>> + for payments_grpc::RequestDetails +{ + type Error = error_stack::Report<UnifiedConnectorServiceError>; + + fn foreign_try_from( + request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, + ) -> Result<Self, Self::Error> { + let headers_map = request_details + .headers + .iter() + .map(|(key, value)| { + let value_string = value.to_str().unwrap_or_default().to_string(); + (key.as_str().to_string(), value_string) + }) + .collect(); + + Ok(Self { + method: 1, // POST method for webhooks + uri: Some({ + let uri_result = request_details + .headers + .get("x-forwarded-path") + .and_then(|h| h.to_str().map_err(|e| { + tracing::warn!( + header_conversion_error=?e, + header_value=?h, + "Failed to convert x-forwarded-path header to string for webhook processing" + ); + e + }).ok()); + + uri_result.unwrap_or_else(|| { + tracing::debug!("x-forwarded-path header not found or invalid, using default '/Unknown'"); + "/Unknown" + }).to_string() + }), + body: request_details.body.to_vec(), + headers: headers_map, + query_params: Some(request_details.query_params.clone()), + }) + } +} + +/// Webhook transform data structure containing UCS response information +pub struct WebhookTransformData { + pub event_type: api_models::webhooks::IncomingWebhookEvent, + pub source_verified: bool, + pub webhook_content: Option<payments_grpc::WebhookResponseContent>, + pub response_ref_id: Option<String>, +} + +/// Transform UCS webhook response into webhook event data +pub fn transform_ucs_webhook_response( + response: PaymentServiceTransformResponse, +) -> Result<WebhookTransformData, error_stack::Report<errors::ApiErrorResponse>> { + let event_type = match response.event_type { + 0 => api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess, + 1 => api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure, + 2 => api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing, + 3 => api_models::webhooks::IncomingWebhookEvent::PaymentIntentCancelled, + 4 => api_models::webhooks::IncomingWebhookEvent::RefundSuccess, + 5 => api_models::webhooks::IncomingWebhookEvent::RefundFailure, + 6 => api_models::webhooks::IncomingWebhookEvent::MandateRevoked, + _ => api_models::webhooks::IncomingWebhookEvent::EventNotSupported, + }; + + Ok(WebhookTransformData { + event_type, + source_verified: response.source_verified, + webhook_content: response.content, + response_ref_id: response.response_ref_id.and_then(|identifier| { + identifier.id_type.and_then(|id_type| match id_type { + payments_grpc::identifier::IdType::Id(id) => Some(id), + payments_grpc::identifier::IdType::EncodedData(encoded_data) => Some(encoded_data), + payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, + }) + }), + }) +} + +/// Build UCS webhook transform request from webhook components +pub fn build_webhook_transform_request( + _webhook_body: &[u8], + request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, + webhook_secrets: Option<payments_grpc::WebhookSecrets>, + merchant_id: &str, + connector_id: &str, +) -> Result<PaymentServiceTransformRequest, error_stack::Report<errors::ApiErrorResponse>> { + let request_details_grpc = payments_grpc::RequestDetails::foreign_try_from(request_details) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to transform webhook request details to gRPC format")?; + + Ok(PaymentServiceTransformRequest { + request_ref_id: Some(Identifier { + id_type: Some(payments_grpc::identifier::IdType::Id(format!( + "{}_{}_{}", + merchant_id, + connector_id, + time::OffsetDateTime::now_utc().unix_timestamp() + ))), + }), + request_details: Some(request_details_grpc), + webhook_secrets, + }) +} + pub fn convert_connector_service_status_code( status_code: u32, ) -> Result<u16, error_stack::Report<UnifiedConnectorServiceError>> { diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index fae94ceb11a..29a6c6c8e26 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -30,7 +30,7 @@ use crate::{ errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, metrics, payment_methods, payments::{self, tokenization}, - refunds, relay, utils as core_utils, + refunds, relay, unified_connector_service, utils as core_utils, webhooks::{network_tokenization_incoming, utils::construct_webhook_router_data}, }, db::StorageInterface, @@ -202,8 +202,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( WebhookResponseTracker, serde_json::Value, )> { - let key_manager_state = &(&state).into(); - + // Initial setup and metrics metrics::WEBHOOK_INCOMING_COUNT.add( 1, router_env::metric_attributes!(( @@ -211,7 +210,8 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( merchant_context.get_merchant_account().get_id().clone() )), ); - let mut request_details = IncomingWebhookRequestDetails { + + let request_details = IncomingWebhookRequestDetails { method: req.method().clone(), uri: req.uri().clone(), headers: req.headers(), @@ -220,31 +220,211 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( }; // Fetch the merchant connector account to get the webhooks source secret - // `webhooks source secret` is a secret shared between the merchant and connector - // This is used for source verification and webhooks integrity let (merchant_connector_account, connector, connector_name) = fetch_optional_mca_and_connector(&state, &merchant_context, connector_name_or_mca_id) .await?; - let decoded_body = connector - .decode_webhook_body( - &request_details, - merchant_context.get_merchant_account().get_id(), - merchant_connector_account - .clone() - .and_then(|merchant_connector_account| { - merchant_connector_account.connector_webhook_details - }), - connector_name.as_str(), + // Determine webhook processing path (UCS vs non-UCS) and handle event type extraction + let webhook_processing_result = + if unified_connector_service::should_call_unified_connector_service_for_webhooks( + &state, + &merchant_context, + &connector_name, ) - .await + .await? + { + logger::info!( + connector = connector_name, + "Using Unified Connector Service for webhook processing", + ); + process_ucs_webhook_transform( + &state, + &merchant_context, + &connector_name, + &body, + &request_details, + merchant_connector_account.as_ref(), + ) + .await? + } else { + // NON-UCS PATH: Need to decode body first + let decoded_body = connector + .decode_webhook_body( + &request_details, + merchant_context.get_merchant_account().get_id(), + merchant_connector_account + .and_then(|mca| mca.connector_webhook_details.clone()), + &connector_name, + ) + .await + .switch() + .attach_printable("There was an error in incoming webhook body decoding")?; + + process_non_ucs_webhook( + &state, + &merchant_context, + &connector, + &connector_name, + decoded_body.into(), + &request_details, + ) + .await? + }; + + // Update request_details with the appropriate body (decoded for non-UCS, raw for UCS) + let final_request_details = match &webhook_processing_result.decoded_body { + Some(decoded_body) => IncomingWebhookRequestDetails { + method: request_details.method.clone(), + uri: request_details.uri.clone(), + headers: request_details.headers, + query_params: request_details.query_params.clone(), + body: decoded_body, + }, + None => request_details, // Use original request details for UCS + }; + + logger::info!(event_type=?webhook_processing_result.event_type); + + // Check if webhook should be processed further + let is_webhook_event_supported = !matches!( + webhook_processing_result.event_type, + webhooks::IncomingWebhookEvent::EventNotSupported + ); + let is_webhook_event_enabled = !utils::is_webhook_event_disabled( + &*state.clone().store, + connector_name.as_str(), + merchant_context.get_merchant_account().get_id(), + &webhook_processing_result.event_type, + ) + .await; + let flow_type: api::WebhookFlow = webhook_processing_result.event_type.into(); + let process_webhook_further = is_webhook_event_enabled + && is_webhook_event_supported + && !matches!(flow_type, api::WebhookFlow::ReturnResponse); + logger::info!(process_webhook=?process_webhook_further); + let mut event_object: Box<dyn masking::ErasedMaskSerialize> = Box::new(serde_json::Value::Null); + + let webhook_effect = match process_webhook_further { + true => { + let business_logic_result = process_webhook_business_logic( + &state, + req_state, + &merchant_context, + &connector, + &connector_name, + webhook_processing_result.event_type, + webhook_processing_result.source_verified, + &webhook_processing_result.transform_data, + &final_request_details, + is_relay_webhook, + ) + .await; + + match business_logic_result { + Ok(response) => { + // Extract event object for serialization + event_object = extract_webhook_event_object( + &webhook_processing_result.transform_data, + &connector, + &final_request_details, + )?; + response + } + Err(error) => { + let error_result = handle_incoming_webhook_error( + error, + &connector, + connector_name.as_str(), + &final_request_details, + ); + match error_result { + Ok((_, webhook_tracker, _)) => webhook_tracker, + Err(e) => return Err(e), + } + } + } + } + false => { + metrics::WEBHOOK_INCOMING_FILTERED_COUNT.add( + 1, + router_env::metric_attributes!(( + MERCHANT_ID, + merchant_context.get_merchant_account().get_id().clone() + )), + ); + WebhookResponseTracker::NoEffect + } + }; + + // Generate response + let response = connector + .get_webhook_api_response(&final_request_details, None) .switch() - .attach_printable("There was an error in incoming webhook body decoding")?; + .attach_printable("Could not get incoming webhook api response from connector")?; + + let serialized_request = event_object + .masked_serialize() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Could not convert webhook effect to string")?; + + Ok((response, webhook_effect, serialized_request)) +} + +/// Process UCS webhook transformation using the high-level UCS abstraction +async fn process_ucs_webhook_transform( + state: &SessionState, + merchant_context: &domain::MerchantContext, + connector_name: &str, + body: &actix_web::web::Bytes, + request_details: &IncomingWebhookRequestDetails<'_>, + merchant_connector_account: Option<&domain::MerchantConnectorAccount>, +) -> errors::RouterResult<WebhookProcessingResult> { + // Use the new UCS abstraction which provides clean separation + let (event_type, source_verified, transform_data) = + unified_connector_service::call_unified_connector_service_for_webhook( + state, + merchant_context, + connector_name, + body, + request_details, + merchant_connector_account, + ) + .await?; + Ok(WebhookProcessingResult { + event_type, + source_verified, + transform_data: Some(Box::new(transform_data)), + decoded_body: None, // UCS path uses raw body + }) +} +/// Result type for webhook processing path determination +pub struct WebhookProcessingResult { + event_type: webhooks::IncomingWebhookEvent, + source_verified: bool, + transform_data: Option<Box<unified_connector_service::WebhookTransformData>>, + decoded_body: Option<actix_web::web::Bytes>, +} - request_details.body = &decoded_body; +/// Process non-UCS webhook using traditional connector processing +async fn process_non_ucs_webhook( + state: &SessionState, + merchant_context: &domain::MerchantContext, + connector: &ConnectorEnum, + connector_name: &str, + decoded_body: actix_web::web::Bytes, + request_details: &IncomingWebhookRequestDetails<'_>, +) -> errors::RouterResult<WebhookProcessingResult> { + // Create request_details with decoded body for connector processing + let updated_request_details = IncomingWebhookRequestDetails { + method: request_details.method.clone(), + uri: request_details.uri.clone(), + headers: request_details.headers, + query_params: request_details.query_params.clone(), + body: &decoded_body, + }; - let event_type = match connector - .get_webhook_event_type(&request_details) + match connector + .get_webhook_event_type(&updated_request_details) .allow_webhook_event_type_not_found( state .clone() @@ -257,14 +437,13 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( .switch() .attach_printable("Could not find event type in incoming webhook body")? { - Some(event_type) => event_type, - // Early return allows us to acknowledge the webhooks that we do not support + Some(event_type) => Ok(WebhookProcessingResult { + event_type, + source_verified: false, + transform_data: None, + decoded_body: Some(decoded_body), + }), None => { - logger::error!( - webhook_payload =? request_details.body, - "Failed while identifying the event type", - ); - metrics::WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT.add( 1, router_env::metric_attributes!( @@ -272,94 +451,101 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( MERCHANT_ID, merchant_context.get_merchant_account().get_id().clone() ), - ("connector", connector_name) + ("connector", connector_name.to_string()) ), ); - - let response = connector - .get_webhook_api_response(&request_details, None) - .switch() - .attach_printable("Failed while early return in case of event type parsing")?; - - return Ok(( - response, - WebhookResponseTracker::NoEffect, - serde_json::Value::Null, - )); + Err(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("Failed to identify event type in incoming webhook body") } - }; - logger::info!(event_type=?event_type); - - let is_webhook_event_supported = !matches!( - event_type, - webhooks::IncomingWebhookEvent::EventNotSupported - ); - let is_webhook_event_enabled = !utils::is_webhook_event_disabled( - &*state.clone().store, - connector_name.as_str(), - merchant_context.get_merchant_account().get_id(), - &event_type, - ) - .await; + } +} - //process webhook further only if webhook event is enabled and is not event_not_supported - let process_webhook_further = is_webhook_event_enabled && is_webhook_event_supported; +/// Extract webhook event object based on transform data availability +fn extract_webhook_event_object( + transform_data: &Option<Box<unified_connector_service::WebhookTransformData>>, + connector: &ConnectorEnum, + request_details: &IncomingWebhookRequestDetails<'_>, +) -> errors::RouterResult<Box<dyn masking::ErasedMaskSerialize>> { + match transform_data { + Some(transform_data) => match &transform_data.webhook_content { + Some(webhook_content) => { + let serialized_value = serde_json::to_value(webhook_content) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to serialize UCS webhook content")?; + Ok(Box::new(serialized_value)) + } + None => connector + .get_webhook_resource_object(request_details) + .switch() + .attach_printable("Could not find resource object in incoming webhook body"), + }, + None => connector + .get_webhook_resource_object(request_details) + .switch() + .attach_printable("Could not find resource object in incoming webhook body"), + } +} - logger::info!(process_webhook=?process_webhook_further); +/// Process the main webhook business logic after event type determination +#[allow(clippy::too_many_arguments)] +async fn process_webhook_business_logic( + state: &SessionState, + req_state: ReqState, + merchant_context: &domain::MerchantContext, + connector: &ConnectorEnum, + connector_name: &str, + event_type: webhooks::IncomingWebhookEvent, + source_verified_via_ucs: bool, + webhook_transform_data: &Option<Box<unified_connector_service::WebhookTransformData>>, + request_details: &IncomingWebhookRequestDetails<'_>, + is_relay_webhook: bool, +) -> errors::RouterResult<WebhookResponseTracker> { + let object_ref_id = connector + .get_webhook_object_reference_id(request_details) + .switch() + .attach_printable("Could not find object reference id in incoming webhook body")?; + let connector_enum = api_models::enums::Connector::from_str(connector_name) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector", + }) + .attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?; + let connectors_with_source_verification_call = &state.conf.webhook_source_verification_call; - let flow_type: api::WebhookFlow = event_type.into(); - let mut event_object: Box<dyn masking::ErasedMaskSerialize> = Box::new(serde_json::Value::Null); - let webhook_effect = if process_webhook_further - && !matches!(flow_type, api::WebhookFlow::ReturnResponse) + let merchant_connector_account = match Box::pin(helper_utils::get_mca_from_object_reference_id( + state, + object_ref_id.clone(), + merchant_context, + connector_name, + )) + .await { - let object_ref_id = connector - .get_webhook_object_reference_id(&request_details) - .switch() - .attach_printable("Could not find object reference id in incoming webhook body")?; - let connector_enum = api_models::enums::Connector::from_str(&connector_name) - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "connector", - }) - .attach_printable_lazy(|| { - format!("unable to parse connector name {connector_name:?}") - })?; - let connectors_with_source_verification_call = &state.conf.webhook_source_verification_call; - - let merchant_connector_account = match merchant_connector_account { - Some(merchant_connector_account) => merchant_connector_account, - None => { - match Box::pin(helper_utils::get_mca_from_object_reference_id( - &state, - object_ref_id.clone(), - &merchant_context, - &connector_name, - )) - .await - { - Ok(mca) => mca, - Err(error) => { - return handle_incoming_webhook_error( - error, - &connector, - connector_name.as_str(), - &request_details, - ); - } - } + Ok(mca) => mca, + Err(error) => { + let result = + handle_incoming_webhook_error(error, connector, connector_name, request_details); + match result { + Ok((_, webhook_tracker, _)) => return Ok(webhook_tracker), + Err(e) => return Err(e), } - }; + } + }; - let source_verified = if connectors_with_source_verification_call + let source_verified = if source_verified_via_ucs { + // If UCS handled verification, use that result + source_verified_via_ucs + } else { + // Fall back to traditional source verification + if connectors_with_source_verification_call .connectors_with_webhook_source_verification_call .contains(&connector_enum) { verify_webhook_source_verification_call( connector.clone(), - &state, - &merchant_context, + state, + merchant_context, merchant_connector_account.clone(), - &connector_name, - &request_details, + connector_name, + request_details, ) .await .or_else(|error| match error.current_context() { @@ -375,11 +561,11 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( connector .clone() .verify_webhook_source( - &request_details, + request_details, merchant_context.get_merchant_account().get_id(), merchant_connector_account.connector_webhook_details.clone(), merchant_connector_account.connector_account_details.clone(), - connector_name.as_str(), + connector_name, ) .await .or_else(|error| match error.current_context() { @@ -391,235 +577,233 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( }) .switch() .attach_printable("There was an issue in incoming webhook source verification")? - }; - - if source_verified { - metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add( - 1, - router_env::metric_attributes!(( - MERCHANT_ID, - merchant_context.get_merchant_account().get_id().clone() - )), - ); - } else if connector.is_webhook_source_verification_mandatory() { - // if webhook consumption is mandatory for connector, fail webhook - // so that merchant can retrigger it after updating merchant_secret - return Err(errors::ApiErrorResponse::WebhookAuthenticationFailed.into()); } + }; - logger::info!(source_verified=?source_verified); + if source_verified { + metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add( + 1, + router_env::metric_attributes!(( + MERCHANT_ID, + merchant_context.get_merchant_account().get_id().clone() + )), + ); + } else if connector.is_webhook_source_verification_mandatory() { + // if webhook consumption is mandatory for connector, fail webhook + // so that merchant can retrigger it after updating merchant_secret + return Err(errors::ApiErrorResponse::WebhookAuthenticationFailed.into()); + } - event_object = connector - .get_webhook_resource_object(&request_details) - .switch() - .attach_printable("Could not find resource object in incoming webhook body")?; + logger::info!(source_verified=?source_verified); - let webhook_details = api::IncomingWebhookDetails { - object_reference_id: object_ref_id.clone(), - resource_object: serde_json::to_vec(&event_object) - .change_context(errors::ParsingError::EncodeError("byte-vec")) - .attach_printable("Unable to convert webhook payload to a value") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "There was an issue when encoding the incoming webhook body to bytes", - )?, + let event_object: Box<dyn masking::ErasedMaskSerialize> = + if let Some(transform_data) = webhook_transform_data { + // Use UCS transform data if available + if let Some(webhook_content) = &transform_data.webhook_content { + // Convert UCS webhook content to appropriate format + Box::new( + serde_json::to_value(webhook_content) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to serialize UCS webhook content")?, + ) + } else { + // Fall back to connector extraction + connector + .get_webhook_resource_object(request_details) + .switch() + .attach_printable("Could not find resource object in incoming webhook body")? + } + } else { + // Use traditional connector extraction + connector + .get_webhook_resource_object(request_details) + .switch() + .attach_printable("Could not find resource object in incoming webhook body")? }; - let profile_id = &merchant_connector_account.profile_id; + let webhook_details = api::IncomingWebhookDetails { + object_reference_id: object_ref_id.clone(), + resource_object: serde_json::to_vec(&event_object) + .change_context(errors::ParsingError::EncodeError("byte-vec")) + .attach_printable("Unable to convert webhook payload to a value") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "There was an issue when encoding the incoming webhook body to bytes", + )?, + }; - let business_profile = state - .store - .find_business_profile_by_profile_id( - key_manager_state, - merchant_context.get_merchant_key_store(), - profile_id, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { - id: profile_id.get_string_repr().to_owned(), - })?; + let profile_id = &merchant_connector_account.profile_id; + let key_manager_state = &(state).into(); + + let business_profile = state + .store + .find_business_profile_by_profile_id( + key_manager_state, + merchant_context.get_merchant_key_store(), + profile_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { + id: profile_id.get_string_repr().to_owned(), + })?; + + // If the incoming webhook is a relay webhook, then we need to trigger the relay webhook flow + let result_response = if is_relay_webhook { + let relay_webhook_response = Box::pin(relay_incoming_webhook_flow( + state.clone(), + merchant_context.clone(), + business_profile, + webhook_details, + event_type, + source_verified, + )) + .await + .attach_printable("Incoming webhook flow for relay failed"); + + // Using early return ensures unsupported webhooks are acknowledged to the connector + if let Some(errors::ApiErrorResponse::NotSupported { .. }) = relay_webhook_response + .as_ref() + .err() + .map(|a| a.current_context()) + { + logger::error!( + webhook_payload =? request_details.body, + "Failed while identifying the event type", + ); + + let _response = connector + .get_webhook_api_response(request_details, None) + .switch() + .attach_printable( + "Failed while early return in case of not supported event type in relay webhooks", + )?; - // If the incoming webhook is a relay webhook, then we need to trigger the relay webhook flow - let result_response = if is_relay_webhook { - let relay_webhook_response = Box::pin(relay_incoming_webhook_flow( + return Ok(WebhookResponseTracker::NoEffect); + }; + + relay_webhook_response + } else { + let flow_type: api::WebhookFlow = event_type.into(); + match flow_type { + api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow( state.clone(), - merchant_context, + req_state, + merchant_context.clone(), business_profile, webhook_details, - event_type, source_verified, + connector, + request_details, + event_type, )) .await - .attach_printable("Incoming webhook flow for relay failed"); - - // Using early return ensures unsupported webhooks are acknowledged to the connector - if let Some(errors::ApiErrorResponse::NotSupported { .. }) = relay_webhook_response - .as_ref() - .err() - .map(|a| a.current_context()) - { - logger::error!( - webhook_payload =? request_details.body, - "Failed while identifying the event type", - ); - - let response = connector - .get_webhook_api_response(&request_details, None) - .switch() - .attach_printable( - "Failed while early return in case of not supported event type in relay webhooks", - )?; - - return Ok(( - response, - WebhookResponseTracker::NoEffect, - serde_json::Value::Null, - )); - }; + .attach_printable("Incoming webhook flow for payments failed"), - relay_webhook_response - } else { - match flow_type { - api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow( - state.clone(), - req_state, - merchant_context, - business_profile, - webhook_details, - source_verified, - &connector, - &request_details, - event_type, - )) - .await - .attach_printable("Incoming webhook flow for payments failed"), - - api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow( - state.clone(), - merchant_context, - business_profile, - webhook_details, - connector_name.as_str(), - source_verified, - event_type, - )) - .await - .attach_printable("Incoming webhook flow for refunds failed"), + api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow( + state.clone(), + merchant_context.clone(), + business_profile, + webhook_details, + connector_name, + source_verified, + event_type, + )) + .await + .attach_printable("Incoming webhook flow for refunds failed"), - api::WebhookFlow::Dispute => Box::pin(disputes_incoming_webhook_flow( - state.clone(), - merchant_context, - business_profile, - webhook_details, - source_verified, - &connector, - &request_details, - event_type, - )) - .await - .attach_printable("Incoming webhook flow for disputes failed"), + api::WebhookFlow::Dispute => Box::pin(disputes_incoming_webhook_flow( + state.clone(), + merchant_context.clone(), + business_profile, + webhook_details, + source_verified, + connector, + request_details, + event_type, + )) + .await + .attach_printable("Incoming webhook flow for disputes failed"), - api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow( - state.clone(), - req_state, - merchant_context, - business_profile, - webhook_details, - source_verified, - )) - .await - .attach_printable("Incoming bank-transfer webhook flow failed"), + api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow( + state.clone(), + req_state, + merchant_context.clone(), + business_profile, + webhook_details, + source_verified, + )) + .await + .attach_printable("Incoming bank-transfer webhook flow failed"), - api::WebhookFlow::ReturnResponse => Ok(WebhookResponseTracker::NoEffect), + api::WebhookFlow::ReturnResponse => Ok(WebhookResponseTracker::NoEffect), - api::WebhookFlow::Mandate => Box::pin(mandates_incoming_webhook_flow( - state.clone(), - merchant_context, - business_profile, - webhook_details, - source_verified, - event_type, - )) - .await - .attach_printable("Incoming webhook flow for mandates failed"), + api::WebhookFlow::Mandate => Box::pin(mandates_incoming_webhook_flow( + state.clone(), + merchant_context.clone(), + business_profile, + webhook_details, + source_verified, + event_type, + )) + .await + .attach_printable("Incoming webhook flow for mandates failed"), - api::WebhookFlow::ExternalAuthentication => { - Box::pin(external_authentication_incoming_webhook_flow( - state.clone(), - req_state, - merchant_context, - source_verified, - event_type, - &request_details, - &connector, - object_ref_id, - business_profile, - merchant_connector_account, - )) - .await - .attach_printable("Incoming webhook flow for external authentication failed") - } - api::WebhookFlow::FraudCheck => Box::pin(frm_incoming_webhook_flow( + api::WebhookFlow::ExternalAuthentication => { + Box::pin(external_authentication_incoming_webhook_flow( state.clone(), req_state, - merchant_context, + merchant_context.clone(), source_verified, event_type, + request_details, + connector, object_ref_id, business_profile, + merchant_connector_account, )) .await - .attach_printable("Incoming webhook flow for fraud check failed"), - - #[cfg(feature = "payouts")] - api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow( - state.clone(), - merchant_context, - business_profile, - webhook_details, - event_type, - source_verified, - )) - .await - .attach_printable("Incoming webhook flow for payouts failed"), - - _ => Err(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unsupported Flow Type received in incoming webhooks"), + .attach_printable("Incoming webhook flow for external authentication failed") } - }; + api::WebhookFlow::FraudCheck => Box::pin(frm_incoming_webhook_flow( + state.clone(), + req_state, + merchant_context.clone(), + source_verified, + event_type, + object_ref_id, + business_profile, + )) + .await + .attach_printable("Incoming webhook flow for fraud check failed"), - match result_response { - Ok(response) => response, - Err(error) => { - return handle_incoming_webhook_error( - error, - &connector, - connector_name.as_str(), - &request_details, - ); - } + #[cfg(feature = "payouts")] + api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow( + state.clone(), + merchant_context.clone(), + business_profile, + webhook_details, + event_type, + source_verified, + )) + .await + .attach_printable("Incoming webhook flow for payouts failed"), + + _ => Err(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unsupported Flow Type received in incoming webhooks"), } - } else { - metrics::WEBHOOK_INCOMING_FILTERED_COUNT.add( - 1, - router_env::metric_attributes!(( - MERCHANT_ID, - merchant_context.get_merchant_account().get_id().clone() - )), - ); - WebhookResponseTracker::NoEffect }; - let response = connector - .get_webhook_api_response(&request_details, None) - .switch() - .attach_printable("Could not get incoming webhook api response from connector")?; - - let serialized_request = event_object - .masked_serialize() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Could not convert webhook effect to string")?; - Ok((response, webhook_effect, serialized_request)) + match result_response { + Ok(response) => Ok(response), + Err(error) => { + let result = + handle_incoming_webhook_error(error, connector, connector_name, request_details); + match result { + Ok((_, webhook_tracker, _)) => Ok(webhook_tracker), + Err(e) => Err(e), + } + } + } } fn handle_incoming_webhook_error( @@ -1346,7 +1530,7 @@ pub async fn get_or_update_dispute_object( Some(dispute) => { logger::info!("Dispute Already exists, Updating the dispute details"); metrics::INCOMING_DISPUTE_WEBHOOK_UPDATE_RECORD_METRIC.add(1, &[]); - crate::core::utils::validate_dispute_stage_and_dispute_status( + core_utils::validate_dispute_stage_and_dispute_status( dispute.dispute_stage, dispute.dispute_status, dispute_details.dispute_stage, @@ -1354,7 +1538,6 @@ pub async fn get_or_update_dispute_object( ) .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("dispute stage and status validation failed")?; - let update_dispute = diesel_models::dispute::DisputeUpdate::Update { dispute_stage: dispute_details.dispute_stage, dispute_status,
2025-08-01T07:07:02Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Added webhooks integration support in hyperswitch so that for webhooks hyperswitch can call UCS and get the response. Closes #8880 ### 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? ``` curl --location 'http://localhost:8080/webhooks/merchant_1753974582/mca_lwqSM0js79MQm1DGwYRj' \ --header 'Content-Type: application/json' \ --header 'X-ANET-Signature: sha512=38b0bc1ea66b14793e39cd58e93d37b799a507442d0dd8d37443fa95dec58e57da6db4742636fea31201c48e57a66e73a308a2e5a5c6bb831e4e39fe2227c00f' \ --header 'api-key: dev_gkgtNkEyXov857WXSuWWiduf9a2PnTLd78j7ZVUheZ86M7nroCye8G3BEgqcL5SH' \ --data '{ "notificationId": "550e8400-e29b-41d4-a716-446655440000", "eventType": "net.authorize.payment.authorization.created", "eventDate": "2023-12-01T12:00:00Z", "webhookId": "webhook_123", "payload": { "responseCode": 1, "entityName": "transaction", "id": "120068558980", "authAmount": 6540, "merchantReferenceId": "REF123", "authCode": "ABC123", "messageText": "This transaction has been approved.", "avsResponse": "Y", "cvvResponse": "M" } }' ``` ## 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 img of hyperswitch <img width="1727" height="1045" alt="Screenshot 2025-08-07 at 9 32 55β€―AM" src="https://github.com/user-attachments/assets/b22707ae-027c-4f5f-8552-1a82372d8bed" /> img of UCS <img width="1728" height="1044" alt="Screenshot 2025-08-07 at 9 30 58β€―AM" src="https://github.com/user-attachments/assets/e5324ec7-0228-4963-ba24-dac2238c4068" /> Steps to test webhooks βœ… 1. Create a Sandbox Account on Authorize.Net Go to: https://developer.authorize.net/hello_world/sandbox/ Sign up for a sandbox account. After registration, note your: API Login ID Transaction Key (Optional: Public Client Key if needed) βœ… 2. Generate the Signature Key Log in to the Authorize.Net Sandbox Navigate to: Account β†’ Settings β†’ API Credentials & Keys Under Signature Key, click New Signature Key β†’ click Submit Copy and save the Signature Key safely β€” you’ll use it to verify webhooks. βœ… 3. Enable Webhooks in Authorize.Net In your sandbox account, go to: Account β†’ Settings β†’ Webhooks Click Add Endpoint Endpoint URL: https://f9475498739857e.ngrok-free.app/webhooks/merchant_id/mca_of_merchant Event Types: Select the events you want (e.g., net.authorize.payment.authcapture.created) Save the webhook. βœ… 4. Configure Hyperswitch Merchant with Signature & Credentials While creating a merchant in Hyperswitch, add the following: authentication creds BodyKey api_key = API Login ID (from step 1) key1 = Transaction Key and below you file find a field named merchant secret where you will put the signature Signature Key (from step 2) This allows Hyperswitch to authenticate with Authorize.Net and validate incoming webhooks. βœ… 5. Trigger a Payment to Receive Webhooks Use Hyperswitch to make a test payment through the merchant you configured. If everything is set up: Authorize.Net will send a webhook to your endpoint (ngrok URL). Your backend should receive and verify the webhook using the signature key. βœ… Optional: Use ngrok to Test Webhooks Locally If running locally: `ngrok http 8080` Use the https://xxxx.ngrok-free.app URL as the webhook URL in step 3.
v1.115.0
8bbb76840bb5b560b0e4d0f98c5fd5530dc11cef
8bbb76840bb5b560b0e4d0f98c5fd5530dc11cef
juspay/hyperswitch
juspay__hyperswitch-8870
Bug: Retry Limit Tracking for Payment Processor Tokens in Revenue Recovery ## Background In the current **revenue recovery flow**, there is **no mapping between a customer and their payment methods**. However, card networks enforce **retry limits** β€” both daily and rolling 30-day β€” for each merchant–customer card combination. Without a centralized retry counter: - We risk exceeding network retry thresholds - Decline rates can increase - Merchant compliance issues may arise --- ## Problem Statement We need a way to: 1. **Group multiple cards** belonging to the same customer under a shared `connector_customer_id` 2. **Track retries per token** for both daily and rolling 30-day windows 3. **Enforce retry limits** before selecting a token for retry
diff --git a/config/config.example.toml b/config/config.example.toml index 00f7ba33a59..eb976ce8a39 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -1179,6 +1179,24 @@ billing_connectors_which_requires_invoice_sync_call = "recurly" # List of billin [revenue_recovery] monitoring_threshold_in_seconds = 60 # 60 secs , threshold for monitoring the retry system retry_algorithm_type = "cascading" # type of retry algorithm +redis_ttl_in_seconds=3888000 # ttl for redis for storing payment processor token details + +# Card specific configuration for Revenue Recovery +[revenue_recovery.card_config.amex] +max_retries_per_day = 20 +max_retry_count_for_thirty_day = 20 + +[revenue_recovery.card_config.mastercard] +max_retries_per_day = 10 +max_retry_count_for_thirty_day = 35 + +[revenue_recovery.card_config.visa] +max_retries_per_day = 20 +max_retry_count_for_thirty_day = 20 + +[revenue_recovery.card_config.discover] +max_retries_per_day = 20 +max_retry_count_for_thirty_day = 20 [revenue_recovery.recovery_timestamp] # Timestamp configuration for Revenue Recovery initial_timestamp_in_hours = 1 # number of hours added to start time for Decider service of Revenue Recovery diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 64db7079f40..40868da8f3f 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -386,6 +386,29 @@ base_url = "http://localhost:8000" # Unified Connector Service Base URL connection_timeout = 10 # Connection Timeout Duration in Seconds ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only +[revenue_recovery] +# monitoring threshold - 120 days +monitoring_threshold_in_seconds = 10368000 +retry_algorithm_type = "cascading" +redis_ttl_in_seconds=3888000 + +# Card specific configuration for Revenue Recovery +[revenue_recovery.card_config.amex] +max_retries_per_day = 20 +max_retry_count_for_thirty_day = 20 + +[revenue_recovery.card_config.mastercard] +max_retries_per_day = 10 +max_retry_count_for_thirty_day = 35 + +[revenue_recovery.card_config.visa] +max_retries_per_day = 20 +max_retry_count_for_thirty_day = 20 + +[revenue_recovery.card_config.discover] +max_retries_per_day = 20 +max_retry_count_for_thirty_day = 20 + [revenue_recovery.recovery_timestamp] # Timestamp configuration for Revenue Recovery initial_timestamp_in_hours = 1 # number of hours added to start time for Decider service of Revenue Recovery diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 40a0bdb137e..7ebb3e1079d 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -850,11 +850,6 @@ billing_connectors_which_require_payment_sync = "stripebilling, recurly" [billing_connectors_invoice_sync] billing_connectors_which_requires_invoice_sync_call = "recurly" - -[revenue_recovery] -monitoring_threshold_in_seconds = 60 -retry_algorithm_type = "cascading" - [authentication_providers] click_to_pay = {connector_list = "adyen, cybersource, trustpay"} diff --git a/config/deployments/production.toml b/config/deployments/production.toml index c4c37289fa1..3cb914fdcdb 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -865,10 +865,6 @@ billing_connectors_which_requires_invoice_sync_call = "recurly" [authentication_providers] click_to_pay = {connector_list = "adyen, cybersource, trustpay"} - -[revenue_recovery] -monitoring_threshold_in_seconds = 60 -retry_algorithm_type = "cascading" - [grpc_client.unified_connector_service] ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS only + diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 171b4bf0987..b91df6cf2b4 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -872,10 +872,6 @@ billing_connectors_which_requires_invoice_sync_call = "recurly" [authentication_providers] click_to_pay = {connector_list = "adyen, cybersource, trustpay"} -[revenue_recovery] -monitoring_threshold_in_seconds = 60 -retry_algorithm_type = "cascading" - [list_dispute_supported_connectors] connector_list = "worldpayvantiv" diff --git a/config/development.toml b/config/development.toml index a2d06e7d28e..02a5dce3be5 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1295,10 +1295,27 @@ ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors t [revenue_recovery] monitoring_threshold_in_seconds = 60 retry_algorithm_type = "cascading" +redis_ttl_in_seconds=3888000 [revenue_recovery.recovery_timestamp] initial_timestamp_in_hours = 1 +[revenue_recovery.card_config.amex] +max_retries_per_day = 20 +max_retry_count_for_thirty_day = 20 + +[revenue_recovery.card_config.mastercard] +max_retries_per_day = 10 +max_retry_count_for_thirty_day = 35 + +[revenue_recovery.card_config.visa] +max_retries_per_day = 20 +max_retry_count_for_thirty_day = 20 + +[revenue_recovery.card_config.discover] +max_retries_per_day = 20 +max_retry_count_for_thirty_day = 20 + [clone_connector_allowlist] merchant_ids = "merchant_123, merchant_234" # Comma-separated list of allowed merchant IDs connector_names = "stripe, adyen" # Comma-separated list of allowed connector names diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 544caf4c9f2..c60a2b0374e 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -1197,6 +1197,24 @@ click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [revenue_recovery] monitoring_threshold_in_seconds = 60 # threshold for monitoring the retry system retry_algorithm_type = "cascading" # type of retry algorithm +redis_ttl_in_seconds=3888000 # ttl for redis for storing payment processor token details + +# Card specific configuration for Revenue Recovery +[revenue_recovery.card_config.amex] +max_retries_per_day = 20 +max_retry_count_for_thirty_day = 20 + +[revenue_recovery.card_config.mastercard] +max_retries_per_day = 10 +max_retry_count_for_thirty_day = 35 + +[revenue_recovery.card_config.visa] +max_retries_per_day = 20 +max_retry_count_for_thirty_day = 20 + +[revenue_recovery.card_config.discover] +max_retries_per_day = 20 +max_retry_count_for_thirty_day = 20 [clone_connector_allowlist] merchant_ids = "merchant_123, merchant_234" # Comma-separated list of allowed merchant IDs diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index b8bf2db6c3c..95f105c67b9 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -515,10 +515,26 @@ impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptD retry_count, invoice_next_billing_time, invoice_billing_started_at_time, - card_network: Some(payment_method_details.card.brand), - card_isin: Some(payment_method_details.card.iin), // This field is none because it is specific to stripebilling. charge_id: None, + // Need to populate these card info field + card_info: api_models::payments::AdditionalCardInfo { + card_network: Some(payment_method_details.card.brand), + card_isin: Some(payment_method_details.card.iin), + card_issuer: None, + card_type: None, + card_issuing_country: None, + bank_code: None, + last4: None, + card_extended_bin: None, + card_exp_month: None, + card_exp_year: None, + card_holder_name: None, + payment_checks: None, + authentication_data: None, + is_regulated: None, + signature_network: None, + }, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs index 42dfc3f86d8..7338500db80 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs @@ -204,10 +204,26 @@ impl payment_method_type: common_enums::PaymentMethod::from( item.response.payment_method.object, ), - card_network: Some(item.response.payment_method.card_type), - card_isin: Some(item.response.payment_method.first_six), // This none because this field is specific to stripebilling. charge_id: None, + // Need to populate these card info field + card_info: api_models::payments::AdditionalCardInfo { + card_network: Some(item.response.payment_method.card_type), + card_isin: Some(item.response.payment_method.first_six), + card_issuer: None, + card_type: None, + card_issuing_country: None, + bank_code: None, + last4: None, + card_extended_bin: None, + card_exp_month: None, + card_exp_year: None, + card_holder_name: None, + payment_checks: None, + authentication_data: None, + is_regulated: None, + signature_network: None, + }, }, ), ..item.data diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs index ffabab2ae95..a5e4610ffdb 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs @@ -560,12 +560,28 @@ impl payment_method_type: common_enums::PaymentMethod::from( charge_details.payment_method_details.type_of_payment_method, ), - card_network: Some(common_enums::CardNetwork::from( - charge_details.payment_method_details.card_details.network, - )), // Todo: Fetch Card issuer details. Generally in the other billing connector we are getting card_issuer using the card bin info. But stripe dosent provide any such details. We should find a way for stripe billing case - card_isin: None, charge_id: Some(charge_details.charge_id.clone()), + // Need to populate these card info field + card_info: api_models::payments::AdditionalCardInfo { + card_network: Some(common_enums::CardNetwork::from( + charge_details.payment_method_details.card_details.network, + )), + card_isin: None, + card_issuer: None, + card_type: None, + card_issuing_country: None, + bank_code: None, + last4: None, + card_extended_bin: None, + card_exp_month: None, + card_exp_year: None, + card_holder_name: None, + payment_checks: None, + authentication_data: None, + is_regulated: None, + signature_network: None, + }, }, ), ..item.data diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 36eece964f9..0a63c036780 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -752,10 +752,25 @@ impl PaymentIntent { retry_count: None, invoice_next_billing_time: None, invoice_billing_started_at_time: None, - card_isin: None, - card_network: None, // No charge id is present here since it is an internal payment and we didn't call connector yet. charge_id: None, + card_info: api_models::payments::AdditionalCardInfo { + card_issuer: None, + card_network: None, + card_type: None, + card_issuing_country: None, + bank_code: None, + last4: None, + card_isin: None, + card_extended_bin: None, + card_exp_month: None, + card_exp_year: None, + card_holder_name: None, + payment_checks: None, + authentication_data: None, + is_regulated: None, + signature_network: None, + }, }) } diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs index fd36c4420f1..094905b1baf 100644 --- a/crates/hyperswitch_domain_models/src/revenue_recovery.rs +++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs @@ -54,12 +54,10 @@ pub struct RevenueRecoveryAttemptData { pub invoice_next_billing_time: Option<PrimitiveDateTime>, /// Time at which the invoice created pub invoice_billing_started_at_time: Option<PrimitiveDateTime>, - /// card network type - pub card_network: Option<common_enums::CardNetwork>, - /// card isin - pub card_isin: Option<String>, /// stripe specific id used to validate duplicate attempts in revenue recovery flow pub charge_id: Option<String>, + /// Additional card details + pub card_info: api_payments::AdditionalCardInfo, } /// This is unified struct for Revenue Recovery Invoice Data and it is constructed from billing connectors @@ -227,10 +225,9 @@ impl network_error_message: None, retry_count: invoice_details.retry_count, invoice_next_billing_time: invoice_details.next_billing_at, - card_network: billing_connector_payment_details.card_network.clone(), - card_isin: billing_connector_payment_details.card_isin.clone(), charge_id: billing_connector_payment_details.charge_id.clone(), invoice_billing_started_at_time: invoice_details.billing_started_at, + card_info: billing_connector_payment_details.card_info.clone(), } } } diff --git a/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs index 3df81e6b66d..65a62f62125 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs @@ -28,12 +28,10 @@ pub struct BillingConnectorPaymentsSyncResponse { pub payment_method_type: common_enums::enums::PaymentMethod, /// payment method sub type of the payment attempt. pub payment_method_sub_type: common_enums::enums::PaymentMethodType, - /// card netword network - pub card_network: Option<common_enums::CardNetwork>, - /// card isin - pub card_isin: Option<String>, /// stripe specific id used to validate duplicate attempts. pub charge_id: Option<String>, + /// card information + pub card_info: api_models::payments::AdditionalCardInfo, } #[derive(Debug, Clone)] diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index c8e7cb4e6f4..bc8397b416b 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -496,4 +496,6 @@ pub enum RevenueRecoveryError { RetryAlgorithmUpdationFailed, #[error("Failed to create the revenue recovery attempt data")] RevenueRecoveryAttemptDataCreateFailed, + #[error("Failed to insert the revenue recovery payment method data in redis")] + RevenueRecoveryRedisInsertFailed, } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 8a3594c310c..cdd552da14c 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -5508,7 +5508,10 @@ impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::PaymentA created_at: attempt.created_at, modified_at: attempt.modified_at, cancellation_reason: attempt.cancellation_reason.clone(), - payment_token: attempt.payment_token.clone(), + payment_token: attempt + .connector_token_details + .as_ref() + .and_then(|details| details.connector_mandate_id.clone()), connector_metadata: attempt.connector_metadata.clone(), payment_experience: attempt.payment_experience, payment_method_type: attempt.payment_method_type, diff --git a/crates/router/src/core/revenue_recovery/api.rs b/crates/router/src/core/revenue_recovery/api.rs index b8f912030c1..d942db48b4d 100644 --- a/crates/router/src/core/revenue_recovery/api.rs +++ b/crates/router/src/core/revenue_recovery/api.rs @@ -1,5 +1,5 @@ use actix_web::{web, Responder}; -use api_models::payments as payments_api; +use api_models::{payments as payments_api, payments as api_payments}; use common_utils::id_type; use error_stack::{report, FutureExt, ResultExt}; use hyperswitch_domain_models::{ diff --git a/crates/router/src/core/revenue_recovery/transformers.rs b/crates/router/src/core/revenue_recovery/transformers.rs index b282ac1e94c..f78d496a6ba 100644 --- a/crates/router/src/core/revenue_recovery/transformers.rs +++ b/crates/router/src/core/revenue_recovery/transformers.rs @@ -107,10 +107,25 @@ impl ForeignFrom<&api_models::payments::RecoveryPaymentsCreate> retry_count: None, invoice_next_billing_time: None, invoice_billing_started_at_time: data.billing_started_at, - card_network: card_info - .as_ref() - .and_then(|info| info.card_network.clone()), - card_isin: card_info.as_ref().and_then(|info| info.card_isin.clone()), + card_info: card_info + .cloned() + .unwrap_or(api_models::payments::AdditionalCardInfo { + card_issuer: None, + card_network: None, + card_type: None, + card_issuing_country: None, + bank_code: None, + last4: None, + card_isin: None, + card_extended_bin: None, + card_exp_month: None, + card_exp_year: None, + card_holder_name: None, + payment_checks: None, + authentication_data: None, + is_regulated: None, + signature_network: None, + }), charge_id: None, } } diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs index 32cb5552655..5f00dd0c5f2 100644 --- a/crates/router/src/core/webhooks/recovery_incoming.rs +++ b/crates/router/src/core/webhooks/recovery_incoming.rs @@ -1,4 +1,4 @@ -use std::{marker::PhantomData, str::FromStr}; +use std::{collections::HashMap, marker::PhantomData, str::FromStr}; use api_models::{enums as api_enums, payments as api_payments, webhooks}; use common_utils::{ @@ -30,11 +30,19 @@ use crate::{ connector_integration_interface::{self, RouterDataConversion}, }, types::{ - self, api, domain, storage::revenue_recovery as storage_churn_recovery, + self, api, domain, + storage::{ + revenue_recovery as storage_revenue_recovery, + revenue_recovery_redis_operation::{ + PaymentProcessorTokenDetails, PaymentProcessorTokenStatus, RedisTokenManager, + }, + }, transformers::ForeignFrom, }, workflows::revenue_recovery as revenue_recovery_flow, }; +#[cfg(feature = "v2")] +pub const REVENUE_RECOVERY: &str = "revenue_recovery"; #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] @@ -617,14 +625,15 @@ impl RevenueRecoveryAttempt { errors::RevenueRecoveryError, > { let payment_connector_id = payment_connector_account.as_ref().map(|account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount| account.id.clone()); + let payment_connector_name = payment_connector_account + .as_ref() + .map(|account| account.connector_name); let request_payload: api_payments::PaymentsAttemptRecordRequest = self .create_payment_record_request( state, billing_connector_account_id, payment_connector_id, - payment_connector_account - .as_ref() - .map(|account| account.connector_name), + payment_connector_name, common_enums::TriggeredBy::External, ) .await?; @@ -685,6 +694,16 @@ impl RevenueRecoveryAttempt { let response = (recovery_attempt, updated_recovery_intent); + self.store_payment_processor_tokens_in_redis(state, &response.0, payment_connector_name) + .await + .map_err(|e| { + router_env::logger::error!( + "Failed to store payment processor tokens in Redis: {:?}", + e + ); + errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed + })?; + Ok(response) } @@ -709,6 +728,7 @@ impl RevenueRecoveryAttempt { }; let card_info = revenue_recovery_attempt_data + .card_info .card_isin .clone() .async_and_then(|isin| async move { @@ -755,7 +775,7 @@ impl RevenueRecoveryAttempt { invoice_billing_started_at_time: revenue_recovery_attempt_data .invoice_billing_started_at_time, triggered_by, - card_network: revenue_recovery_attempt_data.card_network.clone(), + card_network: revenue_recovery_attempt_data.card_info.card_network.clone(), card_issuer, }) } @@ -899,7 +919,7 @@ impl RevenueRecoveryAttempt { .attach_printable("payment attempt id is required for pcr workflow tracking")?; let execute_workflow_tracking_data = - storage_churn_recovery::RevenueRecoveryWorkflowTrackingData { + storage_revenue_recovery::RevenueRecoveryWorkflowTrackingData { billing_mca_id: billing_mca_id.clone(), global_payment_id: payment_id.clone(), merchant_id, @@ -934,6 +954,77 @@ impl RevenueRecoveryAttempt { status: payment_intent.status, }) } + + /// Store payment processor tokens in Redis for retry management + async fn store_payment_processor_tokens_in_redis( + &self, + state: &SessionState, + recovery_attempt: &revenue_recovery::RecoveryPaymentAttempt, + payment_connector_name: Option<common_enums::connector_enums::Connector>, + ) -> CustomResult<(), errors::RevenueRecoveryError> { + let revenue_recovery_attempt_data = &self.0; + let error_code = revenue_recovery_attempt_data.error_code.clone(); + let error_message = revenue_recovery_attempt_data.error_message.clone(); + let connector_name = payment_connector_name + .ok_or(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed) + .attach_printable("unable to derive payment connector")? + .to_string(); + + let gsm_record = helpers::get_gsm_record( + state, + error_code.clone(), + error_message, + connector_name, + REVENUE_RECOVERY.to_string(), + ) + .await; + + let is_hard_decline = gsm_record + .and_then(|record| record.error_category) + .map(|category| category == common_enums::ErrorCategory::HardDecline) + .unwrap_or(false); + + // Extract required fields from the revenue recovery attempt data + let connector_customer_id = revenue_recovery_attempt_data.connector_customer_id.clone(); + + let attempt_id = recovery_attempt.attempt_id.clone(); + let token_unit = PaymentProcessorTokenStatus { + error_code, + inserted_by_attempt_id: attempt_id.clone(), + daily_retry_history: HashMap::from([(recovery_attempt.created_at.date(), 1)]), + scheduled_at: None, + is_hard_decline: Some(is_hard_decline), + payment_processor_token_details: PaymentProcessorTokenDetails { + payment_processor_token: revenue_recovery_attempt_data + .processor_payment_method_token + .clone(), + expiry_month: revenue_recovery_attempt_data + .card_info + .card_exp_month + .clone(), + expiry_year: revenue_recovery_attempt_data + .card_info + .card_exp_year + .clone(), + card_issuer: revenue_recovery_attempt_data.card_info.card_issuer.clone(), + last_four_digits: revenue_recovery_attempt_data.card_info.last4.clone(), + card_network: revenue_recovery_attempt_data.card_info.card_network.clone(), + card_type: revenue_recovery_attempt_data.card_info.card_type.clone(), + }, + }; + + // Make the Redis call to store tokens + RedisTokenManager::upsert_payment_processor_token( + state, + &connector_customer_id, + token_unit, + ) + .await + .change_context(errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed) + .attach_printable("Failed to store payment processor tokens in Redis")?; + + Ok(()) + } } pub struct BillingConnectorPaymentsSyncResponseData( diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 341f9327f75..70a0a344150 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -36,6 +36,8 @@ pub mod payouts; pub mod refund; #[cfg(feature = "v2")] pub mod revenue_recovery; +#[cfg(feature = "v2")] +pub mod revenue_recovery_redis_operation; pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rs index 1c1a076fd01..81a012ba414 100644 --- a/crates/router/src/types/storage/revenue_recovery.rs +++ b/crates/router/src/types/storage/revenue_recovery.rs @@ -1,7 +1,8 @@ -use std::fmt::Debug; +use std::{collections::HashMap, fmt::Debug}; -use common_enums::enums; +use common_enums::enums::{self, CardNetwork}; use common_utils::{date_time, ext_traits::ValueExt, id_type}; +use error_stack::ResultExt; use external_services::grpc_client::{self as external_grpc_client, GrpcHeaders}; use hyperswitch_domain_models::{ business_profile, merchant_account, merchant_connector_account, merchant_key_store, @@ -10,6 +11,7 @@ use hyperswitch_domain_models::{ }; use masking::PeekInterface; use router_env::logger; +use serde::{Deserialize, Serialize}; use crate::{db::StorageInterface, routes::SessionState, workflows::revenue_recovery}; #[derive(serde::Serialize, serde::Deserialize, Debug)] @@ -53,20 +55,7 @@ impl RevenueRecoveryPaymentData { ) .await } - enums::RevenueRecoveryAlgorithmType::Smart => { - if is_hard_decline { - None - } else { - // TODO: Integrate the smart retry call to return back a schedule time - revenue_recovery::get_schedule_time_for_smart_retry( - state, - payment_attempt, - payment_intent, - retry_count, - ) - .await - } - } + enums::RevenueRecoveryAlgorithmType::Smart => None, } } } @@ -76,6 +65,8 @@ pub struct RevenueRecoverySettings { pub monitoring_threshold_in_seconds: i64, pub retry_algorithm_type: enums::RevenueRecoveryAlgorithmType, pub recovery_timestamp: RecoveryTimestamp, + pub card_config: RetryLimitsConfig, + pub redis_ttl_in_seconds: i64, } #[derive(Debug, serde::Deserialize, Clone)] @@ -90,3 +81,28 @@ impl Default for RecoveryTimestamp { } } } + +#[derive(Debug, serde::Deserialize, Clone, Default)] +pub struct RetryLimitsConfig(pub HashMap<CardNetwork, NetworkRetryConfig>); + +#[derive(Debug, serde::Deserialize, Clone, Default)] +pub struct NetworkRetryConfig { + pub max_retries_per_day: i32, + pub max_retry_count_for_thirty_day: i32, +} + +impl RetryLimitsConfig { + pub fn get_network_config(&self, network: Option<CardNetwork>) -> &NetworkRetryConfig { + // Hardcoded fallback default config + static DEFAULT_CONFIG: NetworkRetryConfig = NetworkRetryConfig { + max_retries_per_day: 20, + max_retry_count_for_thirty_day: 20, + }; + + if let Some(net) = network { + self.0.get(&net).unwrap_or(&DEFAULT_CONFIG) + } else { + self.0.get(&CardNetwork::Visa).unwrap_or(&DEFAULT_CONFIG) + } + } +} diff --git a/crates/router/src/types/storage/revenue_recovery_redis_operation.rs b/crates/router/src/types/storage/revenue_recovery_redis_operation.rs new file mode 100644 index 00000000000..433de9c2b36 --- /dev/null +++ b/crates/router/src/types/storage/revenue_recovery_redis_operation.rs @@ -0,0 +1,655 @@ +use std::collections::HashMap; + +use common_enums::enums::CardNetwork; +use common_utils::{date_time, errors::CustomResult, id_type}; +use error_stack::ResultExt; +use masking::Secret; +use redis_interface::{DelReply, SetnxReply}; +use router_env::{instrument, tracing}; +use serde::{Deserialize, Serialize}; +use time::{Date, Duration, OffsetDateTime, PrimitiveDateTime}; + +use crate::{db::errors, SessionState}; + +// Constants for retry window management +const RETRY_WINDOW_DAYS: i32 = 30; +const INITIAL_RETRY_COUNT: i32 = 0; + +/// Payment processor token details including card information +#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] +pub struct PaymentProcessorTokenDetails { + pub payment_processor_token: String, + pub expiry_month: Option<Secret<String>>, + pub expiry_year: Option<Secret<String>>, + pub card_issuer: Option<String>, + pub last_four_digits: Option<String>, + pub card_network: Option<CardNetwork>, + pub card_type: Option<String>, +} + +/// Represents the status and retry history of a payment processor token +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PaymentProcessorTokenStatus { + /// Payment processor token details including card information and token ID + pub payment_processor_token_details: PaymentProcessorTokenDetails, + /// Payment intent ID that originally inserted this token + pub inserted_by_attempt_id: id_type::GlobalAttemptId, + /// Error code associated with the token failure + pub error_code: Option<String>, + /// Daily retry count history for the last 30 days (date -> retry_count) + pub daily_retry_history: HashMap<Date, i32>, + /// Scheduled time for the next retry attempt + pub scheduled_at: Option<PrimitiveDateTime>, + /// Indicates if the token is a hard decline (no retries allowed) + pub is_hard_decline: Option<bool>, +} + +/// Token retry availability information with detailed wait times +#[derive(Debug, Clone)] +pub struct TokenRetryInfo { + pub monthly_wait_hours: i64, // Hours to wait for 30-day limit reset + pub daily_wait_hours: i64, // Hours to wait for daily limit reset + pub total_30_day_retries: i32, // Current total retry count in 30-day window +} + +/// Complete token information with retry limits and wait times +#[derive(Debug, Clone)] +pub struct PaymentProcessorTokenWithRetryInfo { + /// The complete token status information + pub token_status: PaymentProcessorTokenStatus, + /// Hours to wait before next retry attempt (max of daily/monthly wait) + pub retry_wait_time_hours: i64, + /// Number of retries remaining in the 30-day rolling window + pub monthly_retry_remaining: i32, +} + +/// Redis-based token management struct +pub struct RedisTokenManager; + +impl RedisTokenManager { + /// Lock connector customer + #[instrument(skip_all)] + pub async fn lock_connector_customer_status( + state: &SessionState, + connector_customer_id: &str, + payment_id: &id_type::GlobalPaymentId, + ) -> CustomResult<bool, errors::StorageError> { + let redis_conn = + state + .store + .get_redis_conn() + .change_context(errors::StorageError::RedisError( + errors::RedisError::RedisConnectionError.into(), + ))?; + + let lock_key = format!("customer:{connector_customer_id}:status"); + let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds; + + let result: bool = match redis_conn + .set_key_if_not_exists_with_expiry( + &lock_key.into(), + payment_id.get_string_repr(), + Some(*seconds), + ) + .await + { + Ok(resp) => resp == SetnxReply::KeySet, + Err(error) => { + tracing::error!(operation = "lock_stream", err = ?error); + false + } + }; + + tracing::debug!( + connector_customer_id = connector_customer_id, + payment_id = payment_id.get_string_repr(), + lock_acquired = %result, + "Connector customer lock attempt" + ); + + Ok(result) + } + + /// Unlock connector customer status + #[instrument(skip_all)] + pub async fn unlock_connector_customer_status( + state: &SessionState, + connector_customer_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + let redis_conn = + state + .store + .get_redis_conn() + .change_context(errors::StorageError::RedisError( + errors::RedisError::RedisConnectionError.into(), + ))?; + + let lock_key = format!("customer:{connector_customer_id}:status"); + + match redis_conn.delete_key(&lock_key.into()).await { + Ok(DelReply::KeyDeleted) => { + tracing::debug!( + connector_customer_id = connector_customer_id, + "Connector customer unlocked" + ); + Ok(true) + } + Ok(DelReply::KeyNotDeleted) => { + tracing::debug!("Tried to unlock a stream which is already unlocked"); + Ok(false) + } + Err(err) => { + tracing::error!(?err, "Failed to delete lock key"); + Ok(false) + } + } + } + + /// Get all payment processor tokens for a connector customer + #[instrument(skip_all)] + pub async fn get_connector_customer_payment_processor_tokens( + state: &SessionState, + connector_customer_id: &str, + ) -> CustomResult<HashMap<String, PaymentProcessorTokenStatus>, errors::StorageError> { + let redis_conn = + state + .store + .get_redis_conn() + .change_context(errors::StorageError::RedisError( + errors::RedisError::RedisConnectionError.into(), + ))?; + let tokens_key = format!("customer:{connector_customer_id}:tokens"); + + let get_hash_err = + errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into()); + + let payment_processor_tokens: HashMap<String, String> = redis_conn + .get_hash_fields(&tokens_key.into()) + .await + .change_context(get_hash_err)?; + + // build the result map using iterator adapters (explicit match preserved for logging) + let payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus> = + payment_processor_tokens + .into_iter() + .filter_map(|(token_id, token_data)| { + match serde_json::from_str::<PaymentProcessorTokenStatus>(&token_data) { + Ok(token_status) => Some((token_id, token_status)), + Err(err) => { + tracing::warn!( + connector_customer_id = %connector_customer_id, + token_id = %token_id, + error = %err, + "Failed to deserialize token data, skipping", + ); + None + } + } + }) + .collect(); + tracing::debug!( + connector_customer_id = connector_customer_id, + "Fetched payment processor tokens", + ); + + Ok(payment_processor_token_info_map) + } + + /// Update connector customer payment processor tokens or add if doesn't exist + #[instrument(skip_all)] + pub async fn update_or_add_connector_customer_payment_processor_tokens( + state: &SessionState, + connector_customer_id: &str, + payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus>, + ) -> CustomResult<(), errors::StorageError> { + let redis_conn = + state + .store + .get_redis_conn() + .change_context(errors::StorageError::RedisError( + errors::RedisError::RedisConnectionError.into(), + ))?; + let tokens_key = format!("customer:{connector_customer_id}:tokens"); + + // allocate capacity up-front to avoid rehashing + let mut serialized_payment_processor_tokens: HashMap<String, String> = + HashMap::with_capacity(payment_processor_token_info_map.len()); + + // serialize all tokens, preserving explicit error handling and attachable diagnostics + for (payment_processor_token_id, payment_processor_token_status) in + payment_processor_token_info_map + { + let serialized = serde_json::to_string(&payment_processor_token_status) + .change_context(errors::StorageError::SerializationFailed) + .attach_printable("Failed to serialize token status")?; + + serialized_payment_processor_tokens.insert(payment_processor_token_id, serialized); + } + let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds; + + // Update or add tokens + redis_conn + .set_hash_fields( + &tokens_key.into(), + serialized_payment_processor_tokens, + Some(*seconds), + ) + .await + .change_context(errors::StorageError::RedisError( + errors::RedisError::SetHashFieldFailed.into(), + ))?; + + tracing::info!( + connector_customer_id = %connector_customer_id, + "Successfully updated or added customer tokens", + ); + + Ok(()) + } + + /// Get current date in `yyyy-mm-dd` format. + pub fn get_current_date() -> String { + let today = date_time::now().date(); + + let (year, month, day) = (today.year(), today.month(), today.day()); + + format!("{year:04}-{month:02}-{day:02}",) + } + + /// Normalize retry window to exactly `RETRY_WINDOW_DAYS` days (today to `RETRY_WINDOW_DAYS - 1` days ago). + pub fn normalize_retry_window( + payment_processor_token: &mut PaymentProcessorTokenStatus, + today: Date, + ) { + let mut normalized_retry_history: HashMap<Date, i32> = HashMap::new(); + + for days_ago in 0..RETRY_WINDOW_DAYS { + let date = today - Duration::days(days_ago.into()); + + payment_processor_token + .daily_retry_history + .get(&date) + .map(|&retry_count| { + normalized_retry_history.insert(date, retry_count); + }); + } + + payment_processor_token.daily_retry_history = normalized_retry_history; + } + + /// Get all payment processor tokens with retry information and wait times. + pub fn get_tokens_with_retry_metadata( + state: &SessionState, + payment_processor_token_info_map: &HashMap<String, PaymentProcessorTokenStatus>, + ) -> HashMap<String, PaymentProcessorTokenWithRetryInfo> { + let today = OffsetDateTime::now_utc().date(); + let card_config = &state.conf.revenue_recovery.card_config; + + let mut result: HashMap<String, PaymentProcessorTokenWithRetryInfo> = + HashMap::with_capacity(payment_processor_token_info_map.len()); + + for (payment_processor_token_id, payment_processor_token_status) in + payment_processor_token_info_map.iter() + { + let card_network = payment_processor_token_status + .payment_processor_token_details + .card_network + .clone(); + + // Calculate retry information. + let retry_info = Self::payment_processor_token_retry_info( + state, + payment_processor_token_status, + today, + card_network.clone(), + ); + + // Determine the wait time (max of monthly and daily wait hours). + let retry_wait_time_hours = retry_info + .monthly_wait_hours + .max(retry_info.daily_wait_hours); + + // Obtain network-specific limits and compute remaining monthly retries. + let card_network_config = card_config.get_network_config(card_network); + + let monthly_retry_remaining = card_network_config + .max_retry_count_for_thirty_day + .saturating_sub(retry_info.total_30_day_retries); + + // Build the per-token result struct. + let token_with_retry_info = PaymentProcessorTokenWithRetryInfo { + token_status: payment_processor_token_status.clone(), + retry_wait_time_hours, + monthly_retry_remaining, + }; + + result.insert(payment_processor_token_id.clone(), token_with_retry_info); + } + tracing::debug!("Fetched payment processor tokens with retry metadata",); + + result + } + + /// Sum retries over exactly the last 30 days + fn calculate_total_30_day_retries(token: &PaymentProcessorTokenStatus, today: Date) -> i32 { + (0..RETRY_WINDOW_DAYS) + .map(|i| { + let date = today - Duration::days(i.into()); + token + .daily_retry_history + .get(&date) + .copied() + .unwrap_or(INITIAL_RETRY_COUNT) + }) + .sum() + } + + /// Calculate wait hours + fn calculate_wait_hours(target_date: Date, now: OffsetDateTime) -> i64 { + let expiry_time = target_date.midnight().assume_utc(); + (expiry_time - now).whole_hours().max(0) + } + + /// Calculate retry counts for exactly the last 30 days + pub fn payment_processor_token_retry_info( + state: &SessionState, + token: &PaymentProcessorTokenStatus, + today: Date, + network_type: Option<CardNetwork>, + ) -> TokenRetryInfo { + let card_config = &state.conf.revenue_recovery.card_config; + let card_network_config = card_config.get_network_config(network_type); + + let now = OffsetDateTime::now_utc(); + + let total_30_day_retries = Self::calculate_total_30_day_retries(token, today); + + let monthly_wait_hours = + if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day { + (0..RETRY_WINDOW_DAYS) + .map(|i| today - Duration::days(i.into())) + .find(|date| token.daily_retry_history.get(date).copied().unwrap_or(0) > 0) + .map(|date| Self::calculate_wait_hours(date + Duration::days(31), now)) + .unwrap_or(0) + } else { + 0 + }; + + let today_retries = token + .daily_retry_history + .get(&today) + .copied() + .unwrap_or(INITIAL_RETRY_COUNT); + + let daily_wait_hours = if today_retries >= card_network_config.max_retries_per_day { + Self::calculate_wait_hours(today + Duration::days(1), now) + } else { + 0 + }; + + TokenRetryInfo { + monthly_wait_hours, + daily_wait_hours, + total_30_day_retries, + } + } + + // Upsert payment processor token + #[instrument(skip_all)] + pub async fn upsert_payment_processor_token( + state: &SessionState, + connector_customer_id: &str, + token_data: PaymentProcessorTokenStatus, + ) -> CustomResult<bool, errors::StorageError> { + let mut token_map = + Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id) + .await?; + + let token_id = token_data + .payment_processor_token_details + .payment_processor_token + .clone(); + + let was_existing = token_map.contains_key(&token_id); + + let error_code = token_data.error_code.clone(); + let today = OffsetDateTime::now_utc().date(); + + token_map + .get_mut(&token_id) + .map(|existing_token| { + error_code.map(|err| existing_token.error_code = Some(err)); + + Self::normalize_retry_window(existing_token, today); + + for (date, &value) in &token_data.daily_retry_history { + existing_token + .daily_retry_history + .entry(*date) + .and_modify(|v| *v += value) + .or_insert(value); + } + }) + .or_else(|| { + token_map.insert(token_id.clone(), token_data); + None + }); + + Self::update_or_add_connector_customer_payment_processor_tokens( + state, + connector_customer_id, + token_map, + ) + .await?; + tracing::debug!( + connector_customer_id = connector_customer_id, + "Upsert payment processor tokens", + ); + + Ok(!was_existing) + } + + // Update payment processor token error code with billing connector response + #[instrument(skip_all)] + pub async fn update_payment_processor_token_error_code_from_process_tracker( + state: &SessionState, + connector_customer_id: &str, + error_code: &Option<String>, + is_hard_decline: &Option<bool>, + ) -> CustomResult<bool, errors::StorageError> { + let today = OffsetDateTime::now_utc().date(); + let updated_token = + Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id) + .await? + .values() + .find(|status| status.scheduled_at.is_some()) + .map(|status| PaymentProcessorTokenStatus { + payment_processor_token_details: status.payment_processor_token_details.clone(), + inserted_by_attempt_id: status.inserted_by_attempt_id.clone(), + error_code: error_code.clone(), + daily_retry_history: status.daily_retry_history.clone(), + scheduled_at: None, + is_hard_decline: *is_hard_decline, + }); + + match updated_token { + Some(mut token) => { + Self::normalize_retry_window(&mut token, today); + + match token.error_code { + None => token.daily_retry_history.clear(), + Some(_) => { + let current_count = token + .daily_retry_history + .get(&today) + .copied() + .unwrap_or(INITIAL_RETRY_COUNT); + token.daily_retry_history.insert(today, current_count + 1); + } + } + + let mut tokens_map = HashMap::new(); + tokens_map.insert( + token + .payment_processor_token_details + .payment_processor_token + .clone(), + token.clone(), + ); + + Self::update_or_add_connector_customer_payment_processor_tokens( + state, + connector_customer_id, + tokens_map, + ) + .await?; + tracing::debug!( + connector_customer_id = connector_customer_id, + "Updated payment processor tokens with error code", + ); + Ok(true) + } + None => { + tracing::debug!( + connector_customer_id = connector_customer_id, + "No Token found with scheduled time to update error code", + ); + Ok(false) + } + } + } + + // Update payment processor token schedule time + #[instrument(skip_all)] + pub async fn update_payment_processor_token_schedule_time( + state: &SessionState, + connector_customer_id: &str, + payment_processor_token: &str, + schedule_time: Option<PrimitiveDateTime>, + ) -> CustomResult<bool, errors::StorageError> { + let updated_token = + Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id) + .await? + .values() + .find(|status| { + status + .payment_processor_token_details + .payment_processor_token + == payment_processor_token + }) + .map(|status| PaymentProcessorTokenStatus { + payment_processor_token_details: status.payment_processor_token_details.clone(), + inserted_by_attempt_id: status.inserted_by_attempt_id.clone(), + error_code: status.error_code.clone(), + daily_retry_history: status.daily_retry_history.clone(), + scheduled_at: schedule_time, + is_hard_decline: status.is_hard_decline, + }); + + match updated_token { + Some(token) => { + let mut tokens_map = HashMap::new(); + tokens_map.insert( + token + .payment_processor_token_details + .payment_processor_token + .clone(), + token.clone(), + ); + Self::update_or_add_connector_customer_payment_processor_tokens( + state, + connector_customer_id, + tokens_map, + ) + .await?; + tracing::debug!( + connector_customer_id = connector_customer_id, + "Updated payment processor tokens with schedule time", + ); + Ok(true) + } + None => { + tracing::debug!( + connector_customer_id = connector_customer_id, + "payment processor tokens with not found", + ); + Ok(false) + } + } + } + + // Get payment processor token with schedule time + #[instrument(skip_all)] + pub async fn get_payment_processor_token_with_schedule_time( + state: &SessionState, + connector_customer_id: &str, + ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> { + let tokens = + Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id) + .await?; + + let scheduled_token = tokens + .values() + .find(|status| status.scheduled_at.is_some()) + .cloned(); + + tracing::debug!( + connector_customer_id = connector_customer_id, + "Fetched payment processor token with schedule time", + ); + + Ok(scheduled_token) + } + + // Get payment processor token with max retry remaining for cascading retry algorithm + #[instrument(skip_all)] + pub async fn get_token_with_max_retry_remaining( + state: &SessionState, + connector_customer_id: &str, + ) -> CustomResult<Option<PaymentProcessorTokenWithRetryInfo>, errors::StorageError> { + // Get all tokens for the customer + let tokens_map = + Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id) + .await?; + + // Tokens with retry metadata + let tokens_with_retry = Self::get_tokens_with_retry_metadata(state, &tokens_map); + + // Find the token with max retry remaining + let max_retry_token = tokens_with_retry + .into_iter() + .filter(|(_, token_info)| !token_info.token_status.is_hard_decline.unwrap_or(false)) + .max_by_key(|(_, token_info)| token_info.monthly_retry_remaining) + .map(|(_, token_info)| token_info); + + tracing::debug!( + connector_customer_id = connector_customer_id, + "Fetched payment processor token with max retry remaining", + ); + + Ok(max_retry_token) + } + + // Check if all tokens are hard declined or no token found for the customer + #[instrument(skip_all)] + pub async fn are_all_tokens_hard_declined( + state: &SessionState, + connector_customer_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + let tokens_map = + Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id) + .await?; + let all_hard_declined = tokens_map.is_empty() + && tokens_map + .values() + .all(|token| token.is_hard_decline.unwrap_or(false)); + + tracing::debug!( + connector_customer_id = connector_customer_id, + all_hard_declined, + "Checked if all tokens are hard declined or no token found for the customer", + ); + + Ok(all_hard_declined) + } +} diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rs index c962aeb68e5..8f3b3f0e009 100644 --- a/crates/router/src/workflows/revenue_recovery.rs +++ b/crates/router/src/workflows/revenue_recovery.rs @@ -1,14 +1,19 @@ #[cfg(feature = "v2")] -use api_models::payments::PaymentsGetIntentRequest; +use std::collections::HashMap; + +#[cfg(feature = "v2")] +use api_models::{enums::RevenueRecoveryAlgorithmType, payments::PaymentsGetIntentRequest}; #[cfg(feature = "v2")] use common_utils::{ + errors::CustomResult, + ext_traits::AsyncExt, ext_traits::{StringExt, ValueExt}, id_type, }; #[cfg(feature = "v2")] use diesel_models::types::BillingConnectorPaymentMethodDetails; #[cfg(feature = "v2")] -use error_stack::ResultExt; +use error_stack::{Report, ResultExt}; #[cfg(all(feature = "revenue_recovery", feature = "v2"))] use external_services::{ date_time, grpc_client::revenue_recovery::recovery_decider_client as external_grpc_client, @@ -16,21 +21,37 @@ use external_services::{ #[cfg(feature = "v2")] use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, - payments::{ - payment_attempt::PaymentAttempt, PaymentConfirmData, PaymentIntent, PaymentIntentData, - }, + payments::{payment_attempt, PaymentConfirmData, PaymentIntent, PaymentIntentData}, + router_flow_types, router_flow_types::Authorize, }; #[cfg(feature = "v2")] use masking::{ExposeInterface, PeekInterface, Secret}; #[cfg(feature = "v2")] -use router_env::logger; +use router_env::{logger, tracing}; use scheduler::{consumer::workflows::ProcessTrackerWorkflow, errors}; #[cfg(feature = "v2")] use scheduler::{types::process_data, utils as scheduler_utils}; #[cfg(feature = "v2")] use storage_impl::errors as storage_errors; +#[cfg(feature = "v2")] +use time::Date; +#[cfg(feature = "v2")] +use crate::core::payments::operations; +#[cfg(feature = "v2")] +use crate::routes::app::ReqState; +#[cfg(feature = "v2")] +use crate::services; +#[cfg(feature = "v2")] +use crate::types::storage::{ + revenue_recovery::RetryLimitsConfig, + revenue_recovery_redis_operation::{ + PaymentProcessorTokenStatus, PaymentProcessorTokenWithRetryInfo, RedisTokenManager, + }, +}; +#[cfg(feature = "v2")] +use crate::workflows::revenue_recovery::pcr::api; #[cfg(feature = "v2")] use crate::{ core::{ @@ -42,11 +63,16 @@ use crate::{ types::{ api::{self as api_types}, domain, - storage::revenue_recovery as pcr_storage_types, + storage::{ + revenue_recovery as pcr_storage_types, + revenue_recovery_redis_operation::PaymentProcessorTokenDetails, + }, }, }; use crate::{routes::SessionState, types::storage}; pub struct ExecutePcrWorkflow; +#[cfg(feature = "v2")] +pub const REVENUE_RECOVERY: &str = "revenue_recovery"; #[async_trait::async_trait] impl ProcessTrackerWorkflow<SessionState> for ExecutePcrWorkflow { @@ -218,21 +244,21 @@ pub(crate) async fn get_schedule_time_to_retry_mit_payments( #[cfg(feature = "v2")] pub(crate) async fn get_schedule_time_for_smart_retry( state: &SessionState, - payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, - retry_count: i32, -) -> Option<time::PrimitiveDateTime> { - let first_error_message = match payment_attempt.error.as_ref() { - Some(error) => error.message.clone(), - None => { - logger::error!( - payment_intent_id = ?payment_intent.get_id(), - attempt_id = ?payment_attempt.get_id(), - "Payment attempt error information not found - cannot proceed with smart retry" - ); - return None; - } - }; + retry_after_time: Option<prost_types::Timestamp>, + token_with_retry_info: &PaymentProcessorTokenWithRetryInfo, +) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { + let card_config = &state.conf.revenue_recovery.card_config; + + // Not populating it right now + let first_error_message = "None".to_string(); + let retry_count_left = token_with_retry_info.monthly_retry_remaining; + let pg_error_code = token_with_retry_info.token_status.error_code.clone(); + + let card_info = token_with_retry_info + .token_status + .payment_processor_token_details + .clone(); let billing_state = payment_intent .billing_address @@ -241,54 +267,19 @@ pub(crate) async fn get_schedule_time_for_smart_retry( .and_then(|details| details.state.as_ref()) .cloned(); - // Check if payment_method_data itself is None - if payment_attempt.payment_method_data.is_none() { - logger::debug!( - payment_intent_id = ?payment_intent.get_id(), - attempt_id = ?payment_attempt.get_id(), - message = "payment_attempt.payment_method_data is None" - ); - } - - let billing_connector_payment_method_details = payment_intent - .feature_metadata - .as_ref() - .and_then(|revenue_recovery_data| { - revenue_recovery_data - .payment_revenue_recovery_metadata - .as_ref() - }) - .and_then(|payment_metadata| { - payment_metadata - .billing_connector_payment_method_details - .as_ref() - }); - let revenue_recovery_metadata = payment_intent .feature_metadata .as_ref() .and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref()); - let card_network_str = billing_connector_payment_method_details - .and_then(|details| match details { - BillingConnectorPaymentMethodDetails::Card(card_info) => card_info.card_network.clone(), - }) - .map(|cn| cn.to_string()); + let card_network = card_info.card_network.clone(); + let total_retry_count_within_network = card_config.get_network_config(card_network.clone()); - let card_issuer_str = - billing_connector_payment_method_details.and_then(|details| match details { - BillingConnectorPaymentMethodDetails::Card(card_info) => card_info.card_issuer.clone(), - }); + let card_network_str = card_network.map(|network| network.to_string()); - let card_funding_str = payment_intent - .feature_metadata - .as_ref() - .and_then(|revenue_recovery_data| { - revenue_recovery_data - .payment_revenue_recovery_metadata - .as_ref() - }) - .map(|payment_metadata| payment_metadata.payment_method_subtype.to_string()); + let card_issuer_str = card_info.card_issuer.clone(); + + let card_funding_str = card_info.card_type.clone(); let start_time_primitive = payment_intent.created_at; let recovery_timestamp_config = &state.conf.revenue_recovery.recovery_timestamp; @@ -296,6 +287,7 @@ pub(crate) async fn get_schedule_time_for_smart_retry( let modified_start_time_primitive = start_time_primitive.saturating_add(time::Duration::hours( recovery_timestamp_config.initial_timestamp_in_hours, )); + let start_time_proto = date_time::convert_to_prost_timestamp(modified_start_time_primitive); let merchant_id = Some(payment_intent.merchant_id.get_string_repr().to_string()); @@ -321,33 +313,6 @@ pub(crate) async fn get_schedule_time_for_smart_retry( .and_then(|details| details.city.as_ref()) .cloned(); - let attempt_currency = Some(payment_intent.amount_details.currency.to_string()); - let attempt_status = Some(payment_attempt.status.to_string()); - let attempt_amount = Some( - payment_attempt - .amount_details - .get_net_amount() - .get_amount_as_i64(), - ); - let attempt_response_time = Some(date_time::convert_to_prost_timestamp( - payment_attempt.created_at, - )); - let payment_method_type = Some(payment_attempt.payment_method_type.to_string()); - let payment_gateway = payment_attempt.connector.clone(); - - let pg_error_code = payment_attempt - .error - .as_ref() - .map(|error| error.code.clone()); - let network_advice_code = payment_attempt - .error - .as_ref() - .and_then(|error| error.network_advice_code.clone()); - let network_error_code = payment_attempt - .error - .as_ref() - .and_then(|error| error.network_decline_code.clone()); - let first_pg_error_code = revenue_recovery_metadata .and_then(|metadata| metadata.first_payment_attempt_pg_error_code.clone()); let first_network_advice_code = revenue_recovery_metadata @@ -365,29 +330,37 @@ pub(crate) async fn get_schedule_time_for_smart_retry( card_funding: card_funding_str, card_network: card_network_str, card_issuer: card_issuer_str, - invoice_start_time: start_time_proto, - retry_count: Some(retry_count.into()), + invoice_start_time: Some(start_time_proto), + retry_count: Some( + (total_retry_count_within_network.max_retry_count_for_thirty_day - retry_count_left) + .into(), + ), merchant_id, invoice_amount, invoice_currency, invoice_due_date, billing_country, billing_city, - attempt_currency, - attempt_status, - attempt_amount, + attempt_currency: None, + attempt_status: None, + attempt_amount: None, pg_error_code, - network_advice_code, - network_error_code, + network_advice_code: None, + network_error_code: None, first_pg_error_code, first_network_advice_code, first_network_error_code, - attempt_response_time, - payment_method_type, - payment_gateway, - retry_count_left: None, + attempt_response_time: None, + payment_method_type: None, + payment_gateway: None, + retry_count_left: Some(retry_count_left.into()), + total_retry_count_within_network: Some( + total_retry_count_within_network + .max_retry_count_for_thirty_day + .into(), + ), first_error_msg_time: None, - wait_time: None, + wait_time: retry_after_time, }; if let Some(mut client) = state.grpc_client.recovery_decider_client.clone() { @@ -395,7 +368,7 @@ pub(crate) async fn get_schedule_time_for_smart_retry( .decide_on_retry(decider_request.into(), state.get_recovery_grpc_headers()) .await { - Ok(grpc_response) => grpc_response + Ok(grpc_response) => Ok(grpc_response .retry_flag .then_some(()) .and(grpc_response.retry_time) @@ -409,16 +382,16 @@ pub(crate) async fn get_schedule_time_for_smart_retry( None // If conversion fails, treat as no valid retry time } } - }), + })), Err(e) => { logger::error!("Recovery decider gRPC call failed: {e:?}"); - None + Ok(None) } } } else { logger::debug!("Recovery decider client is not configured"); - None + Ok(None) } } @@ -430,7 +403,7 @@ struct InternalDeciderRequest { card_funding: Option<String>, card_network: Option<String>, card_issuer: Option<String>, - invoice_start_time: prost_types::Timestamp, + invoice_start_time: Option<prost_types::Timestamp>, retry_count: Option<i64>, merchant_id: Option<String>, invoice_amount: Option<i64>, @@ -451,6 +424,7 @@ struct InternalDeciderRequest { payment_method_type: Option<String>, payment_gateway: Option<String>, retry_count_left: Option<i64>, + total_retry_count_within_network: Option<i64>, first_error_msg_time: Option<prost_types::Timestamp>, wait_time: Option<prost_types::Timestamp>, } @@ -464,7 +438,7 @@ impl From<InternalDeciderRequest> for external_grpc_client::DeciderRequest { card_funding: internal_request.card_funding, card_network: internal_request.card_network, card_issuer: internal_request.card_issuer, - invoice_start_time: Some(internal_request.invoice_start_time), + invoice_start_time: internal_request.invoice_start_time, retry_count: internal_request.retry_count, merchant_id: internal_request.merchant_id, invoice_amount: internal_request.invoice_amount, @@ -485,8 +459,302 @@ impl From<InternalDeciderRequest> for external_grpc_client::DeciderRequest { payment_method_type: internal_request.payment_method_type, payment_gateway: internal_request.payment_gateway, retry_count_left: internal_request.retry_count_left, + total_retry_count_within_network: internal_request.total_retry_count_within_network, first_error_msg_time: internal_request.first_error_msg_time, wait_time: internal_request.wait_time, } } } + +#[cfg(feature = "v2")] +#[derive(Debug, Clone)] +pub struct ScheduledToken { + pub token_details: PaymentProcessorTokenDetails, + pub schedule_time: time::PrimitiveDateTime, +} + +#[cfg(feature = "v2")] +pub async fn get_token_with_schedule_time_based_on_retry_alogrithm_type( + state: &SessionState, + connector_customer_id: &str, + payment_intent: &PaymentIntent, + retry_algorithm_type: RevenueRecoveryAlgorithmType, + retry_count: i32, +) -> CustomResult<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { + let mut scheduled_time = None; + + match retry_algorithm_type { + RevenueRecoveryAlgorithmType::Monitoring => { + logger::error!("Monitoring type found for Revenue Recovery retry payment"); + } + + RevenueRecoveryAlgorithmType::Cascading => { + let time = get_schedule_time_to_retry_mit_payments( + state.store.as_ref(), + &payment_intent.merchant_id, + retry_count, + ) + .await + .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?; + + scheduled_time = Some(time); + + let token = + RedisTokenManager::get_token_with_max_retry_remaining(state, connector_customer_id) + .await + .change_context(errors::ProcessTrackerError::EApiErrorResponse)?; + + match token { + Some(token) => { + RedisTokenManager::update_payment_processor_token_schedule_time( + state, + connector_customer_id, + &token + .token_status + .payment_processor_token_details + .payment_processor_token, + scheduled_time, + ) + .await + .change_context(errors::ProcessTrackerError::EApiErrorResponse)?; + + logger::debug!("PSP token available for cascading retry"); + } + None => { + logger::debug!("No PSP token available for cascading retry"); + scheduled_time = None; + } + } + } + + RevenueRecoveryAlgorithmType::Smart => { + scheduled_time = get_best_psp_token_available_for_smart_retry( + state, + connector_customer_id, + payment_intent, + ) + .await + .change_context(errors::ProcessTrackerError::EApiErrorResponse)?; + } + } + + Ok(scheduled_time) +} + +#[cfg(feature = "v2")] +pub async fn get_best_psp_token_available_for_smart_retry( + state: &SessionState, + connector_customer_id: &str, + payment_intent: &PaymentIntent, +) -> CustomResult<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { + // Lock using payment_id + let locked = RedisTokenManager::lock_connector_customer_status( + state, + connector_customer_id, + &payment_intent.id, + ) + .await + .change_context(errors::ProcessTrackerError::ERedisError( + errors::RedisError::RedisConnectionError.into(), + ))?; + + match !locked { + true => Ok(None), + + false => { + // Get existing tokens from Redis + let existing_tokens = + RedisTokenManager::get_connector_customer_payment_processor_tokens( + state, + connector_customer_id, + ) + .await + .change_context(errors::ProcessTrackerError::ERedisError( + errors::RedisError::RedisConnectionError.into(), + ))?; + + // TODO: Insert into payment_intent_feature_metadata (DB operation) + + let result = RedisTokenManager::get_tokens_with_retry_metadata(state, &existing_tokens); + + let best_token_time = call_decider_for_payment_processor_tokens_select_closet_time( + state, + &result, + payment_intent, + connector_customer_id, + ) + .await + .change_context(errors::ProcessTrackerError::EApiErrorResponse)?; + + Ok(best_token_time) + } + } +} + +#[cfg(feature = "v2")] +pub async fn calculate_smart_retry_time( + state: &SessionState, + payment_intent: &PaymentIntent, + token_with_retry_info: &PaymentProcessorTokenWithRetryInfo, +) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { + let wait_hours = token_with_retry_info.retry_wait_time_hours; + let current_time = time::OffsetDateTime::now_utc(); + let future_time = current_time + time::Duration::hours(wait_hours); + + // Timestamp after which retry can be done without penalty + let future_timestamp = Some(prost_types::Timestamp { + seconds: future_time.unix_timestamp(), + nanos: 0, + }); + + get_schedule_time_for_smart_retry( + state, + payment_intent, + future_timestamp, + token_with_retry_info, + ) + .await +} + +#[cfg(feature = "v2")] +async fn process_token_for_retry( + state: &SessionState, + token_with_retry_info: &PaymentProcessorTokenWithRetryInfo, + payment_intent: &PaymentIntent, +) -> Result<Option<ScheduledToken>, errors::ProcessTrackerError> { + let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status; + let inserted_by_attempt_id = &token_status.inserted_by_attempt_id; + + let skip = token_status.is_hard_decline.unwrap_or(false); + + match skip { + true => { + logger::info!( + "Skipping decider call due to hard decline for attempt_id: {}", + inserted_by_attempt_id.get_string_repr() + ); + Ok(None) + } + false => { + let schedule_time = + calculate_smart_retry_time(state, payment_intent, token_with_retry_info).await?; + Ok(schedule_time.map(|schedule_time| ScheduledToken { + token_details: token_status.payment_processor_token_details.clone(), + schedule_time, + })) + } + } +} + +#[cfg(feature = "v2")] +#[allow(clippy::too_many_arguments)] +pub async fn call_decider_for_payment_processor_tokens_select_closet_time( + state: &SessionState, + processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>, + payment_intent: &PaymentIntent, + connector_customer_id: &str, +) -> CustomResult<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { + tracing::debug!("Filtered payment attempts based on payment tokens",); + let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new(); + + for token_with_retry_info in processor_tokens.values() { + let token_details = &token_with_retry_info + .token_status + .payment_processor_token_details; + let error_code = token_with_retry_info.token_status.error_code.clone(); + + match error_code { + None => { + let utc_schedule_time = + time::OffsetDateTime::now_utc() + time::Duration::minutes(1); + let schedule_time = time::PrimitiveDateTime::new( + utc_schedule_time.date(), + utc_schedule_time.time(), + ); + tokens_with_schedule_time = vec![ScheduledToken { + token_details: token_details.clone(), + schedule_time, + }]; + tracing::debug!( + "Found payment processor token with no error code scheduling it for {schedule_time}", + ); + break; + } + Some(_) => { + process_token_for_retry(state, token_with_retry_info, payment_intent) + .await? + .map(|token_with_schedule_time| { + tokens_with_schedule_time.push(token_with_schedule_time) + }); + } + } + } + + let best_token = tokens_with_schedule_time + .iter() + .min_by_key(|token| token.schedule_time) + .cloned(); + + match best_token { + None => { + RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id) + .await + .change_context(errors::ProcessTrackerError::EApiErrorResponse)?; + tracing::debug!("No payment processor tokens available for scheduling"); + Ok(None) + } + + Some(token) => { + tracing::debug!("Found payment processor token with least schedule time"); + + RedisTokenManager::update_payment_processor_token_schedule_time( + state, + connector_customer_id, + &token.token_details.payment_processor_token, + Some(token.schedule_time), + ) + .await + .change_context(errors::ProcessTrackerError::EApiErrorResponse)?; + + Ok(Some(token.schedule_time)) + } + } +} + +#[cfg(feature = "v2")] +pub async fn check_hard_decline( + state: &SessionState, + payment_attempt: &payment_attempt::PaymentAttempt, +) -> Result<bool, error_stack::Report<storage_impl::errors::RecoveryError>> { + let error_message = payment_attempt + .error + .as_ref() + .map(|details| details.message.clone()); + + let error_code = payment_attempt + .error + .as_ref() + .map(|details| details.code.clone()); + + let connector_name = payment_attempt + .connector + .clone() + .ok_or(storage_impl::errors::RecoveryError::ValueNotFound) + .attach_printable("unable to derive payment connector from payment attempt")?; + + let gsm_record = payments::helpers::get_gsm_record( + state, + error_code, + error_message, + connector_name, + REVENUE_RECOVERY.to_string(), + ) + .await; + + let is_hard_decline = gsm_record + .and_then(|record| record.error_category) + .map(|category| category == common_enums::ErrorCategory::HardDecline) + .unwrap_or(false); + + Ok(is_hard_decline) +} diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index b49713eb0ce..c42a880f707 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -786,3 +786,21 @@ billing_connectors_which_requires_invoice_sync_call = "recurly" [chat] enabled = false hyperswitch_ai_host = "http://0.0.0.0:8000" + + + +[revenue_recovery.card_config.amex] +max_retries_per_day = 20 +max_retry_count_for_thirty_day = 20 + +[revenue_recovery.card_config.mastercard] +max_retries_per_day = 10 +max_retry_count_for_thirty_day = 35 + +[revenue_recovery.card_config.visa] +max_retries_per_day = 20 +max_retry_count_for_thirty_day = 20 + +[revenue_recovery.card_config.discover] +max_retries_per_day = 20 +max_retry_count_for_thirty_day = 20 \ No newline at end of file diff --git a/proto/recovery_decider.proto b/proto/recovery_decider.proto index 28543b8fa28..b6346bc7ba1 100644 --- a/proto/recovery_decider.proto +++ b/proto/recovery_decider.proto @@ -35,8 +35,9 @@ message DeciderRequest { optional string payment_method_type = 24; optional string payment_gateway = 25; optional int64 retry_count_left = 26; - optional google.protobuf.Timestamp first_error_msg_time = 27; - optional google.protobuf.Timestamp wait_time = 28; + optional int64 total_retry_count_within_network = 27; + optional google.protobuf.Timestamp first_error_msg_time = 28; + optional google.protobuf.Timestamp wait_time = 29; } message DeciderResponse {
2025-08-05T21:28:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This module implements a **Redis-backed system** for managing and selecting the best **payment processor token** during **payment retries**. It ensures: - **Safe** token usage (no race conditions with locks) locked on connector customer level - if a payment has been scheduled then all other invoices for that customer will be in a queue. - **Consistent** retry limit enforcement --- ## Why This Exists In the **revenue recovery flow**, there is **no direct mapping between a customer and their payment methods**. However, card networks enforce **retry limits** (daily and rolling 30-day) for **each merchant–customer card**. Without tracking at this level, retries could breach these limits, leading to: - Higher decline rates - Potential network penalties ### The Solution 1. **Group multiple cards of a customer** under a single **`connector_customer_id`**. 2. **Store all payment processor tokens** for that connector customer in Redis. 3. Allow tokens to be: - **Inserted** when a webhook is received - **Retrieved** during the process tracker’s calculation flow to select the best retry candidate This enables: - Enforcement of **daily** and **30-day rolling thresholds** - Compliance with **network-level** retry rules - Token availability across flows without additional database lookups --- ## Redis Schema | Key Pattern | Type | Purpose | |-------------|--------|---------| | `customer:{customer_id}:status` | String | Lock key storing the `payment_id` to prevent parallel updates | | `customer:{customer_id}:tokens` | Hash | Maps `token_id` β†’ `TokenStatus` JSON | ### Example `TokenStatus` JSON ```json { "token_id": "tok_abc123", "error_code": "do_not_honor", "network": "visa", "added_by_payment_id": "pay_xyz789", "retry_history": { "2025-08-01": 1, "2025-08-02": 2 } } ``` ## Flow ### **Step 1 – Acquire Lock** - Create a lock key: `customer:{customer_id}:status` β†’ value = `payment_id` - Purpose: Prevent parallel processes from working on the same customer - If the lock is already present: - Exit early with message: *"Customer is already locked by another process."* --- ### **Step 2– Fetch Existing Tokens** - Retrieve all payment processor tokens from `customer:{customer_id}:tokens` - These tokens are then evaluated for retry eligibility --- ### **Step 3 – Check Retry Limits** For each token: - Count retries in the **last 30 days** - Check if daily or rolling 30-day limit is exceeded - If limit exceeded β†’ give a wait time for those tokens - Calculate **wait time** before the token can be retried again --- ### **Step 4 – Decider Logic (Upcoming)** - For all eligible tokens: 1. Determine the ** schedule time** for the psp tokens 2. Select the token with the **earliest schedule time** --- ### **Step 5 – Update Retry State** - After Transaction Executed - Increment **today’s retry count** for the selected token - Persist the updated `TokenStatus` back to Redis --- ### **Step 6 – Release Lock** - Delete `customer:{customer_id}:status` lock key - Allow the next payment flow to proceed ### 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 ### Payment Processor curl ``` curl --location 'http://localhost:8080/v2/connector-accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: {{}}' \ --header 'x-profile-id: {{}}' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'api-key: {{}}' \ --data ' { "connector_type": "payment_processor", "connector_name": "worldpayvantiv", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "u83996941026920501", "key1": "010193081", "api_secret": "qRfXV7aPcvkX6Fr" }, "payment_methods_enabled": [ { "payment_method_type": "card", "payment_method_subtypes": [ { "payment_method_subtype": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_subtype": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "frm_configs": null, "connector_webhook_details": { "merchant_secret": "" }, "metadata": { "report_group": "Hello", "merchant_config_currency": "USD" }, "profile_id": "pro_6BnIGqGPytQ3vwObbAw6" }' ``` ### Billing Processor curl ``` curl --location 'http://localhost:8080/v2/connector-accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: {{}}' \ --header 'x-profile-id: {{}}' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'api-key: {{}}' \ --data '{ "connector_type": "billing_processor", "connector_name": "custombilling", "connector_account_details": { "auth_type": "NoKey" }, "feature_metadata" : { "revenue_recovery" : { "max_retry_count" : 9, "billing_connector_retry_threshold" : 0, "billing_account_reference" :{ "{{connector_mca_id}}" : "{{connector_mca_id}}" }, "switch_payment_method_config" : { "retry_threshold" : 0, "time_threshold_after_creation": 0 } } }, "profile_id": "pro_6BnIGqGPytQ3vwObbAw6" }' ``` ### Api ``` curl --location 'http://localhost:8080/v2/payments/recovery' \ --header 'Authorization: api-key=dev_qHo39mf1hdLbY7GW7FOr89FaoCM1NQOdwPddWguUDI3RnsjQKPzG71uZIkuULDQu' \ --header 'x-profile-id: pro_xsbw9tuM9f6whrwaZKC2' \ --header 'x-merchant-id: cloth_seller_2px3Q1TUxtGOvO3Yzm0S' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_qHo39mf1hdLbY7GW7FOr89FaoCM1NQOdwPddWguUDI3RnsjQKPzG71uZIkuULDQu' \ --data '{ "amount_details": { "order_amount": 2250, "currency": "USD" }, "merchant_reference_id": "1234567891", "connector_transaction_id": "43255654", "connector_customer_id": "526755", "error": { "code": "110", "message": "Insufficient Funds" }, "billing": { "address": { "state": "CA", "country": "US" } }, "payment_method_type": "card", "payment_method_sub_type": "credit", "payment_method_data": { "primary_processor_payment_method_token": "2541911049890008", "additional_payment_method_info": { "card_exp_month": "12", "card_exp_year": "25", "last_four_digits": 1997, "card_network": "VISA", "card_issuer": "Wells Fargo NA", "card_type": "credit" } }, "billing_started_at": "2024-05-29T08:10:58Z", "transaction_created_at": "2024-05-29T08:10:58Z", "attempt_status": "failure", "action": "schedule_failed_payment", "billing_merchant_connector_id": "mca_6y5xtQUL2tgnHbjS7Bai", "payment_merchant_connector_id": "mca_OWLpnzoAxkhT1eZVJ3Q3" }' ``` ### Output The payment processor token details is getting stored in redis. <img width="1081" height="131" alt="Screenshot 2025-08-22 at 1 05 58β€―PM" src="https://github.com/user-attachments/assets/c99f54e3-9845-438c-b129-e661db08cc08" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.116.0
f5db00352b90e99e78b631fa8b9cde5800093a9d
f5db00352b90e99e78b631fa8b9cde5800093a9d
juspay/hyperswitch
juspay__hyperswitch-8864
Bug: [FEATURE] Reward PaymentMethod & CurrencyAuthKey for Hyperswitch <> UCS Integration ### Feature Description Add Reward payment method and CurrencyAuthKey auth type for HS <> UCS integration ### Possible Implementation Add Reward payment method and CurrencyAuthKey auth type for HS <> UCS integration ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index 474d6d6f1d5..5ce7eff9c8c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3041,6 +3041,7 @@ dependencies = [ "aws-sdk-sts", "aws-smithy-runtime", "base64 0.22.1", + "common_enums", "common_utils", "dyn-clone", "error-stack 0.4.1", @@ -3061,6 +3062,7 @@ dependencies = [ "router_env", "rust-grpc-client", "serde", + "serde_json", "thiserror 1.0.69", "time", "tokio 1.45.1", @@ -3538,7 +3540,7 @@ dependencies = [ [[package]] name = "grpc-api-types" version = "0.1.0" -source = "git+https://github.com/juspay/connector-service?rev=4387a6310dc9c2693b453b455a8032623f3d6a81#4387a6310dc9c2693b453b455a8032623f3d6a81" +source = "git+https://github.com/juspay/connector-service?rev=2263c96a70f2606475ab30e6f716b2773e1fd093#2263c96a70f2606475ab30e6f716b2773e1fd093" dependencies = [ "axum 0.8.4", "error-stack 0.5.0", @@ -6914,7 +6916,7 @@ dependencies = [ [[package]] name = "rust-grpc-client" version = "0.1.0" -source = "git+https://github.com/juspay/connector-service?rev=4387a6310dc9c2693b453b455a8032623f3d6a81#4387a6310dc9c2693b453b455a8032623f3d6a81" +source = "git+https://github.com/juspay/connector-service?rev=2263c96a70f2606475ab30e6f716b2773e1fd093#2263c96a70f2606475ab30e6f716b2773e1fd093" dependencies = [ "grpc-api-types", ] diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index b8933003065..062755496fe 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -51,6 +51,7 @@ lettre = "0.11.16" once_cell = "1.21.3" serde = { version = "1.0.219", features = ["derive"] } thiserror = "1.0.69" +serde_json = "1.0.140" vaultrs = { version = "0.7.4", optional = true } prost = { version = "0.13", optional = true } prost-types = { version = "0.13", optional = true } @@ -65,11 +66,12 @@ reqwest = { version = "0.11.27", features = ["rustls-tls"] } http = "0.2.12" url = { version = "2.5.4", features = ["serde"] } quick-xml = { version = "0.31.0", features = ["serialize"] } -unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "4387a6310dc9c2693b453b455a8032623f3d6a81", package = "rust-grpc-client" } +unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "2263c96a70f2606475ab30e6f716b2773e1fd093", package = "rust-grpc-client" } # First party crates common_utils = { version = "0.1.0", path = "../common_utils" } +common_enums = { version = "0.1.0", path = "../common_enums" } hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false } masking = { version = "0.1.0", path = "../masking" } router_env = { version = "0.1.0", path = "../router_env", features = [ diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs index 699d8dad7ee..62f681a985c 100644 --- a/crates/external_services/src/grpc_client/unified_connector_service.rs +++ b/crates/external_services/src/grpc_client/unified_connector_service.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use common_utils::{consts as common_utils_consts, errors::CustomResult, types::Url}; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; @@ -144,6 +146,10 @@ pub struct ConnectorAuthMetadata { /// Optional API secret used for signature or secure authentication. pub api_secret: Option<Secret<String>>, + /// Optional auth_key_map used for authentication. + pub auth_key_map: + Option<HashMap<common_enums::enums::Currency, common_utils::pii::SecretSerdeValue>>, + /// Id of the merchant. pub merchant_id: Secret<String>, } @@ -381,6 +387,16 @@ pub fn build_unified_connector_service_grpc_headers( parse("api_secret", api_secret.peek())?, ); } + if let Some(auth_key_map) = meta.auth_key_map { + let auth_key_map_str = serde_json::to_string(&auth_key_map).map_err(|error| { + logger::error!(?error); + UnifiedConnectorServiceError::ParsingFailed + })?; + metadata.append( + consts::UCS_HEADER_AUTH_KEY_MAP, + parse("auth_key_map", &auth_key_map_str)?, + ); + } metadata.append( common_utils_consts::X_MERCHANT_ID, diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index f63d2227053..7d97b5e99c0 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -85,6 +85,9 @@ pub mod consts { /// Header key for sending the API secret in signature-based authentication. pub(crate) const UCS_HEADER_API_SECRET: &str = "x-api-secret"; + + /// Header key for sending the AUTH KEY MAP in currency-based authentication. + pub(crate) const UCS_HEADER_AUTH_KEY_MAP: &str = "x-auth-key-map"; } /// Metrics for interactions with external systems. diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 4c59c8e952b..83629e53d05 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -89,7 +89,7 @@ reqwest = { version = "0.11.27", features = ["json", "rustls-tls", "gzip", "mult ring = "0.17.14" rust_decimal = { version = "1.37.1", features = ["serde-with-float", "serde-with-str"] } rust-i18n = { git = "https://github.com/kashif-m/rust-i18n", rev = "f2d8096aaaff7a87a847c35a5394c269f75e077a" } -unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "4387a6310dc9c2693b453b455a8032623f3d6a81", package = "rust-grpc-client" } +unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "2263c96a70f2606475ab30e6f716b2773e1fd093", package = "rust-grpc-client" } rustc-hash = "1.1.0" rustls = "0.22" rustls-pemfile = "2" diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 3907592d400..70b7fd3f75c 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -326,3 +326,6 @@ pub const UCS_AUTH_BODY_KEY: &str = "body-key"; /// Header value indicating that header-key-based authentication is used. pub const UCS_AUTH_HEADER_KEY: &str = "header-key"; + +/// Header value indicating that currency-auth-key-based authentication is used. +pub const UCS_AUTH_CURRENCY_AUTH_KEY: &str = "currency-auth-key"; diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs index b00440e89f3..b14811ea735 100644 --- a/crates/router/src/core/unified_connector_service.rs +++ b/crates/router/src/core/unified_connector_service.rs @@ -18,7 +18,7 @@ use masking::{ExposeInterface, PeekInterface, Secret}; use router_env::logger; use unified_connector_service_client::payments::{ self as payments_grpc, payment_method::PaymentMethod, CardDetails, CardPaymentMethodType, - PaymentServiceAuthorizeResponse, + PaymentServiceAuthorizeResponse, RewardPaymentMethodType, }; use crate::{ @@ -325,6 +325,24 @@ pub fn build_unified_connector_service_payment_method( payment_method: Some(upi_type), }) } + hyperswitch_domain_models::payment_method_data::PaymentMethodData::Reward => { + match payment_method_type { + PaymentMethodType::ClassicReward => Ok(payments_grpc::PaymentMethod { + payment_method: Some(PaymentMethod::Reward(RewardPaymentMethodType { + reward_type: 1, + })), + }), + PaymentMethodType::Evoucher => Ok(payments_grpc::PaymentMethod { + payment_method: Some(PaymentMethod::Reward(RewardPaymentMethodType { + reward_type: 2, + })), + }), + _ => Err(UnifiedConnectorServiceError::NotImplemented(format!( + "Unimplemented payment method subtype: {payment_method_type:?}" + )) + .into()), + } + } _ => Err(UnifiedConnectorServiceError::NotImplemented(format!( "Unimplemented payment method: {payment_method_data:?}" )) @@ -385,6 +403,7 @@ pub fn build_unified_connector_service_auth_metadata( api_key: Some(api_key.clone()), key1: Some(key1.clone()), api_secret: Some(api_secret.clone()), + auth_key_map: None, merchant_id: Secret::new(merchant_id.to_string()), }), ConnectorAuthType::BodyKey { api_key, key1 } => Ok(ConnectorAuthMetadata { @@ -393,6 +412,7 @@ pub fn build_unified_connector_service_auth_metadata( api_key: Some(api_key.clone()), key1: Some(key1.clone()), api_secret: None, + auth_key_map: None, merchant_id: Secret::new(merchant_id.to_string()), }), ConnectorAuthType::HeaderKey { api_key } => Ok(ConnectorAuthMetadata { @@ -401,6 +421,16 @@ pub fn build_unified_connector_service_auth_metadata( api_key: Some(api_key.clone()), key1: None, api_secret: None, + auth_key_map: None, + merchant_id: Secret::new(merchant_id.to_string()), + }), + ConnectorAuthType::CurrencyAuthKey { auth_key_map } => Ok(ConnectorAuthMetadata { + connector_name, + auth_type: consts::UCS_AUTH_CURRENCY_AUTH_KEY.to_string(), + api_key: None, + key1: None, + api_secret: None, + auth_key_map: Some(auth_key_map.clone()), merchant_id: Secret::new(merchant_id.to_string()), }), _ => Err(UnifiedConnectorServiceError::FailedToObtainAuthType) diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs index a6559abc2d4..c63fd4a4a62 100644 --- a/crates/router/src/core/unified_connector_service/transformers.rs +++ b/crates/router/src/core/unified_connector_service/transformers.rs @@ -51,6 +51,16 @@ impl ForeignTryFrom<&RouterData<PSync, PaymentsSyncData, PaymentsResponseData>> }) .ok(); + let encoded_data = router_data + .request + .encoded_data + .as_ref() + .map(|data| Identifier { + id_type: Some(payments_grpc::identifier::IdType::EncodedData( + data.to_string(), + )), + }); + let connector_ref_id = router_data .request .connector_reference_id @@ -60,7 +70,7 @@ impl ForeignTryFrom<&RouterData<PSync, PaymentsSyncData, PaymentsResponseData>> }); Ok(Self { - transaction_id: connector_transaction_id, + transaction_id: connector_transaction_id.or(encoded_data), request_ref_id: connector_ref_id, }) } @@ -319,6 +329,19 @@ impl ForeignTryFrom<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsRespon } }; + let capture_method = router_data + .request + .capture_method + .map(payments_grpc::CaptureMethod::foreign_try_from) + .transpose()?; + + let browser_info = router_data + .request + .browser_info + .clone() + .map(payments_grpc::BrowserInformation::foreign_try_from) + .transpose()?; + Ok(Self { request_ref_id: Some(Identifier { id_type: Some(payments_grpc::identifier::IdType::Id( @@ -342,6 +365,13 @@ impl ForeignTryFrom<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsRespon }) .unwrap_or_default(), webhook_url: router_data.request.webhook_url.clone(), + capture_method: capture_method.map(|capture_method| capture_method.into()), + email: router_data + .request + .email + .clone() + .map(|e| e.expose().expose()), + browser_info, }) } } @@ -370,13 +400,11 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse> }) }); - let transaction_id = response.transaction_id.as_ref().and_then(|id| { - id.id_type.clone().and_then(|id_type| match id_type { - payments_grpc::identifier::IdType::Id(id) => Some(id), - payments_grpc::identifier::IdType::EncodedData(encoded_data) => Some(encoded_data), - payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, - }) - }); + let resource_id: hyperswitch_domain_models::router_request_types::ResponseId = match response.transaction_id.as_ref().and_then(|id| id.id_type.clone()) { + Some(payments_grpc::identifier::IdType::Id(id)) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(id), + Some(payments_grpc::identifier::IdType::EncodedData(encoded_data)) => hyperswitch_domain_models::router_request_types::ResponseId::EncodedData(encoded_data), + Some(payments_grpc::identifier::IdType::NoResponseIdMarker(_)) | None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId, + }; let (connector_metadata, redirection_data) = match response.redirection_data.clone() { Some(redirection_data) => match redirection_data.form_type { @@ -423,13 +451,8 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse> }) } else { Ok(PaymentsResponseData::TransactionResponse { - resource_id: match transaction_id.as_ref() { - Some(transaction_id) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(transaction_id.clone()), - None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId, - }, - redirection_data: Box::new( - redirection_data - ), + resource_id, + redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata, network_txn_id: response.network_txn_id.clone(), @@ -469,6 +492,12 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceGetResponse> let status_code = convert_connector_service_status_code(response.status_code)?; + let resource_id: hyperswitch_domain_models::router_request_types::ResponseId = match response.transaction_id.as_ref().and_then(|id| id.id_type.clone()) { + Some(payments_grpc::identifier::IdType::Id(id)) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(id), + Some(payments_grpc::identifier::IdType::EncodedData(encoded_data)) => hyperswitch_domain_models::router_request_types::ResponseId::EncodedData(encoded_data), + Some(payments_grpc::identifier::IdType::NoResponseIdMarker(_)) | None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId, + }; + let response = if response.error_code.is_some() { Err(ErrorResponse { code: response.error_code().to_owned(), @@ -483,21 +512,22 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceGetResponse> }) } else { Ok(PaymentsResponseData::TransactionResponse { - resource_id: match connector_response_reference_id.as_ref() { - Some(connector_response_reference_id) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(connector_response_reference_id.clone()), - None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId, - }, - redirection_data: Box::new( - None - ), - mandate_reference: Box::new(None), + resource_id, + redirection_data: Box::new(None), + mandate_reference: Box::new(response.mandate_reference.map(|grpc_mandate| { + hyperswitch_domain_models::router_response_types::MandateReference { + connector_mandate_id: grpc_mandate.mandate_id, + payment_method_id: None, + mandate_metadata: None, + connector_mandate_request_reference_id: None, + } + })), connector_metadata: None, network_txn_id: response.network_txn_id.clone(), connector_response_reference_id, incremental_authorization_allowed: None, charges: None, - } - ) + }) }; Ok(response)
2025-07-28T09:27: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 implements the following - Added support for Reward payment methods for HS <> UCS integration - Added support for CurrencyAuthKey auth type for HS <> UCS integration - Send encoded_data as transaction_id when connector_transaction_id is None for PSync via UCS - Handle mandate_reference in PSync response from UCS - Updated unified-connector-service-client dependency ### 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? <details> <summary>Create Payment Evoucher</summary> ```json { "amount": 1000, "currency": "USD", "confirm": true, "payment_method_data": "reward", "payment_method_type": "evoucher", "payment_method":"reward", "capture_method": "automatic", "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1.2 Safari/605.1.15", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "en-US", "color_depth": 24, "screen_height": 1117, "screen_width": 1728, "time_zone": -330, "java_enabled": true, "java_script_enabled": true }, "customer_id": "cus_5ZiQdWmdv9efuLCPWeoN", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://www.google.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" }, "phone": { "number": "1233456789", "country_code": "+1" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" }, "phone": { "number": "1233456789", "country_code": "+1" } } } ``` Response ```json { "payment_id": "pay_Rg4QpaAPecdVQsRNBTmR", "merchant_id": "merchant_1753630639", "status": "requires_customer_action", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "cashtocode", "client_secret": "pay_Rg4QpaAPecdVQsRNBTmR_secret_OLIhHcWDaspkeHhC1LX8", "created": "2025-07-27T18:36:26.771Z", "currency": "USD", "customer_id": "cus_5ZiQdWmdv9efuLCPWeoN", "customer": { "id": "cus_5ZiQdWmdv9efuLCPWeoN", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "reward", "payment_method_data": "reward", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": "1233456789", "country_code": "+1" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": "1233456789", "country_code": "+1" }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://www.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_Rg4QpaAPecdVQsRNBTmR/merchant_1753630639/pay_Rg4QpaAPecdVQsRNBTmR_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "evoucher", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cus_5ZiQdWmdv9efuLCPWeoN", "created_at": 1753641386, "expires": 1753644986, "secret": "epk_e8ef8c9944cb44d0a04b9f480d56f8b1" }, "manual_retry_allowed": null, "connector_transaction_id": "pay_Rg4QpaAPecdVQsRNBTmR_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_TTKe5DLbKRzmvW23NZ8W", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_Cyziv5reSS6yqqJxi3NW", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-27T18:51:26.771Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": -330, "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1.2 Safari/605.1.15", "color_depth": 24, "java_enabled": true, "screen_width": 1728, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1117, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-07-27T18:36:28.202Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` </details> <details> <summary>Create Payment Classicreward</summary> ```json { "amount": 1000, "currency": "EUR", "confirm": true, "payment_method_data": "reward", "payment_method_type": "classic", "payment_method":"reward", "capture_method": "automatic", "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1.2 Safari/605.1.15", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "en-US", "color_depth": 24, "screen_height": 1117, "screen_width": 1728, "time_zone": -330, "java_enabled": true, "java_script_enabled": true }, "customer_id": "cus_5ZiQdWmdv9efuLCPWeoN", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://www.google.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" }, "phone": { "number": "1233456789", "country_code": "+1" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" }, "phone": { "number": "1233456789", "country_code": "+1" } } } ``` Response ```json { "payment_id": "pay_u2oFZ7JZu9DKDMxmr4V8", "merchant_id": "merchant_1753630639", "status": "requires_customer_action", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "cashtocode", "client_secret": "pay_u2oFZ7JZu9DKDMxmr4V8_secret_zfm7dQ9weLttW8467iKF", "created": "2025-07-27T18:41:01.619Z", "currency": "EUR", "customer_id": "cus_5ZiQdWmdv9efuLCPWeoN", "customer": { "id": "cus_5ZiQdWmdv9efuLCPWeoN", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "reward", "payment_method_data": "reward", "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": "1233456789", "country_code": "+1" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": { "number": "1233456789", "country_code": "+1" }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://www.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_u2oFZ7JZu9DKDMxmr4V8/merchant_1753630639/pay_u2oFZ7JZu9DKDMxmr4V8_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "classic", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cus_5ZiQdWmdv9efuLCPWeoN", "created_at": 1753641661, "expires": 1753645261, "secret": "epk_03beb90b91b249028e5f524c4366b16f" }, "manual_retry_allowed": null, "connector_transaction_id": "pay_u2oFZ7JZu9DKDMxmr4V8_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_TTKe5DLbKRzmvW23NZ8W", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_Cyziv5reSS6yqqJxi3NW", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-27T18:56:01.619Z", "fingerprint": null, "browser_info": { "language": "en-US", "time_zone": -330, "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1.2 Safari/605.1.15", "color_depth": 24, "java_enabled": true, "screen_width": 1728, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1117, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-07-27T18:41:02.554Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` </details> Enable payments in HS via UCS <img width="576" height="148" alt="Screenshot 2025-07-28 at 7 15 10β€―PM" src="https://github.com/user-attachments/assets/fe0d8b17-a3f6-427c-931f-1cbe2eef252e" /> Tests via HS <details> <summary>Create Payment</summary> ```json { "amount": 1000, "currency": "EUR", "confirm": true, "payment_link": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://www.google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4000000000001091", "card_exp_month": "12", "card_exp_year": "2029", "card_holder_name": "Max Mustermann", "card_cvc": "123", "card_network": "VISA" } }, "billing": { "address": { "line1": "1467", "line2": "CA", "line3": "CA", "city": "Musterhausen", "state": "California", "zip": "12345", "country": "DE", "first_name": "Max", "last_name": "Mustermann" }, "email": "test@novalnet.de", "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "Musterstr", "line2": "CA", "line3": "CA", "city": "Musterhausen", "state": "California", "zip": "94122", "country": "DE", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,\/;q=0.8", "language": "nl-NL", "color_depth": 24, "ip_address": "103.77.139.95", "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ``` Response ```json { "payment_id": "pay_SRFVMZTPcqcztdvz5Gqo", "merchant_id": "merchant_1753713393", "status": "requires_customer_action", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "novalnet", "client_secret": "pay_SRFVMZTPcqcztdvz5Gqo_secret_8ozHMAIx9DBii0jJSOOH", "created": "2025-07-28T16:36:32.363Z", "currency": "EUR", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1091", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "2029", "card_holder_name": "Max Mustermann", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "Musterhausen", "country": "DE", "line1": "Musterstr", "line2": "CA", "line3": "CA", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "Musterhausen", "country": "DE", "line1": "1467", "line2": "CA", "line3": "CA", "zip": "12345", "state": "California", "first_name": "Max", "last_name": "Mustermann" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "test@novalnet.de" }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_SRFVMZTPcqcztdvz5Gqo/merchant_1753713393/pay_SRFVMZTPcqcztdvz5Gqo_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": "StripeCustomer", "created_at": 1753720592, "expires": 1753724192, "secret": "epk_aa8c7a02cd0449c58648567385e71406" }, "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_khSwRJ3kHOBW2pETWhl3", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_44BTpt1weQvLwraRCJBa", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-28T16:51:32.363Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "103.77.139.95", "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-07-28T16:36:33.299Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` </details> <details> <summary>Sync Payment</summary> Response ```json { "payment_id": "pay_SRFVMZTPcqcztdvz5Gqo", "merchant_id": "merchant_1753713393", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "novalnet", "client_secret": "pay_SRFVMZTPcqcztdvz5Gqo_secret_8ozHMAIx9DBii0jJSOOH", "created": "2025-07-28T16:36:32.363Z", "currency": "EUR", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "attempts": [ { "attempt_id": "pay_SRFVMZTPcqcztdvz5Gqo_1", "status": "charged", "amount": 1000, "order_tax_amount": null, "currency": "EUR", "connector": "novalnet", "error_message": null, "payment_method": "card", "connector_transaction_id": null, "capture_method": "automatic", "authentication_type": "no_three_ds", "created_at": "2025-07-28T16:36:32.363Z", "modified_at": "2025-07-28T16:36:54.815Z", "cancellation_reason": null, "mandate_id": null, "error_code": null, "payment_token": null, "connector_metadata": null, "payment_experience": null, "payment_method_type": "credit", "reference_id": null, "unified_code": null, "unified_message": null, "client_source": null, "client_version": 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": "1091", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "2029", "card_holder_name": "Max Mustermann", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "Musterhausen", "country": "DE", "line1": "Musterstr", "line2": "CA", "line3": "CA", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "Musterhausen", "country": "DE", "line1": "1467", "line2": "CA", "line3": "CA", "zip": "12345", "state": "California", "first_name": "Max", "last_name": "Mustermann" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "test@novalnet.de" }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": 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_khSwRJ3kHOBW2pETWhl3", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_44BTpt1weQvLwraRCJBa", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-28T16:51:32.363Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "103.77.139.95", "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-07-28T16:36:54.815Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` </details> <details> <summary>Setup Mandate with 0 amount</summary> ```json { "confirm": true, "customer_id": "Customer123", "payment_type": "setup_mandate", "setup_future_usage": "off_session", "amount": 0, "currency": "EUR", "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" } }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4000000000001091", "card_exp_month": "12", "card_exp_year": "2029", "card_holder_name": "Max Mustermann", "card_cvc": "123", "card_network": "VISA" } }, "billing": { "address": { "line1": "1467", "line2": "CA", "line3": "CA", "city": "Musterhausen", "state": "California", "zip": "12345", "country": "DE", "first_name": "Max", "last_name": "Mustermann" }, "email": "test@novalnet.de", "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "Musterstr", "line2": "CA", "line3": "CA", "city": "Musterhausen", "state": "California", "zip": "94122", "country": "DE", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,\/;q=0.8", "language": "nl-NL", "color_depth": 24, "ip_address": "103.77.139.95", "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ``` Response ```json { "payment_id": "pay_SRFVMZTPcqcztdvz5Gqo", "merchant_id": "merchant_1753713393", "status": "requires_customer_action", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "novalnet", "client_secret": "pay_SRFVMZTPcqcztdvz5Gqo_secret_8ozHMAIx9DBii0jJSOOH", "created": "2025-07-28T16:36:32.363Z", "currency": "EUR", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1091", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "2029", "card_holder_name": "Max Mustermann", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "Musterhausen", "country": "DE", "line1": "Musterstr", "line2": "CA", "line3": "CA", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "Musterhausen", "country": "DE", "line1": "1467", "line2": "CA", "line3": "CA", "zip": "12345", "state": "California", "first_name": "Max", "last_name": "Mustermann" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "test@novalnet.de" }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://www.google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_SRFVMZTPcqcztdvz5Gqo/merchant_1753713393/pay_SRFVMZTPcqcztdvz5Gqo_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": "StripeCustomer", "created_at": 1753720592, "expires": 1753724192, "secret": "epk_aa8c7a02cd0449c58648567385e71406" }, "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_khSwRJ3kHOBW2pETWhl3", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_44BTpt1weQvLwraRCJBa", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-28T16:51:32.363Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "103.77.139.95", "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-07-28T16:36:33.299Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` </details> <details> <summary>Make a mandate payment manual capture</summary> ```json { "amount": 100, "currency": "EUR", "confirm": true, "capture_method": "manual", "customer_id": "Customer123", "off_session": true, "recurring_details": { "type": "payment_method_id", "data": "pm_dPmHDOL7xWQi0IGMPlCF" } } ``` Response ```json { "payment_id": "pay_TyY8IWSWaxTEzpOLgsu1", "merchant_id": "merchant_1753878378", "status": "requires_capture", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 100, "amount_received": null, "connector": "novalnet", "client_secret": "pay_TyY8IWSWaxTEzpOLgsu1_secret_CjCYuDfP1JGo6caJ4g2C", "created": "2025-07-31T13:50:56.144Z", "currency": "EUR", "customer_id": "Customer123", "customer": { "id": "Customer123", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "1091", "card_type": null, "card_network": "Visa", "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "2029", "card_holder_name": "Max Mustermann", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "Customer123", "created_at": 1753969856, "expires": 1753973456, "secret": "epk_382858505e58422b980776ffe49e26ed" }, "manual_retry_allowed": false, "connector_transaction_id": "15212700054805789", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "15212700054805789", "payment_link": null, "profile_id": "pro_McJmiAJzH046VnPS0CAN", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_O7lUCBZh6h106Xmsxady", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-31T14:05:56.144Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_dPmHDOL7xWQi0IGMPlCF", "payment_method_status": "active", "updated": "2025-07-31T13:50:58.462Z", "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": "R2cB22w22w00a02c-R22w22w22wNJV-V14o10kNZ22wB18sB18s16q00aNP22wXV", "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` </details> <details> <summary>Make a mandate payment auto capture</summary> ```json { "amount": 100, "currency": "EUR", "confirm": true, "capture_method": "automatic", "customer_id": "Customer123", "off_session": true, "recurring_details": { "type": "payment_method_id", "data": "pm_dPmHDOL7xWQi0IGMPlCF" } } ``` Response ```json { "payment_id": "pay_Ep1buzxTanjWDHQIv3Sx", "merchant_id": "merchant_1753878378", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "novalnet", "client_secret": "pay_Ep1buzxTanjWDHQIv3Sx_secret_9faeER31esgb88tLjiqK", "created": "2025-07-31T13:52:14.410Z", "currency": "EUR", "customer_id": "Customer123", "customer": { "id": "Customer123", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1091", "card_type": null, "card_network": "Visa", "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "2029", "card_holder_name": "Max Mustermann", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "Customer123", "created_at": 1753969934, "expires": 1753973534, "secret": "epk_253da8acb7454f67a2fb6bcdc170f1aa" }, "manual_retry_allowed": false, "connector_transaction_id": "15212700054912058", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "15212700054912058", "payment_link": null, "profile_id": "pro_McJmiAJzH046VnPS0CAN", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_O7lUCBZh6h106Xmsxady", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-31T14:07:14.410Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_dPmHDOL7xWQi0IGMPlCF", "payment_method_status": "active", "updated": "2025-07-31T13:52:17.146Z", "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": "R2cB22w22w00a02c-R22w22w22wNJV-V14o10kNZ22wB18sB18s16q00aNP22wXV", "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` </details> <!-- 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.116.0
8bb8b2062e84e8d7116a9ca0e76c8ebd71b2b3ec
8bb8b2062e84e8d7116a9ca0e76c8ebd71b2b3ec
juspay/hyperswitch
juspay__hyperswitch-8863
Bug: [FEATURE] Add new calculate job for revenue-recovery
diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs index 3aefb486810..962f917788d 100644 --- a/crates/diesel_models/src/process_tracker.rs +++ b/crates/diesel_models/src/process_tracker.rs @@ -255,6 +255,9 @@ pub mod business_status { /// This status indicates the completion of a execute task pub const EXECUTE_WORKFLOW_COMPLETE: &str = "COMPLETED_EXECUTE_TASK"; + /// This status indicates the failure of a execute task + pub const EXECUTE_WORKFLOW_FAILURE: &str = "FAILED_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"; @@ -276,4 +279,21 @@ pub mod business_status { /// This status indicates the completion of a review task pub const REVIEW_WORKFLOW_COMPLETE: &str = "COMPLETED_REVIEW_TASK"; + + /// For the CALCULATE_WORKFLOW + /// + /// This status indicates an invoice is queued + pub const CALCULATE_WORKFLOW_QUEUED: &str = "CALCULATE_WORKFLOW_QUEUED"; + + /// This status indicates an invoice has been declined due to hard decline + pub const CALCULATE_WORKFLOW_FINISH: &str = "FAILED_DUE_TO_HARD_DECLINE_ERROR"; + + /// This status indicates that the invoice is scheduled with the best available token + pub const CALCULATE_WORKFLOW_SCHEDULED: &str = "CALCULATE_WORKFLOW_SCHEDULED"; + + /// This status indicates the invoice is in payment sync state + pub const CALCULATE_WORKFLOW_PROCESSING: &str = "CALCULATE_WORKFLOW_PROCESSING"; + + /// This status indicates the workflow has completed successfully when the invoice is paid + pub const CALCULATE_WORKFLOW_COMPLETE: &str = "CALCULATE_WORKFLOW_COMPLETE"; } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 0a63c036780..1a8224b8140 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -518,6 +518,26 @@ pub struct PaymentIntent { #[cfg(feature = "v2")] impl PaymentIntent { + /// Extract customer_id from payment intent feature metadata + pub fn extract_connector_customer_id_from_payment_intent( + &self, + ) -> Result<String, common_utils::errors::ValidationError> { + self.feature_metadata + .as_ref() + .and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref()) + .map(|recovery| { + recovery + .billing_connector_payment_details + .connector_customer_id + .clone() + }) + .ok_or( + common_utils::errors::ValidationError::MissingRequiredField { + field_name: "connector_customer_id".to_string(), + }, + ) + } + fn get_payment_method_sub_type(&self) -> Option<common_enums::PaymentMethodType> { self.feature_metadata .as_ref() diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index bc8397b416b..bf5330a9325 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -486,6 +486,8 @@ pub enum RevenueRecoveryError { BillingConnectorPaymentsSyncFailed, #[error("Billing connector invoice sync call failed")] BillingConnectorInvoiceSyncFailed, + #[error("Failed to fetch connector customer ID")] + CustomerIdNotFound, #[error("Failed to get the retry count for payment intent")] RetryCountFetchFailed, #[error("Failed to get the billing threshold retry count")] diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs index 235d57f96d7..a2a90f1e9e1 100644 --- a/crates/router/src/core/revenue_recovery.rs +++ b/crates/router/src/core/revenue_recovery.rs @@ -1,35 +1,154 @@ pub mod api; pub mod transformers; pub mod types; -use api_models::{enums, process_tracker::revenue_recovery}; +use api_models::{enums, process_tracker::revenue_recovery, webhooks}; use common_utils::{ self, + errors::CustomResult, ext_traits::{OptionExt, ValueExt}, id_type, }; use diesel_models::{enums as diesel_enum, process_tracker::business_status}; use error_stack::{self, ResultExt}; -use hyperswitch_domain_models::{payments::PaymentIntent, ApiModelToDieselModelConvertor}; +use hyperswitch_domain_models::{ + payments::PaymentIntent, revenue_recovery as domain_revenue_recovery, + ApiModelToDieselModelConvertor, +}; use scheduler::errors as sch_errors; use crate::{ core::errors::{self, RouterResponse, RouterResult, StorageErrorExt}, db::StorageInterface, logger, - routes::{metrics, SessionState}, + routes::{app::ReqState, metrics, SessionState}, services::ApplicationResponse, types::{ + domain, storage::{self, revenue_recovery as pcr}, transformers::ForeignInto, }, + workflows, }; pub const EXECUTE_WORKFLOW: &str = "EXECUTE_WORKFLOW"; pub const PSYNC_WORKFLOW: &str = "PSYNC_WORKFLOW"; +pub const CALCULATE_WORKFLOW: &str = "CALCULATE_WORKFLOW"; + +#[allow(clippy::too_many_arguments)] +pub async fn upsert_calculate_pcr_task( + billing_connector_account: &domain::MerchantConnectorAccount, + state: &SessionState, + merchant_context: &domain::MerchantContext, + recovery_intent_from_payment_intent: &domain_revenue_recovery::RecoveryPaymentIntent, + business_profile: &domain::Profile, + intent_retry_count: u16, + payment_attempt_id: Option<id_type::GlobalAttemptId>, + runner: storage::ProcessTrackerRunner, + revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType, +) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { + router_env::logger::info!("Starting calculate_job..."); + + let task = "CALCULATE_WORKFLOW"; + + let db = &*state.store; + let payment_id = &recovery_intent_from_payment_intent.payment_id; + + // Create process tracker ID in the format: CALCULATE_WORKFLOW_{payment_intent_id} + let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr()); + + // Set scheduled time to 1 hour from now + let schedule_time = common_utils::date_time::now() + time::Duration::hours(1); + + let payment_attempt_id = payment_attempt_id + .ok_or(error_stack::report!( + errors::RevenueRecoveryError::PaymentAttemptIdNotFound + )) + .attach_printable("payment attempt id is required for calculate workflow tracking")?; + + // Check if a process tracker entry already exists for this payment intent + let existing_entry = db + .as_scheduler() + .find_process_by_id(&process_tracker_id) + .await + .change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError) + .attach_printable( + "Failed to check for existing calculate workflow process tracker entry", + )?; + + match existing_entry { + Some(existing_process) => { + router_env::logger::error!( + "Found existing CALCULATE_WORKFLOW task with id: {}", + existing_process.id + ); + } + None => { + // No entry exists - create a new one + router_env::logger::info!( + "No existing CALCULATE_WORKFLOW task found for payment_intent_id: {}, creating new entry scheduled for 1 hour from now", + payment_id.get_string_repr() + ); + + // Create tracking data + let calculate_workflow_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData { + billing_mca_id: billing_connector_account.get_id(), + global_payment_id: payment_id.clone(), + merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), + profile_id: business_profile.get_id().to_owned(), + payment_attempt_id, + revenue_recovery_retry, + invoice_scheduled_time: None, + }; + + let tag = ["PCR"]; + let task = "CALCULATE_WORKFLOW"; + let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; + + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + calculate_workflow_tracking_data, + Some(1), + schedule_time, + common_types::consts::API_VERSION, + ) + .change_context(errors::RevenueRecoveryError::ProcessTrackerCreationError) + .attach_printable("Failed to construct calculate workflow process tracker entry")?; + + // Insert into process tracker with status New + db.as_scheduler() + .insert_process(process_tracker_entry) + .await + .change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError) + .attach_printable( + "Failed to enter calculate workflow process_tracker_entry in DB", + )?; + + router_env::logger::info!( + "Successfully created new CALCULATE_WORKFLOW task for payment_intent_id: {}", + payment_id.get_string_repr() + ); + + metrics::TASKS_ADDED_COUNT.add( + 1, + router_env::metric_attributes!(("flow", "CalculateWorkflow")), + ); + } + } + + Ok(webhooks::WebhookResponseTracker::Payment { + payment_id: payment_id.clone(), + status: recovery_intent_from_payment_intent.status, + }) +} pub async fn perform_execute_payment( state: &SessionState, execute_task_process: &storage::ProcessTracker, + profile: &domain::Profile, + merchant_context: domain::MerchantContext, tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData, revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData, payment_intent: &PaymentIntent, @@ -74,6 +193,8 @@ pub async fn perform_execute_payment( revenue_recovery_payment_data.merchant_account.get_id(), payment_intent, execute_task_process, + profile, + merchant_context, revenue_recovery_payment_data, &revenue_recovery_metadata, )) @@ -218,6 +339,7 @@ async fn insert_psync_pcr_task_to_pt( profile_id, payment_attempt_id, revenue_recovery_retry, + invoice_scheduled_time: Some(schedule_time), }; let tag = ["REVENUE_RECOVERY"]; let process_tracker_entry = storage::ProcessTrackerNew::new( @@ -249,6 +371,8 @@ async fn insert_psync_pcr_task_to_pt( pub async fn perform_payments_sync( state: &SessionState, process: &storage::ProcessTracker, + profile: &domain::Profile, + merchant_context: domain::MerchantContext, tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData, revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData, payment_intent: &PaymentIntent, @@ -274,6 +398,8 @@ pub async fn perform_payments_sync( state, payment_intent, process.clone(), + profile, + merchant_context, revenue_recovery_payment_data, payment_attempt, &mut revenue_recovery_metadata, @@ -284,6 +410,416 @@ pub async fn perform_payments_sync( Ok(()) } +pub async fn perform_calculate_workflow( + state: &SessionState, + process: &storage::ProcessTracker, + profile: &domain::Profile, + merchant_context: domain::MerchantContext, + tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData, + revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData, + payment_intent: &PaymentIntent, +) -> Result<(), sch_errors::ProcessTrackerError> { + let db = &*state.store; + let merchant_id = revenue_recovery_payment_data.merchant_account.get_id(); + let profile_id = revenue_recovery_payment_data.profile.get_id(); + let billing_mca_id = revenue_recovery_payment_data.billing_mca.get_id(); + + logger::info!( + process_id = %process.id, + payment_id = %tracking_data.global_payment_id.get_string_repr(), + "Starting CALCULATE_WORKFLOW..." + ); + + // 1. Extract connector_customer_id and token_list from tracking_data + let connector_customer_id = payment_intent + .extract_connector_customer_id_from_payment_intent() + .change_context(errors::RecoveryError::ValueNotFound) + .attach_printable("Failed to extract customer ID from payment intent")?; + + let merchant_context_from_revenue_recovery_payment_data = + domain::MerchantContext::NormalMerchant(Box::new(domain::Context( + revenue_recovery_payment_data.merchant_account.clone(), + revenue_recovery_payment_data.key_store.clone(), + ))); + + let retry_algorithm_type = match profile + .revenue_recovery_retry_algorithm_type + .filter(|retry_type| + *retry_type != common_enums::RevenueRecoveryAlgorithmType::Monitoring) // ignore Monitoring in profile + .unwrap_or(tracking_data.revenue_recovery_retry) // fallback to tracking_data + { + common_enums::RevenueRecoveryAlgorithmType::Smart => common_enums::RevenueRecoveryAlgorithmType::Smart, + common_enums::RevenueRecoveryAlgorithmType::Cascading => common_enums::RevenueRecoveryAlgorithmType::Cascading, + common_enums::RevenueRecoveryAlgorithmType::Monitoring => { + return Err(sch_errors::ProcessTrackerError::ProcessUpdateFailed); + } + }; + + // 2. Get best available token + let best_time_to_schedule = match workflows::revenue_recovery::get_token_with_schedule_time_based_on_retry_alogrithm_type( + state, + &connector_customer_id, + payment_intent, + retry_algorithm_type, + process.retry_count, + ) + .await + { + Ok(token_opt) => token_opt, + Err(e) => { + logger::error!( + error = ?e, + connector_customer_id = %connector_customer_id, + "Failed to get best PSP token" + ); + None + } + }; + + match best_time_to_schedule { + Some(scheduled_time) => { + logger::info!( + process_id = %process.id, + connector_customer_id = %connector_customer_id, + "Found best available token, creating EXECUTE_WORKFLOW task" + ); + + // 3. If token found: create EXECUTE_WORKFLOW task and finish CALCULATE_WORKFLOW + insert_execute_pcr_task_to_pt( + &tracking_data.billing_mca_id, + state, + &tracking_data.merchant_id, + payment_intent, + &tracking_data.profile_id, + &tracking_data.payment_attempt_id, + storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, + tracking_data.revenue_recovery_retry, + scheduled_time, + ) + .await?; + + db.as_scheduler() + .finish_process_with_business_status( + process.clone(), + business_status::CALCULATE_WORKFLOW_SCHEDULED, + ) + .await + .map_err(|e| { + logger::error!( + process_id = %process.id, + error = ?e, + "Failed to update CALCULATE_WORKFLOW status to complete" + ); + sch_errors::ProcessTrackerError::ProcessUpdateFailed + })?; + + logger::info!( + process_id = %process.id, + connector_customer_id = %connector_customer_id, + "CALCULATE_WORKFLOW completed successfully" + ); + } + + None => { + let scheduled_token = match storage::revenue_recovery_redis_operation:: + RedisTokenManager::get_payment_processor_token_with_schedule_time(state, &connector_customer_id) + .await { + Ok(scheduled_token_opt) => scheduled_token_opt, + Err(e) => { + logger::error!( + error = ?e, + connector_customer_id = %connector_customer_id, + "Failed to get PSP token status" + ); + None + } + }; + + match scheduled_token { + Some(scheduled_token) => { + // Update scheduled time to scheduled time + 15 minutes + // here scheduled_time is the wait time 15 minutes is a buffer time that we are adding + logger::info!( + process_id = %process.id, + connector_customer_id = %connector_customer_id, + "No token but time available, rescheduling for scheduled time + 15 mins" + ); + + update_calculate_job_schedule_time( + db, + process, + time::Duration::minutes(15), + scheduled_token.scheduled_at, + &connector_customer_id, + ) + .await?; + } + None => { + let hard_decline_flag = storage::revenue_recovery_redis_operation:: + RedisTokenManager::are_all_tokens_hard_declined( + state, + &connector_customer_id + ) + .await + .ok() + .unwrap_or(false); + + match hard_decline_flag { + false => { + logger::info!( + process_id = %process.id, + connector_customer_id = %connector_customer_id, + "Hard decline flag is false, rescheduling for scheduled time + 15 mins" + ); + + update_calculate_job_schedule_time( + db, + process, + time::Duration::minutes(15), + Some(common_utils::date_time::now()), + &connector_customer_id, + ) + .await?; + } + true => { + // Finish calculate workflow with CALCULATE_WORKFLOW_FINISH + logger::info!( + process_id = %process.id, + connector_customer_id = %connector_customer_id, + "No token available, finishing CALCULATE_WORKFLOW" + ); + + db.as_scheduler() + .finish_process_with_business_status( + process.clone(), + business_status::CALCULATE_WORKFLOW_FINISH, + ) + .await + .map_err(|e| { + logger::error!( + process_id = %process.id, + error = ?e, + "Failed to finish CALCULATE_WORKFLOW" + ); + sch_errors::ProcessTrackerError::ProcessUpdateFailed + })?; + + logger::info!( + process_id = %process.id, + connector_customer_id = %connector_customer_id, + "CALCULATE_WORKFLOW finished successfully" + ); + } + } + } + } + } + } + Ok(()) +} + +/// Update the schedule time for a CALCULATE_WORKFLOW process tracker +async fn update_calculate_job_schedule_time( + db: &dyn StorageInterface, + process: &storage::ProcessTracker, + additional_time: time::Duration, + base_time: Option<time::PrimitiveDateTime>, + connector_customer_id: &str, +) -> Result<(), sch_errors::ProcessTrackerError> { + let new_schedule_time = + base_time.unwrap_or_else(common_utils::date_time::now) + additional_time; + + let pt_update = storage::ProcessTrackerUpdate::Update { + name: Some("CALCULATE_WORKFLOW".to_string()), + retry_count: Some(process.clone().retry_count), + schedule_time: Some(new_schedule_time), + tracking_data: Some(process.clone().tracking_data), + business_status: Some(String::from(business_status::PENDING)), + status: Some(common_enums::ProcessTrackerStatus::Pending), + updated_at: Some(common_utils::date_time::now()), + }; + + db.as_scheduler() + .update_process(process.clone(), pt_update) + .await + .map_err(|e| { + logger::error!( + process_id = %process.id, + error = ?e, + "Failed to reschedule CALCULATE_WORKFLOW" + ); + sch_errors::ProcessTrackerError::ProcessUpdateFailed + })?; + + logger::info!( + process_id = %process.id, + connector_customer_id = %connector_customer_id, + new_schedule_time = %new_schedule_time, + additional_time = ?additional_time, + "CALCULATE_WORKFLOW rescheduled successfully" + ); + + Ok(()) +} + +/// Insert Execute PCR Task to Process Tracker +#[allow(clippy::too_many_arguments)] +async fn insert_execute_pcr_task_to_pt( + billing_mca_id: &id_type::MerchantConnectorAccountId, + state: &SessionState, + merchant_id: &id_type::MerchantId, + payment_intent: &PaymentIntent, + profile_id: &id_type::ProfileId, + payment_attempt_id: &id_type::GlobalAttemptId, + runner: storage::ProcessTrackerRunner, + revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType, + schedule_time: time::PrimitiveDateTime, +) -> Result<storage::ProcessTracker, sch_errors::ProcessTrackerError> { + let task = "EXECUTE_WORKFLOW"; + + let payment_id = payment_intent.id.clone(); + + let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr()); + + // Check if a process tracker entry already exists for this payment intent + let existing_entry = state + .store + .find_process_by_id(&process_tracker_id) + .await + .map_err(|e| { + logger::error!( + payment_id = %payment_id.get_string_repr(), + process_tracker_id = %process_tracker_id, + error = ?e, + "Failed to check for existing execute workflow process tracker entry" + ); + sch_errors::ProcessTrackerError::ProcessUpdateFailed + })?; + + match existing_entry { + Some(existing_process) + if existing_process.business_status == business_status::EXECUTE_WORKFLOW_FAILURE + || existing_process.business_status + == business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC => + { + // Entry exists with EXECUTE_WORKFLOW_COMPLETE status - update it + logger::info!( + payment_id = %payment_id.get_string_repr(), + process_tracker_id = %process_tracker_id, + current_retry_count = %existing_process.retry_count, + "Found existing EXECUTE_WORKFLOW task with COMPLETE status, updating to PENDING with incremented retry count" + ); + + let pt_update = storage::ProcessTrackerUpdate::Update { + name: Some(task.to_string()), + retry_count: Some(existing_process.clone().retry_count + 1), + schedule_time: Some(schedule_time), + tracking_data: Some(existing_process.clone().tracking_data), + business_status: Some(String::from(business_status::PENDING)), + status: Some(enums::ProcessTrackerStatus::Pending), + updated_at: Some(common_utils::date_time::now()), + }; + + let updated_process = state + .store + .update_process(existing_process, pt_update) + .await + .map_err(|e| { + logger::error!( + payment_id = %payment_id.get_string_repr(), + process_tracker_id = %process_tracker_id, + error = ?e, + "Failed to update existing execute workflow process tracker entry" + ); + sch_errors::ProcessTrackerError::ProcessUpdateFailed + })?; + + logger::info!( + payment_id = %payment_id.get_string_repr(), + process_tracker_id = %process_tracker_id, + new_retry_count = %updated_process.retry_count, + "Successfully updated existing EXECUTE_WORKFLOW task" + ); + + Ok(updated_process) + } + Some(existing_process) => { + // Entry exists but business status is not EXECUTE_WORKFLOW_COMPLETE + logger::info!( + payment_id = %payment_id.get_string_repr(), + process_tracker_id = %process_tracker_id, + current_business_status = %existing_process.business_status, + ); + + Ok(existing_process) + } + None => { + // No entry exists - create a new one + logger::info!( + payment_id = %payment_id.get_string_repr(), + process_tracker_id = %process_tracker_id, + "No existing EXECUTE_WORKFLOW task found, creating new entry" + ); + + let execute_workflow_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData { + billing_mca_id: billing_mca_id.clone(), + global_payment_id: payment_id.clone(), + merchant_id: merchant_id.clone(), + profile_id: profile_id.clone(), + payment_attempt_id: payment_attempt_id.clone(), + revenue_recovery_retry, + invoice_scheduled_time: Some(schedule_time), + }; + + let tag = ["PCR"]; + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id.clone(), + task, + runner, + tag, + execute_workflow_tracking_data, + Some(1), + schedule_time, + common_types::consts::API_VERSION, + ) + .map_err(|e| { + logger::error!( + payment_id = %payment_id.get_string_repr(), + error = ?e, + "Failed to construct execute workflow process tracker entry" + ); + sch_errors::ProcessTrackerError::ProcessUpdateFailed + })?; + + let response = state + .store + .insert_process(process_tracker_entry) + .await + .map_err(|e| { + logger::error!( + payment_id = %payment_id.get_string_repr(), + error = ?e, + "Failed to insert execute workflow process tracker entry" + ); + sch_errors::ProcessTrackerError::ProcessUpdateFailed + })?; + + metrics::TASKS_ADDED_COUNT.add( + 1, + router_env::metric_attributes!(("flow", "RevenueRecoveryExecute")), + ); + + logger::info!( + payment_id = %payment_id.get_string_repr(), + process_tracker_id = %response.id, + "Successfully created new EXECUTE_WORKFLOW task" + ); + + Ok(response) + } + } +} + pub async fn retrieve_revenue_recovery_process_tracker( state: SessionState, id: id_type::GlobalPaymentId, diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index 1bccb5134bb..e3401baa40f 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -31,11 +31,12 @@ use hyperswitch_domain_models::{ }; use time::PrimitiveDateTime; +use super::errors::StorageErrorExt; use crate::{ core::{ errors::{self, RouterResult}, payments::{self, helpers, operations::Operation}, - revenue_recovery::{self as revenue_recovery_core}, + revenue_recovery::{self as revenue_recovery_core, perform_calculate_workflow}, webhooks::recovery_incoming as recovery_incoming_flow, }, db::StorageInterface, @@ -43,9 +44,13 @@ use crate::{ routes::SessionState, services::{self, connector_integration_interface::RouterDataConversion}, types::{ - self, api as api_types, api::payments as payments_types, storage, transformers::ForeignInto, + self, api as api_types, api::payments as payments_types, domain, storage, + transformers::ForeignInto, + }, + workflows::{ + payment_sync, + revenue_recovery::{self, get_schedule_time_to_retry_mit_payments}, }, - workflows::{payment_sync, revenue_recovery::get_schedule_time_to_retry_mit_payments}, }; type RecoveryResult<T> = error_stack::Result<T, errors::RecoveryError>; @@ -93,15 +98,23 @@ impl RevenueRecoveryPaymentsAttemptStatus { Ok(()) } + #[allow(clippy::too_many_arguments)] pub(crate) async fn update_pt_status_based_on_attempt_status_for_payments_sync( &self, state: &SessionState, payment_intent: &PaymentIntent, process_tracker: storage::ProcessTracker, + profile: &domain::Profile, + merchant_context: domain::MerchantContext, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, payment_attempt: PaymentAttempt, revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata, ) -> Result<(), errors::ProcessTrackerError> { + let connector_customer_id = payment_intent + .extract_connector_customer_id_from_payment_intent() + .change_context(errors::RecoveryError::ValueNotFound) + .attach_printable("Failed to extract customer ID from payment intent")?; + let db = &*state.store; let recovery_payment_intent = @@ -143,6 +156,26 @@ impl RevenueRecoveryPaymentsAttemptStatus { ); }; + let is_hard_decline = revenue_recovery::check_hard_decline(state, &payment_attempt) + .await + .ok(); + + // update the status of token in redis + let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( + state, + &connector_customer_id, + &None, + &is_hard_decline + ) + .await; + + // unlocking the token + let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( + state, + &connector_customer_id, + ) + .await; + // Record a successful transaction back to Billing Connector // TODO: Add support for retrying failed outgoing recordback webhooks record_back_to_billing_connector( @@ -175,26 +208,38 @@ impl RevenueRecoveryPaymentsAttemptStatus { ); }; - // get a reschedule time - let schedule_time = get_schedule_time_to_retry_mit_payments( - db, - &revenue_recovery_payment_data - .merchant_account - .get_id() - .clone(), - process_tracker.retry_count + 1, + let error_code = recovery_payment_attempt.error_code; + + let is_hard_decline = revenue_recovery::check_hard_decline(state, &payment_attempt) + .await + .ok(); + + // update the status of token in redis + let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( + state, + &connector_customer_id, + &error_code, + &is_hard_decline ) .await; - // check if retry is possible - if let Some(schedule_time) = schedule_time { - // schedule a retry - // TODO: Update connecter called field and active attempt + // unlocking the token + let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( + state, + &connector_customer_id, + ) + .await; - db.as_scheduler() - .retry_process(process_tracker.clone(), schedule_time) - .await?; - } + // Reopen calculate workflow on payment failure + reopen_calculate_workflow_on_payment_failure( + state, + &process_tracker, + profile, + merchant_context, + payment_intent, + revenue_recovery_payment_data, + ) + .await?; } Self::Processing => { // do a psync payment @@ -203,6 +248,8 @@ impl RevenueRecoveryPaymentsAttemptStatus { revenue_recovery_payment_data, payment_intent, &process_tracker, + profile, + merchant_context, payment_attempt, )) .await?; @@ -307,105 +354,227 @@ pub enum Action { ManualReviewAction, } impl Action { + #[allow(clippy::too_many_arguments)] pub async fn execute_payment( state: &SessionState, merchant_id: &id_type::MerchantId, payment_intent: &PaymentIntent, process: &storage::ProcessTracker, + profile: &domain::Profile, + merchant_context: domain::MerchantContext, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, revenue_recovery_metadata: &PaymentRevenueRecoveryMetadata, ) -> RecoveryResult<Self> { - let response = revenue_recovery_core::api::call_proxy_api( - state, - payment_intent, - revenue_recovery_payment_data, - revenue_recovery_metadata, - ) - .await; - let recovery_payment_intent = - hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from( - payment_intent, - ); + let connector_customer_id = payment_intent + .extract_connector_customer_id_from_payment_intent() + .change_context(errors::RecoveryError::ValueNotFound) + .attach_printable("Failed to extract customer ID from payment intent")?; - // handle proxy api's response - match response { - Ok(payment_data) => match payment_data.payment_attempt.status.foreign_into() { - RevenueRecoveryPaymentsAttemptStatus::Succeeded => { - let recovery_payment_attempt = - hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from( - &payment_data.payment_attempt, - ); - - let recovery_payment_tuple = recovery_incoming_flow::RecoveryPaymentTuple::new( - &recovery_payment_intent, - &recovery_payment_attempt, - ); + let scheduled_token = match storage::revenue_recovery_redis_operation:: + RedisTokenManager::get_payment_processor_token_with_schedule_time(state, &connector_customer_id) + .await { + Ok(scheduled_token_opt) => scheduled_token_opt, + Err(e) => { + logger::error!( + error = ?e, + connector_customer_id = %connector_customer_id, + "Failed to get PSP token status" + ); + None + } + }; - // publish events to kafka - if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( + match scheduled_token { + Some(scheduled_token) => { + let response = revenue_recovery_core::api::call_proxy_api( state, - &recovery_payment_tuple, - Some(process.retry_count+1) + payment_intent, + revenue_recovery_payment_data, + revenue_recovery_metadata, ) - .await{ - router_env::logger::error!( - "Failed to publish revenue recovery event to kafka: {:?}", - e + .await; + + let recovery_payment_intent = + hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from( + payment_intent, ); - }; - Ok(Self::SuccessfulPayment( - payment_data.payment_attempt.clone(), - )) + // handle proxy api's response + match response { + Ok(payment_data) => match payment_data.payment_attempt.status.foreign_into() { + RevenueRecoveryPaymentsAttemptStatus::Succeeded => { + let recovery_payment_attempt = + hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from( + &payment_data.payment_attempt, + ); + + let recovery_payment_tuple = + recovery_incoming_flow::RecoveryPaymentTuple::new( + &recovery_payment_intent, + &recovery_payment_attempt, + ); + + // publish events to kafka + if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( + state, + &recovery_payment_tuple, + Some(process.retry_count+1) + ) + .await{ + router_env::logger::error!( + "Failed to publish revenue recovery event to kafka: {:?}", + e + ); + }; + + let is_hard_decline = revenue_recovery::check_hard_decline( + state, + &payment_data.payment_attempt, + ) + .await + .ok(); + + // update the status of token in redis + let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( + state, + &connector_customer_id, + &None, + &is_hard_decline + ) + .await; + + // unlocking the token + let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( + state, + &connector_customer_id, + ) + .await; + + Ok(Self::SuccessfulPayment( + payment_data.payment_attempt.clone(), + )) + } + RevenueRecoveryPaymentsAttemptStatus::Failed => { + let recovery_payment_attempt = + hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from( + &payment_data.payment_attempt, + ); + + let recovery_payment_tuple = + recovery_incoming_flow::RecoveryPaymentTuple::new( + &recovery_payment_intent, + &recovery_payment_attempt, + ); + + // publish events to kafka + if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( + state, + &recovery_payment_tuple, + Some(process.retry_count+1) + ) + .await{ + router_env::logger::error!( + "Failed to publish revenue recovery event to kafka: {:?}", + e + ); + }; + + let error_code = payment_data + .payment_attempt + .clone() + .error + .map(|error| error.code); + + let is_hard_decline = revenue_recovery::check_hard_decline( + state, + &payment_data.payment_attempt, + ) + .await + .ok(); + + let _update_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( + state, + &connector_customer_id, + &error_code, + &is_hard_decline + ) + .await; + + // unlocking the token + let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( + state, + &connector_customer_id, + ) + .await; + + // Reopen calculate workflow on payment failure + reopen_calculate_workflow_on_payment_failure( + state, + process, + profile, + merchant_context, + payment_intent, + revenue_recovery_payment_data, + ) + .await?; + + // Return terminal failure to finish the current execute workflow + Ok(Self::TerminalFailure(payment_data.payment_attempt.clone())) + } + + RevenueRecoveryPaymentsAttemptStatus::Processing => { + Ok(Self::SyncPayment(payment_data.payment_attempt.clone())) + } + RevenueRecoveryPaymentsAttemptStatus::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); + Ok(Self::ReviewPayment) + } } - RevenueRecoveryPaymentsAttemptStatus::Failed => { - let recovery_payment_attempt = - hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from( - &payment_data.payment_attempt, - ); - - let recovery_payment_tuple = recovery_incoming_flow::RecoveryPaymentTuple::new( - &recovery_payment_intent, - &recovery_payment_attempt, - ); + } + None => { + let response = revenue_recovery_core::api::call_psync_api( + state, + payment_intent.get_id(), + revenue_recovery_payment_data, + ) + .await; - // publish events to kafka - if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( - state, - &recovery_payment_tuple, - Some(process.retry_count+1) - ) - .await{ - router_env::logger::error!( - "Failed to publish revenue recovery event to kafka: {:?}", - e - ); - }; - - Self::decide_retry_failure_action( - state, - merchant_id, + let payment_status_data = response + .change_context(errors::RecoveryError::PaymentCallFailed) + .attach_printable("Error while executing the Psync call")?; + + let payment_attempt = payment_status_data.payment_attempt; + + logger::info!( + process_id = %process.id, + connector_customer_id = %connector_customer_id, + "No token available, finishing CALCULATE_WORKFLOW" + ); + + state + .store + .as_scheduler() + .finish_process_with_business_status( process.clone(), - revenue_recovery_payment_data, - &payment_data.payment_attempt, - payment_intent, + business_status::CALCULATE_WORKFLOW_FINISH, ) .await - } + .change_context(errors::RecoveryError::ProcessTrackerFailure) + .attach_printable("Failed to finish CALCULATE_WORKFLOW")?; - RevenueRecoveryPaymentsAttemptStatus::Processing => { - Ok(Self::SyncPayment(payment_data.payment_attempt.clone())) - } - RevenueRecoveryPaymentsAttemptStatus::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); - Ok(Self::ReviewPayment) + logger::info!( + process_id = %process.id, + connector_customer_id = %connector_customer_id, + "CALCULATE_WORKFLOW finished successfully" + ); + Ok(Self::TerminalFailure(payment_attempt.clone())) } } } @@ -486,16 +655,45 @@ impl Action { Ok(()) } Self::TerminalFailure(payment_attempt) => { + // update the connector payment transmission field to Unsuccessful and unset active attempt id + revenue_recovery_metadata.set_payment_transmission_field_for_api_request( + enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful, + ); + + let payment_update_req = + PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api( + payment_intent + .feature_metadata + .clone() + .unwrap_or_default() + .convert_back() + .set_payment_revenue_recovery_metadata_using_api( + revenue_recovery_metadata.clone(), + ), + api_enums::UpdateActiveAttempt::Unset, + ); + logger::info!( + "Call made to payments update intent api , with the request body {:?}", + payment_update_req + ); + revenue_recovery_core::api::update_payment_intent_api( + state, + payment_intent.id.clone(), + revenue_recovery_payment_data, + payment_update_req, + ) + .await + .change_context(errors::RecoveryError::PaymentCallFailed)?; + db.as_scheduler() .finish_process_with_business_status( execute_task_process.clone(), - business_status::EXECUTE_WORKFLOW_COMPLETE, + business_status::EXECUTE_WORKFLOW_FAILURE, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; // TODO: Add support for retrying failed outgoing recordback webhooks - Ok(()) } Self::SuccessfulPayment(payment_attempt) => { @@ -551,6 +749,8 @@ impl Action { revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, payment_intent: &PaymentIntent, process: &storage::ProcessTracker, + profile: &domain::Profile, + merchant_context: domain::MerchantContext, payment_attempt: PaymentAttempt, ) -> RecoveryResult<Self> { let response = revenue_recovery_core::api::call_psync_api( @@ -563,18 +763,74 @@ impl Action { match response { Ok(_payment_data) => match payment_attempt.status.foreign_into() { RevenueRecoveryPaymentsAttemptStatus::Succeeded => { + let connector_customer_id = payment_intent + .extract_connector_customer_id_from_payment_intent() + .change_context(errors::RecoveryError::ValueNotFound) + .attach_printable("Failed to extract customer ID from payment intent")?; + + let is_hard_decline = + revenue_recovery::check_hard_decline(state, &payment_attempt) + .await + .ok(); + + // update the status of token in redis + let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( + state, + &connector_customer_id, + &None, + &is_hard_decline + ) + .await; + + // unlocking the token + let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( + state, + &connector_customer_id, + ) + .await; + Ok(Self::SuccessfulPayment(payment_attempt)) } RevenueRecoveryPaymentsAttemptStatus::Failed => { - Self::decide_retry_failure_action( + let connector_customer_id = payment_intent + .extract_connector_customer_id_from_payment_intent() + .change_context(errors::RecoveryError::ValueNotFound) + .attach_printable("Failed to extract customer ID from payment intent")?; + + let error_code = payment_attempt.clone().error.map(|error| error.code); + + let is_hard_decline = + revenue_recovery::check_hard_decline(state, &payment_attempt) + .await + .ok(); + + let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( + state, + &connector_customer_id, + &error_code, + &is_hard_decline + ) + .await; + + // unlocking the token + let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( state, - revenue_recovery_payment_data.merchant_account.get_id(), - process.clone(), - revenue_recovery_payment_data, - &payment_attempt, + &connector_customer_id, + ) + .await; + + // Reopen calculate workflow on payment failure + reopen_calculate_workflow_on_payment_failure( + state, + process, + profile, + merchant_context, payment_intent, + revenue_recovery_payment_data, ) - .await + .await?; + + Ok(Self::TerminalFailure(payment_attempt.clone())) } RevenueRecoveryPaymentsAttemptStatus::Processing => { @@ -684,6 +940,37 @@ impl Action { } Self::TerminalFailure(payment_attempt) => { + // update the connector payment transmission field to Unsuccessful and unset active attempt id + revenue_recovery_metadata.set_payment_transmission_field_for_api_request( + enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful, + ); + + let payment_update_req = + PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api( + payment_intent + .feature_metadata + .clone() + .unwrap_or_default() + .convert_back() + .set_payment_revenue_recovery_metadata_using_api( + revenue_recovery_metadata.clone(), + ), + api_enums::UpdateActiveAttempt::Unset, + ); + logger::info!( + "Call made to payments update intent api , with the request body {:?}", + payment_update_req + ); + + revenue_recovery_core::api::update_payment_intent_api( + state, + payment_intent.id.clone(), + revenue_recovery_payment_data, + payment_update_req, + ) + .await + .change_context(errors::RecoveryError::PaymentCallFailed)?; + // TODO: Add support for retrying failed outgoing recordback webhooks // finish the current psync task db.as_scheduler() @@ -804,6 +1091,140 @@ impl Action { } } } + +/// Reopen calculate workflow when payment fails +pub async fn reopen_calculate_workflow_on_payment_failure( + state: &SessionState, + process: &storage::ProcessTracker, + profile: &domain::Profile, + merchant_context: domain::MerchantContext, + payment_intent: &PaymentIntent, + revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, +) -> RecoveryResult<()> { + let db = &*state.store; + let id = payment_intent.id.clone(); + let task = revenue_recovery_core::CALCULATE_WORKFLOW; + let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; + + // Construct the process tracker ID for CALCULATE_WORKFLOW + let process_tracker_id = format!("{}_{}_{}", runner, task, id.get_string_repr()); + + logger::info!( + payment_id = %id.get_string_repr(), + process_tracker_id = %process_tracker_id, + "Attempting to reopen CALCULATE_WORKFLOW on payment failure" + ); + + // Find the existing CALCULATE_WORKFLOW process tracker + let calculate_process = db + .find_process_by_id(&process_tracker_id) + .await + .change_context(errors::RecoveryError::ProcessTrackerFailure) + .attach_printable("Failed to find CALCULATE_WORKFLOW process tracker")?; + + match calculate_process { + Some(process) => { + logger::info!( + payment_id = %id.get_string_repr(), + process_tracker_id = %process_tracker_id, + current_status = %process.business_status, + current_retry_count = process.retry_count, + "Found existing CALCULATE_WORKFLOW, updating status and retry count" + ); + + // Update the process tracker to reopen the calculate workflow + // 1. Change status from "finish" to "pending" + // 2. Increase retry count by 1 + // 3. Set business status to QUEUED + // 4. Schedule for immediate execution + let new_retry_count = process.retry_count + 1; + let new_schedule_time = common_utils::date_time::now() + time::Duration::hours(1); + + let pt_update = storage::ProcessTrackerUpdate::Update { + name: Some(task.to_string()), + retry_count: Some(new_retry_count), + schedule_time: Some(new_schedule_time), + tracking_data: Some(process.clone().tracking_data), + business_status: Some(String::from(business_status::PENDING)), + status: Some(common_enums::ProcessTrackerStatus::Pending), + updated_at: Some(common_utils::date_time::now()), + }; + + db.update_process(process.clone(), pt_update) + .await + .change_context(errors::RecoveryError::ProcessTrackerFailure) + .attach_printable("Failed to update CALCULATE_WORKFLOW process tracker")?; + + logger::info!( + payment_id = %id.get_string_repr(), + process_tracker_id = %process_tracker_id, + new_retry_count = new_retry_count, + new_schedule_time = %new_schedule_time, + "Successfully reopened CALCULATE_WORKFLOW with increased retry count" + ); + } + None => { + logger::info!( + payment_id = %id.get_string_repr(), + process_tracker_id = %process_tracker_id, + "CALCULATE_WORKFLOW process tracker not found, creating new entry" + ); + + // Create tracking data for the new CALCULATE_WORKFLOW + let tracking_data = create_calculate_workflow_tracking_data( + payment_intent, + revenue_recovery_payment_data, + )?; + + // Call the existing perform_calculate_workflow function + perform_calculate_workflow( + state, + process, + profile, + merchant_context, + &tracking_data, + revenue_recovery_payment_data, + payment_intent, + ) + .await + .change_context(errors::RecoveryError::ProcessTrackerFailure) + .attach_printable("Failed to perform calculate workflow")?; + + logger::info!( + payment_id = %id.get_string_repr(), + process_tracker_id = %process_tracker_id, + "Successfully created new CALCULATE_WORKFLOW entry using perform_calculate_workflow" + ); + } + } + + Ok(()) +} + +/// Create tracking data for the CALCULATE_WORKFLOW +fn create_calculate_workflow_tracking_data( + payment_intent: &PaymentIntent, + revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, +) -> RecoveryResult<storage::revenue_recovery::RevenueRecoveryWorkflowTrackingData> { + let tracking_data = storage::revenue_recovery::RevenueRecoveryWorkflowTrackingData { + merchant_id: revenue_recovery_payment_data + .merchant_account + .get_id() + .clone(), + profile_id: revenue_recovery_payment_data.profile.get_id().clone(), + global_payment_id: payment_intent.id.clone(), + payment_attempt_id: payment_intent + .active_attempt_id + .clone() + .ok_or(storage_impl::errors::RecoveryError::ValueNotFound)?, + billing_mca_id: revenue_recovery_payment_data.billing_mca.get_id().clone(), + revenue_recovery_retry: revenue_recovery_payment_data.retry_algorithm, + invoice_scheduled_time: None, // Will be set by perform_calculate_workflow + }; + + Ok(tracking_data) +} + // TODO: Move these to impl based functions async fn record_back_to_billing_connector( state: &SessionState, diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs index 5f00dd0c5f2..9238b30723f 100644 --- a/crates/router/src/core/webhooks/recovery_incoming.rs +++ b/crates/router/src/core/webhooks/recovery_incoming.rs @@ -7,19 +7,25 @@ use common_utils::{ }; use diesel_models::process_tracker as storage; use error_stack::{report, ResultExt}; +use futures::stream::SelectNextSome; use hyperswitch_domain_models::{ - payments as domain_payments, revenue_recovery, router_data_v2::flow_common_types, - router_flow_types, router_request_types::revenue_recovery as revenue_recovery_request, - router_response_types::revenue_recovery as revenue_recovery_response, types as router_types, + payments as domain_payments, + revenue_recovery::{self, RecoveryPaymentIntent}, + router_data_v2::flow_common_types, + router_flow_types, + router_request_types::revenue_recovery as revenue_recovery_request, + router_response_types::revenue_recovery as revenue_recovery_response, + types as router_types, }; use hyperswitch_interfaces::webhooks as interface_webhooks; use masking::{PeekInterface, Secret}; use router_env::{instrument, logger, tracing}; use services::kafka; +use storage::business_status; use crate::{ core::{ - admin, + self, admin, errors::{self, CustomResult}, payments::{self, helpers}, }, @@ -232,6 +238,7 @@ async fn handle_monitoring_threshold( } Ok(webhooks::WebhookResponseTracker::NoEffect) } + #[allow(clippy::too_many_arguments)] async fn handle_schedule_failed_payment( billing_connector_account: &domain::MerchantConnectorAccount, @@ -248,6 +255,8 @@ async fn handle_schedule_failed_payment( ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { let (recovery_attempt_from_payment_attempt, recovery_intent_from_payment_attempt) = payment_attempt_with_recovery_intent; + + // When intent_retry_count is less than or equal to threshold (intent_retry_count <= mca_retry_threshold) .then(|| { logger::error!( @@ -258,12 +267,13 @@ async fn handle_schedule_failed_payment( Ok(webhooks::WebhookResponseTracker::NoEffect) }) .async_unwrap_or_else(|| async { - RevenueRecoveryAttempt::insert_execute_pcr_task( - &billing_connector_account.get_id(), - &*state.store, - merchant_context.get_merchant_account().get_id().to_owned(), - recovery_intent_from_payment_attempt.clone(), - business_profile.get_id().to_owned(), + // Call calculate_job + core::revenue_recovery::upsert_calculate_pcr_task( + billing_connector_account, + state, + merchant_context, + recovery_intent_from_payment_attempt, + business_profile, intent_retry_count, recovery_attempt_from_payment_attempt .as_ref() @@ -926,6 +936,7 @@ impl RevenueRecoveryAttempt { profile_id, payment_attempt_id, revenue_recovery_retry, + invoice_scheduled_time: Some(schedule_time), }; let tag = ["PCR"]; diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rs index 81a012ba414..af84ed2170f 100644 --- a/crates/router/src/types/storage/revenue_recovery.rs +++ b/crates/router/src/types/storage/revenue_recovery.rs @@ -13,7 +13,7 @@ use masking::PeekInterface; use router_env::logger; use serde::{Deserialize, Serialize}; -use crate::{db::StorageInterface, routes::SessionState, workflows::revenue_recovery}; +use crate::{db::StorageInterface, routes::SessionState, types, workflows::revenue_recovery}; #[derive(serde::Serialize, serde::Deserialize, Debug)] pub struct RevenueRecoveryWorkflowTrackingData { pub merchant_id: id_type::MerchantId, @@ -22,6 +22,7 @@ pub struct RevenueRecoveryWorkflowTrackingData { pub payment_attempt_id: id_type::GlobalAttemptId, pub billing_mca_id: id_type::MerchantConnectorAccountId, pub revenue_recovery_retry: enums::RevenueRecoveryAlgorithmType, + pub invoice_scheduled_time: Option<time::PrimitiveDateTime>, } #[derive(Debug, Clone)] diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rs index 8f3b3f0e009..dc1d97bc422 100644 --- a/crates/router/src/workflows/revenue_recovery.rs +++ b/crates/router/src/workflows/revenue_recovery.rs @@ -114,7 +114,7 @@ impl ProcessTrackerWorkflow<SessionState> for ExecutePcrWorkflow { >( state, state.get_req_state(), - merchant_context_from_revenue_recovery_payment_data, + merchant_context_from_revenue_recovery_payment_data.clone(), revenue_recovery_payment_data.profile.clone(), payments::operations::PaymentGetIntent, request, @@ -128,6 +128,8 @@ impl ProcessTrackerWorkflow<SessionState> for ExecutePcrWorkflow { Box::pin(pcr::perform_execute_payment( state, &process, + &revenue_recovery_payment_data.profile.clone(), + merchant_context_from_revenue_recovery_payment_data.clone(), &tracking_data, &revenue_recovery_payment_data, &payment_data.payment_intent, @@ -138,6 +140,8 @@ impl ProcessTrackerWorkflow<SessionState> for ExecutePcrWorkflow { Box::pin(pcr::perform_payments_sync( state, &process, + &revenue_recovery_payment_data.profile.clone(), + merchant_context_from_revenue_recovery_payment_data.clone(), &tracking_data, &revenue_recovery_payment_data, &payment_data.payment_intent, @@ -145,6 +149,18 @@ impl ProcessTrackerWorkflow<SessionState> for ExecutePcrWorkflow { .await?; Ok(()) } + Some("CALCULATE_WORKFLOW") => { + Box::pin(pcr::perform_calculate_workflow( + state, + &process, + &revenue_recovery_payment_data.profile.clone(), + merchant_context_from_revenue_recovery_payment_data, + &tracking_data, + &revenue_recovery_payment_data, + &payment_data.payment_intent, + )) + .await + } _ => Err(errors::ProcessTrackerError::JobNotFound), }
2025-08-06T03:26: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 --> **CALCULATE WORKFLOW** CALCULATE WORKFLOW When we receive failed webhook and its intent retry count is more than the threshold, it will inserted into calculate job with the schedule time with 1 hour from now, before inserting it will first check the DB for existing entry for CALCULATE_WORKFLOW_{payment_intent}, If found and business_status is CALCULATE_WORKFLOW_QUEUED, then we just update the existing entry with scheduled time with plus hour. If found and business_status is not CALCULATE_WORKFLOW_QUEUED, we do not insert the entry If not found, make a new entry with scheduled time as 1 hour plus from now time and feed token list from payment_intent to tracking_data Introduced one new field in tracking_data Invoice_scheduled_time Option (used as scheduling time in execute workflow and as well as for dashboard purpose) At the scheduled time, consumer picks it up and perform tasks like:- Call a function(best_token_with_time() ) that returns Option<{(token, scheduled_time)}> We pass scheduled time in tracking_data as well as pass in insert_execute_task_to_pt so that we can schedule EXECUTE WORKFLOW at that time, we change calculate flow's the business_status to CALCULATE_WORKFLOW_SCHEDULED and status as Finish also lock the customer of that active token with redis fn call. If we receive None from best_token_with_time(), then we call get_payment_processor_token_with_schedule_time() whose return type is also Option<{PSPstatusdetails}>, if this is Some() then we just requeue it with wait time return by this fn, and add 15 minutes as buffer time and update the business_status as CALCULATE_WORKFLOW_QUEUED, else if it returns None then we mark the invoice as finish and finish the calculate workflow since this is a HARD DECLINE. EXECUTE WORKFLOW When the consumer picks up the execute task, it tries to do payment by calling proxy_api at the scheduled_time, here we have three possibilities for response of payment:- Success:- Update the token with success status and also update calculate_workflow entry’s business_status to CALCULATE_WORKFLOW_COMPLETED and status to Finish and also unlock the customer with redis fn call and change the status of token to success in redis. Failure:- Finish the task by updating the status to Finish and business status to EXECUTE_WORKFLOW_FINISH, increment the retry count by 1 and also unlock the customer with redis fn call, then find the calculate job for the id, and update its the business status to CALCULATE_WORKFLOW_QUEUED and scheduled time to now() + 1 hr Pending:- Will call PSYNC, update the business status of calculate job to CALCULATE_WORKFLOW_PROCESSING PSYNC WORKFLOW When the consumer picks up the psync task, here we have three possibilities:- Success:- Update the token with success status and also update calculate_workflow entry’s business_status to CALCULATE_WORKFLOW_COMPLETED and status to Finish. Failure:- Finish the task by updating the status to Finish and business status to EXECUTE_WORKFLOW_FINISH and also increment the retry count by 1, find the calculate job for the id, and update the business status to CALCULATE_WORKFLOW_QUEUED and scheduled time to now() + 1 hr Pending:- Will call PSYNC, update the business status of calculate job to CALCULATE_WORKFLOW_PROCESSING <img width="1530" height="308" alt="Screenshot 2025-08-13 at 16 42 06" src="https://github.com/user-attachments/assets/bc598e19-4404-4d1f-b736-be73501a5464" /> ### 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)? --> How to test invoice queuing and card switching: Create a business profile - where the default revenue_recovery_algorithm_type would be Monitoring by default. (Need to update it to Cascading and Smart and test the flows. Create a Payment Processor (worldpayvantiv) ```curl --location 'http://localhost:8080/v2/connector-accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: {{}}' \ --header 'x-profile-id: {{}}' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'api-key: {{}}' \ --data ' { "connector_type": "payment_processor", "connector_name": "worldpayvantiv", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "u83996941026920501", "key1": "010193081", "api_secret": "qRfXV7aPcvkX6Fr" }, "payment_methods_enabled": [ { "payment_method_type": "card", "payment_method_subtypes": [ { "payment_method_subtype": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_subtype": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "frm_configs": null, "connector_webhook_details": { "merchant_secret": "" }, "metadata": { "report_group": "Hello", "merchant_config_currency": "USD" }, "profile_id": "pro_6BnIGqGPytQ3vwObbAw6" }' ``` Create Billing Processor for custom billing ```curl --location 'http://localhost:8080/v2/connector-accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: {{}}' \ --header 'x-profile-id: {{}}' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'api-key: {{}}' \ --data '{ "connector_type": "billing_processor", "connector_name": "custombilling", "connector_account_details": { "auth_type": "NoKey" }, "feature_metadata" : { "revenue_recovery" : { "max_retry_count" : 9, "billing_connector_retry_threshold" : 0, "billing_account_reference" :{ "{{connector_mca_id}}" : "{{connector_mca_id}}" }, "switch_payment_method_config" : { "retry_threshold" : 0, "time_threshold_after_creation": 0 } } }, "profile_id": "pro_6BnIGqGPytQ3vwObbAw6" }' ``` Use the payment/recovery api ```curl --location 'http://localhost:8080/v2/payments/recovery' \ --header 'Authorization: api-key=dev_qHo39mf1hdLbY7GW7FOr89FaoCM1NQOdwPddWguUDI3RnsjQKPzG71uZIkuULDQu' \ --header 'x-profile-id: pro_xsbw9tuM9f6whrwaZKC2' \ --header 'x-merchant-id: cloth_seller_2px3Q1TUxtGOvO3Yzm0S' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_qHo39mf1hdLbY7GW7FOr89FaoCM1NQOdwPddWguUDI3RnsjQKPzG71uZIkuULDQu' \ --data '{ "amount_details": { "order_amount": 2250, "currency": "USD" }, "merchant_reference_id": "1234567891", "connector_transaction_id": "43255654", "connector_customer_id": "526755", "error": { "code": "110", "message": "Insufficient Funds" }, "billing": { "address": { "state": "CA", "country": "US" } }, "payment_method_type": "card", "payment_method_sub_type": "credit", "payment_method_data": { "primary_processor_payment_method_token": "2541911049890008", "additional_payment_method_info": { "card_exp_month": "12", "card_exp_year": "25", "last_four_digits": 1997, "card_network": "VISA", "card_issuer": "Wells Fargo NA", "card_type": "credit" } }, "billing_started_at": "2024-05-29T08:10:58Z", "transaction_created_at": "2024-05-29T08:10:58Z", "attempt_status": "failure", "action": "schedule_failed_payment", "billing_merchant_connector_id": "mca_6y5xtQUL2tgnHbjS7Bai", "payment_merchant_connector_id": "mca_OWLpnzoAxkhT1eZVJ3Q3" }' ``` We need to hit recovery api curl multiple times by changing, here merchant reference is invoice_id : "merchant_reference_id": "1234567891", "connector_transaction_id": "43255654", "connector_customer_id": "526755", There should be entry in the process tracker only when the retries exceed the threshold. In the given curl we have kept the retry threshold as 0. Redis will contain keys <img width="721" height="117" alt="Screenshot 2025-08-25 at 18 04 14" src="https://github.com/user-attachments/assets/2ce5a60f-a537-41f3-8c9c-33a510337b77" /> Cascading When the profile is in CASCADING phase, the decider should not be called(gRPC call). It should take the retry date from config and schedule accordingly. Process Tracker entry (Calculate Job) : <img width="688" height="138" alt="Screenshot 2025-08-25 at 18 05 02" src="https://github.com/user-attachments/assets/2a0abbc8-d40f-40bb-adcd-f6ce9e2ed6a2" /> Process Tracker (Execute Job) : <img width="684" height="150" alt="Screenshot 2025-08-25 at 18 05 35" src="https://github.com/user-attachments/assets/689c47b9-3cc9-456c-b212-1b48c3076f07" /> At the scheduled time proxy api is called. <img width="690" height="264" alt="Screenshot 2025-08-25 at 18 06 11" src="https://github.com/user-attachments/assets/1097d92c-64b8-4023-aebc-b140dabcaa72" /> After which if payment is successful- Psync flow triggered <img width="686" height="234" alt="Screenshot 2025-08-25 at 18 07 52" src="https://github.com/user-attachments/assets/6dfa5a86-44f9-415f-84ac-34a5205096ed" /> And end with business_status as global failure on succeeded status in psync call. Smart When the profile is in SMART phase, the decider should be called(gRPC call). Process Tracker entry (Calculate Job) : <img width="687" height="239" alt="Screenshot 2025-08-25 at 18 08 18" src="https://github.com/user-attachments/assets/32d47ab0-4a99-4efe-a25f-71bddaab0da0" /> Process Tracker (Execute Job) : <img width="685" height="248" alt="Screenshot 2025-08-25 at 18 08 40" src="https://github.com/user-attachments/assets/e8a1a97b-45f6-4c8e-83dc-1cc2a79e04de" /> Process Tracker status after Proxy call Process Tracker (Execute Job) : <img width="682" height="236" alt="Screenshot 2025-08-25 at 18 10 07" src="https://github.com/user-attachments/assets/a9b60a59-a4ac-481d-8cba-487e4be582f2" /> Process Tracker (Psync Flow ) <img width="680" height="242" alt="Screenshot 2025-08-25 at 18 10 34" src="https://github.com/user-attachments/assets/f4e741a2-38fb-45c2-aaea-03beef0386ed" /> In psync job, if we get a response as failed from connector The calculate job is reopened . ## 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.116.0
0b59b9086cd68eef346413a27d03fa61fb6bb1f7
0b59b9086cd68eef346413a27d03fa61fb6bb1f7
juspay/hyperswitch
juspay__hyperswitch-8860
Bug: [CI] Add mock credentials for alpha connectors in CI updating the creds for alpha connectors makes no sense. we've complete control over the alpha connector's behavior. so, better add a mock / fake credentials that mimic this behavior.
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 83544e40cc1..160a29aa1a3 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -1446,6 +1446,35 @@ merchant_id_evoucher="MerchantId Evoucher" [cashtocode.connector_webhook_details] merchant_secret="Source verification key" +[celero] +[[celero.credit]] + payment_method_type = "AmericanExpress" +[[celero.credit]] + payment_method_type = "Discover" +[[celero.credit]] + payment_method_type = "DinersClub" +[[celero.credit]] + payment_method_type = "JCB" +[[celero.credit]] + payment_method_type = "Mastercard" +[[celero.credit]] + payment_method_type = "Visa" +[[celero.debit]] + payment_method_type = "AmericanExpress" +[[celero.debit]] + payment_method_type = "Discover" +[[celero.debit]] + payment_method_type = "DinersClub" +[[celero.debit]] + payment_method_type = "JCB" +[[celero.debit]] + payment_method_type = "Mastercard" +[[celero.debit]] + payment_method_type = "Visa" +[celero.connector_auth.HeaderKey] +api_key="Celero API Key" + + [checkbook] [[checkbook.bank_transfer]] payment_method_type = "ach" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 019d842b8d1..47aff66d845 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -1212,6 +1212,34 @@ key1 = "Secret Key" [cryptopay.connector_webhook_details] merchant_secret = "Source verification key" +[celero] +[[celero.credit]] + payment_method_type = "AmericanExpress" +[[celero.credit]] + payment_method_type = "Discover" +[[celero.credit]] + payment_method_type = "DinersClub" +[[celero.credit]] + payment_method_type = "JCB" +[[celero.credit]] + payment_method_type = "Mastercard" +[[celero.credit]] + payment_method_type = "Visa" +[[celero.debit]] + payment_method_type = "AmericanExpress" +[[celero.debit]] + payment_method_type = "Discover" +[[celero.debit]] + payment_method_type = "DinersClub" +[[celero.debit]] + payment_method_type = "JCB" +[[celero.debit]] + payment_method_type = "Mastercard" +[[celero.debit]] + payment_method_type = "Visa" +[celero.connector_auth.HeaderKey] +api_key="Celero API Key" + [checkbook] [[checkbook.bank_transfer]] payment_method_type = "ach" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 8571315082e..d1ea6ba609f 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -1445,6 +1445,35 @@ merchant_id_evoucher = "MerchantId Evoucher" [cashtocode.connector_webhook_details] merchant_secret = "Source verification key" +[celero] +[[celero.credit]] + payment_method_type = "AmericanExpress" +[[celero.credit]] + payment_method_type = "Discover" +[[celero.credit]] + payment_method_type = "DinersClub" +[[celero.credit]] + payment_method_type = "JCB" +[[celero.credit]] + payment_method_type = "Mastercard" +[[celero.credit]] + payment_method_type = "Visa" +[[celero.debit]] + payment_method_type = "AmericanExpress" +[[celero.debit]] + payment_method_type = "Discover" +[[celero.debit]] + payment_method_type = "DinersClub" +[[celero.debit]] + payment_method_type = "JCB" +[[celero.debit]] + payment_method_type = "Mastercard" +[[celero.debit]] + payment_method_type = "Visa" +[celero.connector_auth.HeaderKey] +api_key="Celero API Key" + + [checkbook] [[checkbook.bank_transfer]] payment_method_type = "ach" diff --git a/crates/hyperswitch_connectors/src/connectors/celero.rs b/crates/hyperswitch_connectors/src/connectors/celero.rs index 9db111a10e4..726791a72eb 100644 --- a/crates/hyperswitch_connectors/src/connectors/celero.rs +++ b/crates/hyperswitch_connectors/src/connectors/celero.rs @@ -1,10 +1,13 @@ pub mod transformers; +use std::sync::LazyLock; + +use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, - types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, + types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ @@ -19,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, RefundSyncRouterData, RefundsRouterData, @@ -43,13 +49,13 @@ use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Clone)] pub struct Celero { - amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Celero { pub fn new() -> &'static Self { &Self { - amount_converter: &StringMinorUnitForConnector, + amount_converter: &MinorUnitForConnector, } } } @@ -98,10 +104,7 @@ impl ConnectorCommon for Celero { } fn get_currency_unit(&self) -> api::CurrencyUnit { - api::CurrencyUnit::Base - // TODO! Check connector documentation, on which unit they are processing the currency. - // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, - // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base + api::CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { @@ -137,23 +140,53 @@ impl ConnectorCommon for Celero { event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + // Extract error details from the response + let error_details = celero::CeleroErrorDetails::from(response); + Ok(ErrorResponse { status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, + code: error_details + .error_code + .unwrap_or_else(|| "UNKNOWN_ERROR".to_string()), + message: error_details.error_message, + reason: error_details.decline_reason, attempt_status: None, connector_transaction_id: None, - network_decline_code: None, + network_decline_code: error_details.processor_response_code.clone(), network_advice_code: None, - network_error_message: None, + network_error_message: error_details.processor_response_code, connector_metadata: None, }) } } impl ConnectorValidation for Celero { - //TODO: implement functions when support enabled + 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(); + + // CeleroCommerce supports both automatic (sale) and manual (authorize + capture) flows + let is_capture_method_supported = matches!( + capture_method, + enums::CaptureMethod::Automatic + | enums::CaptureMethod::Manual + | enums::CaptureMethod::SequentialAutomatic + ); + + if is_capture_method_supported { + Ok(()) + } else { + Err(errors::ConnectorError::NotSupported { + message: capture_method.to_string(), + connector: self.id(), + } + .into()) + } + } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Celero { @@ -180,9 +213,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!("{}/api/transaction", self.base_url(connectors))) } fn get_request_body( @@ -196,7 +229,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req.request.currency, )?; - let connector_router_data = celero::CeleroRouterData::from((amount, req)); + let connector_router_data = celero::CeleroRouterData::try_from((amount, req))?; let connector_req = celero::CeleroPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -267,9 +300,22 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cel fn get_url( &self, _req: &PaymentsSyncRouterData, - _connectors: &Connectors, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + // CeleroCommerce uses search API for payment sync + Ok(format!( + "{}/api/transaction/search", + self.base_url(connectors) + )) + } + + fn get_request_body( + &self, + req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = celero::CeleroSearchRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( @@ -279,10 +325,13 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cel ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() - .method(Method::Get) + .method(Method::Post) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .set_body(types::PaymentsSyncType::get_request_body( + self, req, connectors, + )?) .build(), )) } @@ -330,18 +379,31 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo fn get_url( &self, - _req: &PaymentsCaptureRouterData, - _connectors: &Connectors, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let connector_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}/api/transaction/{}/capture", + self.base_url(connectors), + connector_payment_id + )) } fn get_request_body( &self, - _req: &PaymentsCaptureRouterData, + req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount_to_capture, + req.request.currency, + )?; + + let connector_router_data = celero::CeleroRouterData::try_from((amount, req))?; + let connector_req = celero::CeleroCaptureRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( @@ -370,7 +432,7 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { - let response: celero::CeleroPaymentsResponse = res + let response: celero::CeleroCaptureResponse = res .response .parse_struct("Celero PaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -392,7 +454,77 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo } } -impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Celero {} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Celero { + fn get_headers( + &self, + req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>, + 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: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let connector_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}/api/transaction/{}/void", + self.base_url(connectors), + connector_payment_id + )) + } + + fn build_request( + &self, + req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult< + RouterData<Void, PaymentsCancelData, PaymentsResponseData>, + errors::ConnectorError, + > { + let response: celero::CeleroVoidResponse = res + .response + .parse_struct("Celero PaymentsVoidResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Celero { fn get_headers( @@ -409,10 +541,15 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Celero fn get_url( &self, - _req: &RefundsRouterData<Execute>, - _connectors: &Connectors, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let connector_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}/api/transaction/{}/refund", + self.base_url(connectors), + connector_payment_id + )) } fn get_request_body( @@ -426,7 +563,7 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Celero req.request.currency, )?; - let connector_router_data = celero::CeleroRouterData::from((refund_amount, req)); + let connector_router_data = celero::CeleroRouterData::try_from((refund_amount, req))?; let connector_req = celero::CeleroRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -456,10 +593,10 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Celero event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { - let response: celero::RefundResponse = - res.response - .parse_struct("celero RefundResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let response: celero::CeleroRefundResponse = res + .response + .parse_struct("celero 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 { @@ -494,9 +631,22 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Celero { fn get_url( &self, _req: &RefundSyncRouterData, - _connectors: &Connectors, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + // CeleroCommerce uses search API for refund sync + Ok(format!( + "{}/api/transaction/search", + self.base_url(connectors) + )) + } + + fn get_request_body( + &self, + req: &RefundSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = celero::CeleroSearchRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( @@ -506,7 +656,7 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Celero { ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() - .method(Method::Get) + .method(Method::Post) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) @@ -523,7 +673,7 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Celero { event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { - let response: celero::RefundResponse = res + let response: celero::CeleroRefundResponse = res .response .parse_struct("celero RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -569,4 +719,80 @@ impl webhooks::IncomingWebhook for Celero { } } -impl ConnectorSpecifications for Celero {} +static CELERO_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::AmericanExpress, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + ]; + + let mut celero_supported_payment_methods = SupportedPaymentMethods::new(); + + celero_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(), + } + }), + ), + }, + ); + + celero_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(), + } + }), + ), + }, + ); + + celero_supported_payment_methods +}); + +static CELERO_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Celero", + description: "Celero is your trusted provider for payment processing technology and solutions, with a commitment to helping small to mid-sized businesses thrive", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; + +impl ConnectorSpecifications for Celero { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&CELERO_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*CELERO_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + None + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/celero/transformers.rs b/crates/hyperswitch_connectors/src/connectors/celero/transformers.rs index 2579c81ae6b..76990260923 100644 --- a/crates/hyperswitch_connectors/src/connectors/celero/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/celero/transformers.rs @@ -1,80 +1,260 @@ -use common_enums::enums; -use common_utils::types::StringMinorUnit; +use common_enums::{enums, Currency}; +use common_utils::{pii::Email, types::MinorUnit}; use hyperswitch_domain_models::{ + address::Address as DomainAddress, payment_method_data::PaymentMethodData, - router_data::{ConnectorAuthType, RouterData}, - router_flow_types::refunds::{Execute, RSync}, - router_request_types::ResponseId, + router_data::{ + AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, + RouterData, + }, + router_flow_types::{ + payments::Capture, + refunds::{Execute, RSync}, + }, + router_request_types::{PaymentsCaptureData, ResponseId}, router_response_types::{PaymentsResponseData, RefundsResponseData}, - types::{PaymentsAuthorizeRouterData, RefundsRouterData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundSyncRouterData, RefundsRouterData, + }, }; -use hyperswitch_interfaces::errors; -use masking::Secret; +use hyperswitch_interfaces::{consts, errors}; +use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, - utils::PaymentsAuthorizeRequestData, + utils::{ + AddressDetailsData, PaymentsAuthorizeRequestData, RefundsRequestData, RouterData as _, + }, }; //TODO: Fill the struct with respective fields pub struct CeleroRouterData<T> { - pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub amount: MinorUnit, // CeleroCommerce expects integer cents pub router_data: T, } -impl<T> From<(StringMinorUnit, T)> for CeleroRouterData<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 { +impl<T> TryFrom<(MinorUnit, T)> for CeleroRouterData<T> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> { + Ok(Self { amount, router_data: item, - } + }) } } +// CeleroCommerce Search Request for sync operations - POST /api/transaction/search +#[derive(Debug, Serialize, PartialEq)] +pub struct CeleroSearchRequest { + transaction_id: String, +} -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, PartialEq)] +impl TryFrom<&PaymentsSyncRouterData> for CeleroSearchRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> { + let transaction_id = match &item.request.connector_transaction_id { + ResponseId::ConnectorTransactionId(id) => id.clone(), + _ => { + return Err(errors::ConnectorError::MissingConnectorTransactionID.into()); + } + }; + Ok(Self { transaction_id }) + } +} + +impl TryFrom<&RefundSyncRouterData> for CeleroSearchRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> { + Ok(Self { + transaction_id: item.request.get_connector_refund_id()?, + }) + } +} + +// CeleroCommerce Payment Request according to API specs +#[derive(Debug, Serialize, PartialEq)] pub struct CeleroPaymentsRequest { - amount: StringMinorUnit, - card: CeleroCard, + idempotency_key: String, + #[serde(rename = "type")] + transaction_type: TransactionType, + amount: MinorUnit, // CeleroCommerce expects integer cents + currency: Currency, + payment_method: CeleroPaymentMethod, + #[serde(skip_serializing_if = "Option::is_none")] + billing_address: Option<CeleroAddress>, + #[serde(skip_serializing_if = "Option::is_none")] + shipping_address: Option<CeleroAddress>, + #[serde(skip_serializing_if = "Option::is_none")] + create_vault_record: Option<bool>, +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct CeleroAddress { + first_name: Option<Secret<String>>, + last_name: Option<Secret<String>>, + address_line_1: Option<Secret<String>>, + address_line_2: Option<Secret<String>>, + city: Option<String>, + state: Option<Secret<String>>, + postal_code: Option<Secret<String>>, + country: Option<common_enums::CountryAlpha2>, + phone: Option<Secret<String>>, + email: Option<Email>, } -#[derive(Default, Debug, Serialize, Eq, PartialEq)] +impl TryFrom<&DomainAddress> for CeleroAddress { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(address: &DomainAddress) -> Result<Self, Self::Error> { + let address_details = address.address.as_ref(); + match address_details { + Some(address_details) => Ok(Self { + first_name: address_details.get_optional_first_name(), + last_name: address_details.get_optional_last_name(), + address_line_1: address_details.get_optional_line1(), + address_line_2: address_details.get_optional_line2(), + city: address_details.get_optional_city(), + state: address_details.get_optional_state(), + postal_code: address_details.get_optional_zip(), + country: address_details.get_optional_country(), + phone: address + .phone + .as_ref() + .and_then(|phone| phone.number.clone()), + email: address.email.clone(), + }), + None => Err(errors::ConnectorError::MissingRequiredField { + field_name: "address_details", + } + .into()), + } + } +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum CeleroPaymentMethod { + Card(CeleroCard), +} + +#[derive(Debug, Serialize, PartialEq, Clone, Copy)] +#[serde(rename_all = "lowercase")] +pub enum CeleroEntryType { + Keyed, +} + +#[derive(Debug, Serialize, PartialEq)] pub struct CeleroCard { + entry_type: CeleroEntryType, number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, + expiration_date: Secret<String>, cvc: Secret<String>, - complete: bool, } -impl TryFrom<&CeleroRouterData<&PaymentsAuthorizeRouterData>> for CeleroPaymentsRequest { +impl TryFrom<&PaymentMethodData> for CeleroPaymentMethod { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: &CeleroRouterData<&PaymentsAuthorizeRouterData>, - ) -> Result<Self, Self::Error> { - match item.router_data.request.payment_method_data.clone() { + fn try_from(item: &PaymentMethodData) -> Result<Self, Self::Error> { + match item { PaymentMethodData::Card(req_card) => { let card = CeleroCard { - 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()?, + entry_type: CeleroEntryType::Keyed, + number: req_card.card_number.clone(), + expiration_date: Secret::new(format!( + "{}/{}", + req_card.card_exp_month.peek(), + req_card.card_exp_year.peek() + )), + cvc: req_card.card_cvc.clone(), }; - Ok(Self { - amount: item.amount.clone(), - card, - }) + Ok(Self::Card(card)) } - _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + PaymentMethodData::CardDetailsForNetworkTransactionId(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::MobilePayment(_) => Err(errors::ConnectorError::NotImplemented( + "Selected payment method through celero".to_string(), + ) + .into()), } } } -//TODO: Fill the struct with respective fields -// Auth Struct +// Implementation for handling 3DS specifically +impl TryFrom<(&PaymentMethodData, bool)> for CeleroPaymentMethod { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from((item, is_three_ds): (&PaymentMethodData, bool)) -> Result<Self, Self::Error> { + // If 3DS is requested, return an error + if is_three_ds { + return Err(errors::ConnectorError::NotSupported { + message: "Cards 3DS".to_string(), + connector: "celero", + } + .into()); + } + + // Otherwise, delegate to the standard implementation + Self::try_from(item) + } +} + +impl TryFrom<&CeleroRouterData<&PaymentsAuthorizeRouterData>> for CeleroPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &CeleroRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let is_auto_capture = item.router_data.request.is_auto_capture()?; + let transaction_type = if is_auto_capture { + TransactionType::Sale + } else { + TransactionType::Authorize + }; + + let billing_address: Option<CeleroAddress> = item + .router_data + .get_optional_billing() + .and_then(|address| address.try_into().ok()); + + let shipping_address: Option<CeleroAddress> = item + .router_data + .get_optional_shipping() + .and_then(|address| address.try_into().ok()); + + // Check if 3DS is requested + let is_three_ds = item.router_data.is_three_ds(); + + let request = Self { + idempotency_key: item.router_data.connector_request_reference_id.clone(), + transaction_type, + amount: item.amount, + currency: item.router_data.request.currency, + payment_method: CeleroPaymentMethod::try_from(( + &item.router_data.request.payment_method_data, + is_three_ds, + ))?, + billing_address, + shipping_address, + create_vault_record: Some(false), + }; + + Ok(request) + } +} + +// Auth Struct for CeleroCommerce API key authentication pub struct CeleroAuthType { pub(super) api_key: Secret<String>, } @@ -84,38 +264,100 @@ impl TryFrom<&ConnectorAuthType> for CeleroAuthType { 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(), + api_key: api_key.clone(), }), _ => 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 CeleroPaymentStatus { - Succeeded, - Failed, - #[default] - Processing, +// CeleroCommerce API Response Structures +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub enum CeleroResponseStatus { + #[serde(alias = "success", alias = "Success", alias = "SUCCESS")] + Success, + #[serde(alias = "error", alias = "Error", alias = "ERROR")] + Error, } -impl From<CeleroPaymentStatus> for common_enums::AttemptStatus { - fn from(item: CeleroPaymentStatus) -> Self { +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CeleroTransactionStatus { + Approved, + Declined, + Error, + Pending, + PendingSettlement, + Settled, + Voided, + Reversed, +} + +impl From<CeleroTransactionStatus> for common_enums::AttemptStatus { + fn from(item: CeleroTransactionStatus) -> Self { match item { - CeleroPaymentStatus::Succeeded => Self::Charged, - CeleroPaymentStatus::Failed => Self::Failure, - CeleroPaymentStatus::Processing => Self::Authorizing, + CeleroTransactionStatus::Approved => Self::Authorized, + CeleroTransactionStatus::Settled => Self::Charged, + CeleroTransactionStatus::Declined | CeleroTransactionStatus::Error => Self::Failure, + CeleroTransactionStatus::Pending | CeleroTransactionStatus::PendingSettlement => { + Self::Pending + } + CeleroTransactionStatus::Voided | CeleroTransactionStatus::Reversed => Self::Voided, } } } +#[serde_with::skip_serializing_none] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct CeleroCardResponse { + pub status: CeleroTransactionStatus, + pub auth_code: Option<String>, + pub processor_response_code: Option<String>, + pub avs_response_code: Option<String>, +} -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum CeleroPaymentMethodResponse { + Card(CeleroCardResponse), +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum TransactionType { + Sale, + Authorize, +} +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] +#[serde_with::skip_serializing_none] +pub struct CeleroTransactionResponseData { + pub id: String, + #[serde(rename = "type")] + pub transaction_type: TransactionType, + pub amount: i64, + pub currency: String, + pub response: CeleroPaymentMethodResponse, + pub billing_address: Option<CeleroAddressResponse>, + pub shipping_address: Option<CeleroAddressResponse>, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] +pub struct CeleroAddressResponse { + first_name: Option<Secret<String>>, + last_name: Option<Secret<String>>, + address_line_1: Option<Secret<String>>, + address_line_2: Option<Secret<String>>, + city: Option<String>, + state: Option<Secret<String>>, + postal_code: Option<Secret<String>>, + country: Option<common_enums::CountryAlpha2>, + phone: Option<Secret<String>>, + email: Option<Secret<String>>, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] pub struct CeleroPaymentsResponse { - status: CeleroPaymentStatus, - id: String, + pub status: CeleroResponseStatus, + pub msg: String, + pub data: Option<CeleroTransactionResponseData>, } impl<F, T> TryFrom<ResponseRouterData<F, CeleroPaymentsResponse, T, PaymentsResponseData>> @@ -125,104 +367,508 @@ impl<F, T> TryFrom<ResponseRouterData<F, CeleroPaymentsResponse, T, PaymentsResp fn try_from( item: ResponseRouterData<F, CeleroPaymentsResponse, 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 - }) + match item.response.status { + CeleroResponseStatus::Success => { + if let Some(data) = item.response.data { + let CeleroPaymentMethodResponse::Card(response) = &data.response; + // Check if transaction itself failed despite successful API call + match response.status { + CeleroTransactionStatus::Declined | CeleroTransactionStatus::Error => { + // Transaction failed - create error response with transaction details + let error_details = CeleroErrorDetails::from_transaction_response( + response, + item.response.msg, + ); + + Ok(Self { + status: common_enums::AttemptStatus::Failure, + response: Err( + hyperswitch_domain_models::router_data::ErrorResponse { + code: error_details + .error_code + .unwrap_or_else(|| "TRANSACTION_FAILED".to_string()), + message: error_details.error_message, + reason: error_details.decline_reason, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(data.id), + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_metadata: None, + }, + ), + ..item.data + }) + } + _ => { + let connector_response_data = + convert_to_additional_payment_method_connector_response( + response.avs_response_code.clone(), + ) + .map(ConnectorResponseData::with_additional_payment_method_data); + let final_status: enums::AttemptStatus = response.status.into(); + Ok(Self { + status: final_status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(data.id), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: response.auth_code.clone(), + incremental_authorization_allowed: None, + charges: None, + }), + connector_response: connector_response_data, + ..item.data + }) + } + } + } else { + // No transaction data in successful response + Ok(Self { + status: common_enums::AttemptStatus::Failure, + response: Err(hyperswitch_domain_models::router_data::ErrorResponse { + code: "MISSING_DATA".to_string(), + message: "No transaction data in response".to_string(), + reason: Some(item.response.msg), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: None, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_metadata: None, + }), + ..item.data + }) + } + } + CeleroResponseStatus::Error => { + // Top-level API error + let error_details = + CeleroErrorDetails::from_top_level_error(item.response.msg.clone()); + + Ok(Self { + status: common_enums::AttemptStatus::Failure, + response: Err(hyperswitch_domain_models::router_data::ErrorResponse { + code: error_details + .error_code + .unwrap_or_else(|| "API_ERROR".to_string()), + message: error_details.error_message, + reason: error_details.decline_reason, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: None, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_metadata: None, + }), + ..item.data + }) + } + } } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest +// CAPTURE: +// Type definition for CaptureRequest #[derive(Default, Debug, Serialize)] -pub struct CeleroRefundRequest { - pub amount: StringMinorUnit, +pub struct CeleroCaptureRequest { + pub amount: MinorUnit, + #[serde(skip_serializing_if = "Option::is_none")] + pub order_id: Option<String>, } -impl<F> TryFrom<&CeleroRouterData<&RefundsRouterData<F>>> for CeleroRefundRequest { +impl TryFrom<&CeleroRouterData<&PaymentsCaptureRouterData>> for CeleroCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &CeleroRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + fn try_from(item: &CeleroRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { Ok(Self { - amount: item.amount.to_owned(), + amount: item.amount, + order_id: Some(item.router_data.payment_id.clone()), }) } } -// Type definition for Refund Response - -#[allow(dead_code)] -#[derive(Debug, Serialize, Default, Deserialize, Clone)] -pub enum RefundStatus { - Succeeded, - Failed, - #[default] - Processing, +// CeleroCommerce Capture Response +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct CeleroCaptureResponse { + pub status: CeleroResponseStatus, + pub msg: Option<String>, + pub data: Option<serde_json::Value>, // Usually null for capture responses } -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 +impl + TryFrom< + ResponseRouterData< + Capture, + CeleroCaptureResponse, + PaymentsCaptureData, + PaymentsResponseData, + >, + > for RouterData<Capture, PaymentsCaptureData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + Capture, + CeleroCaptureResponse, + PaymentsCaptureData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response.status { + CeleroResponseStatus::Success => Ok(Self { + status: common_enums::AttemptStatus::Charged, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.data.request.connector_transaction_id.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 + }), + CeleroResponseStatus::Error => Ok(Self { + status: common_enums::AttemptStatus::Failure, + response: Err(hyperswitch_domain_models::router_data::ErrorResponse { + code: "CAPTURE_FAILED".to_string(), + message: item + .response + .msg + .clone() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: None, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some( + item.data.request.connector_transaction_id.clone(), + ), + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_metadata: None, + }), + ..item.data + }), } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize)] -pub struct RefundResponse { - id: String, - status: RefundStatus, +// CeleroCommerce Void Response - matches API spec format +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct CeleroVoidResponse { + pub status: CeleroResponseStatus, + pub msg: String, + pub data: Option<serde_json::Value>, // Usually null for void responses } -impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { +impl + TryFrom< + ResponseRouterData< + hyperswitch_domain_models::router_flow_types::payments::Void, + CeleroVoidResponse, + hyperswitch_domain_models::router_request_types::PaymentsCancelData, + PaymentsResponseData, + >, + > + for RouterData< + hyperswitch_domain_models::router_flow_types::payments::Void, + hyperswitch_domain_models::router_request_types::PaymentsCancelData, + PaymentsResponseData, + > +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: RefundsResponseRouterData<Execute, RefundResponse>, + item: ResponseRouterData< + hyperswitch_domain_models::router_flow_types::payments::Void, + CeleroVoidResponse, + hyperswitch_domain_models::router_request_types::PaymentsCancelData, + PaymentsResponseData, + >, ) -> 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.status { + CeleroResponseStatus::Success => Ok(Self { + status: common_enums::AttemptStatus::Voided, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.data.request.connector_transaction_id.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 + }), + CeleroResponseStatus::Error => Ok(Self { + status: common_enums::AttemptStatus::Failure, + response: Err(hyperswitch_domain_models::router_data::ErrorResponse { + code: "VOID_FAILED".to_string(), + message: item.response.msg.clone(), + reason: Some(item.response.msg), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some( + item.data.request.connector_transaction_id.clone(), + ), + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_metadata: None, + }), + ..item.data }), - ..item.data + } + } +} +#[derive(Default, Debug, Serialize)] +pub struct CeleroRefundRequest { + pub amount: MinorUnit, + pub surcharge: MinorUnit, // Required field as per API specification +} + +impl<F> TryFrom<&CeleroRouterData<&RefundsRouterData<F>>> for CeleroRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &CeleroRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount, + surcharge: MinorUnit::zero(), // Default to 0 as per API specification }) } } -impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { +// CeleroCommerce Refund Response - matches API spec format +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct CeleroRefundResponse { + pub status: CeleroResponseStatus, + pub msg: String, + pub data: Option<serde_json::Value>, // Usually null for refund responses +} + +impl TryFrom<RefundsResponseRouterData<Execute, CeleroRefundResponse>> + for RefundsRouterData<Execute> +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: RefundsResponseRouterData<RSync, RefundResponse>, + item: RefundsResponseRouterData<Execute, CeleroRefundResponse>, ) -> 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.status { + CeleroResponseStatus::Success => Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.data.request.refund_id.clone(), + refund_status: enums::RefundStatus::Success, + }), + ..item.data }), - ..item.data - }) + CeleroResponseStatus::Error => Ok(Self { + response: Err(hyperswitch_domain_models::router_data::ErrorResponse { + code: "REFUND_FAILED".to_string(), + message: item.response.msg.clone(), + reason: Some(item.response.msg), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some( + item.data.request.connector_transaction_id.clone(), + ), + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_metadata: None, + }), + ..item.data + }), + } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +impl TryFrom<RefundsResponseRouterData<RSync, CeleroRefundResponse>> for RefundsRouterData<RSync> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<RSync, CeleroRefundResponse>, + ) -> Result<Self, Self::Error> { + match item.response.status { + CeleroResponseStatus::Success => Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.data.request.refund_id.clone(), + refund_status: enums::RefundStatus::Success, + }), + ..item.data + }), + CeleroResponseStatus::Error => Ok(Self { + response: Err(hyperswitch_domain_models::router_data::ErrorResponse { + code: "REFUND_SYNC_FAILED".to_string(), + message: item.response.msg.clone(), + reason: Some(item.response.msg), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some( + item.data.request.connector_transaction_id.clone(), + ), + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + connector_metadata: None, + }), + ..item.data + }), + } + } +} + +// CeleroCommerce Error Response Structures + +// Main error response structure - matches API spec format +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct CeleroErrorResponse { - pub status_code: u16, - pub code: String, - pub message: String, - pub reason: Option<String>, + pub status: CeleroResponseStatus, + pub msg: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub data: Option<serde_json::Value>, +} + +// Error details that can be extracted from various response fields +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct CeleroErrorDetails { + pub error_code: Option<String>, + pub error_message: String, + pub processor_response_code: Option<String>, + pub decline_reason: Option<String>, +} + +impl From<CeleroErrorResponse> for CeleroErrorDetails { + fn from(error_response: CeleroErrorResponse) -> Self { + Self { + error_code: Some("API_ERROR".to_string()), + error_message: error_response.msg, + processor_response_code: None, + decline_reason: None, + } + } +} + +// Function to extract error details from transaction response data +impl CeleroErrorDetails { + pub fn from_transaction_response(response: &CeleroCardResponse, msg: String) -> Self { + // Map specific error codes based on common response patterns + let decline_reason = Self::map_processor_error(&response.processor_response_code, &msg); + + Self { + error_code: None, + error_message: msg, + processor_response_code: response.processor_response_code.clone(), + decline_reason, + } + } + + pub fn from_top_level_error(msg: String) -> Self { + // Map specific error codes from top-level API errors + + Self { + error_code: None, + error_message: msg, + processor_response_code: None, + decline_reason: None, + } + } + + /// Map processor response codes and messages to specific Hyperswitch error codes + fn map_processor_error(processor_code: &Option<String>, message: &str) -> Option<String> { + let message_lower = message.to_lowercase(); + // Check processor response codes if available + if let Some(code) = processor_code { + match code.as_str() { + "05" => Some("TRANSACTION_DECLINED".to_string()), + "14" => Some("INVALID_CARD_DATA".to_string()), + "51" => Some("INSUFFICIENT_FUNDS".to_string()), + "54" => Some("EXPIRED_CARD".to_string()), + "55" => Some("INCORRECT_CVC".to_string()), + "61" => Some("Exceeds withdrawal amount limit".to_string()), + "62" => Some("TRANSACTION_DECLINED".to_string()), + "65" => Some("Exceeds withdrawal frequency limit".to_string()), + "78" => Some("INVALID_CARD_DATA".to_string()), + "91" => Some("PROCESSING_ERROR".to_string()), + "96" => Some("PROCESSING_ERROR".to_string()), + _ => { + router_env::logger::info!( + "Celero response error code ({:?}) is not mapped to any error state ", + code + ); + Some("Transaction failed".to_string()) + } + } + } else { + Some(message_lower) + } + } +} + +pub fn get_avs_definition(code: &str) -> Option<&'static str> { + match code { + "0" => Some("AVS Not Available"), + "A" => Some("Address match only"), + "B" => Some("Address matches, ZIP not verified"), + "C" => Some("Incompatible format"), + "D" => Some("Exact match"), + "F" => Some("Exact match, UK-issued cards"), + "G" => Some("Non-U.S. Issuer does not participate"), + "I" => Some("Not verified"), + "M" => Some("Exact match"), + "N" => Some("No address or ZIP match"), + "P" => Some("Postal Code match"), + "R" => Some("Issuer system unavailable"), + "S" => Some("Service not supported"), + "U" => Some("Address unavailable"), + "W" => Some("9-character numeric ZIP match only"), + "X" => Some("Exact match, 9-character numeric ZIP"), + "Y" => Some("Exact match, 5-character numeric ZIP"), + "Z" => Some("5-character ZIP match only"), + "L" => Some("Partial match, Name and billing postal code match"), + "1" => Some("Cardholder name and ZIP match"), + "2" => Some("Cardholder name, address and ZIP match"), + "3" => Some("Cardholder name and address match"), + "4" => Some("Cardholder name matches"), + "5" => Some("Cardholder name incorrect, ZIP matches"), + "6" => Some("Cardholder name incorrect, address and zip match"), + "7" => Some("Cardholder name incorrect, address matches"), + "8" => Some("Cardholder name, address, and ZIP do not match"), + _ => { + router_env::logger::info!( + "Celero avs response code ({:?}) is not mapped to any defination.", + code + ); + + None + } // No definition found for the given code + } +} +fn convert_to_additional_payment_method_connector_response( + response_code: Option<String>, +) -> Option<AdditionalPaymentMethodConnectorResponse> { + match response_code { + None => None, + Some(code) => { + let description = get_avs_definition(&code); + let payment_checks = serde_json::json!({ + "avs_result_code": code, + "description": description + }); + Some(AdditionalPaymentMethodConnectorResponse::Card { + authentication_data: None, + payment_checks: Some(payment_checks), + card_network: None, + domestic_network: None, + }) + } + } } diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs index 5ce306c5976..15a4ef90a95 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -1305,6 +1305,7 @@ fn get_cards_required_fields() -> HashMap<Connector, RequiredFieldFinal> { ), (Connector::Boku, fields(vec![], vec![], card_basic())), (Connector::Braintree, fields(vec![], vec![], card_basic())), + (Connector::Celero, fields(vec![], vec![], card_basic())), (Connector::Checkout, fields(vec![], card_basic(), vec![])), ( Connector::Coinbase,
2025-07-08T05:02:05Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Integrate celero commerce connector Doc : https://sandbox.gotnpgateway.com/docs/api/transactions [x] Cards [x] Avs ### 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` --> MOCK SERVER results <img width="803" height="920" alt="Screenshot 2025-08-05 at 11 37 29β€―AM" src="https://github.com/user-attachments/assets/19bee0c6-f0e4-4123-b423-b959c229899b" /> <img width="560" height="926" alt="Screenshot 2025-08-05 at 11 37 38β€―AM" src="https://github.com/user-attachments/assets/2e9c08e7-aba4-4799-b3b5-4a0f3df9360e" /> <img width="930" height="1001" alt="Screenshot 2025-08-05 at 11 37 54β€―AM" src="https://github.com/user-attachments/assets/e8b202e1-a5a0-4afe-8574-93944b61d816" /> ![Uploading Screenshot 2025-08-06 at 3.00.16β€―PM.png…]() ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with 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/8575 ## 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 creds for testing ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible
v1.116.0
a56d78a46a3ee80cdb2b48f9abfd2cd7b297e328
a56d78a46a3ee80cdb2b48f9abfd2cd7b297e328
juspay/hyperswitch
juspay__hyperswitch-8859
Bug: feat(api): Adds support to change reveue_recovery_retry_algorithm_type using UpdateProfileAPI (V2) Add support to change `reveue_recovery_retry_algorithm_type` through ProfileUpdateAPI
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 22c1868f6ac..e7df178c1ed 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -2989,6 +2989,11 @@ pub struct ProfileUpdate { /// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior. #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, + + /// Inidcates the state of revenue recovery algorithm type + #[schema(value_type = Option<RevenueRecoveryAlgorithmType>, example = "cascading")] + pub revenue_recovery_retry_algorithm_type: + Option<common_enums::enums::RevenueRecoveryAlgorithmType>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index c5a78c6f39f..0afe3402954 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -1363,6 +1363,7 @@ pub struct ProfileGeneralUpdate { pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, + pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>, } #[cfg(feature = "v2")] @@ -1443,6 +1444,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { external_vault_connector_details, merchant_category_code, merchant_country_code, + revenue_recovery_retry_algorithm_type, } = *update; Self { profile_name, @@ -1489,7 +1491,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_clear_pan_retries_enabled: None, is_debit_routing_enabled, merchant_business_country, - revenue_recovery_retry_algorithm_type: None, + revenue_recovery_retry_algorithm_type, revenue_recovery_retry_algorithm_data: None, is_iframe_redirection_enabled, is_external_vault_enabled, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index c116f266dfe..9068aa2ba0d 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -4074,6 +4074,8 @@ impl ProfileUpdateBridge for api::ProfileUpdate { } }; + let revenue_recovery_retry_algorithm_type = self.revenue_recovery_retry_algorithm_type; + Ok(domain::ProfileUpdate::Update(Box::new( domain::ProfileGeneralUpdate { profile_name: self.profile_name, @@ -4123,6 +4125,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { .map(ForeignInto::foreign_into), merchant_category_code: self.merchant_category_code, merchant_country_code: self.merchant_country_code, + revenue_recovery_retry_algorithm_type, }, ))) }
2025-08-06T18:04:41Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This Pr provides support to change `revenue_recovery_retry_algorithm_type` under the profile using ProfileUpdate API. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## 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 Business Profile and hit the following api. ``` curl --location --request PUT '{{base_url}}/v2/profiles/{{profile_id}}' \ --header 'x-merchant-id: {{merchant_id}}' \ --header 'Authorization: {{admin_api_key}}' \ --header 'Content-Type: application/json' \ --header 'api-key: {{admin-api-key}}' \ --data '{ "revenue_recovery_retry_algorithm_type": "monitoring" }' ``` And verify the `revenue_recovery_retry_algorithm_type` status of the Business Profile In the DB. ## 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.115.0
e2bfce8974dec9348d5829c39ad1f9acd340b9e3
e2bfce8974dec9348d5829c39ad1f9acd340b9e3
juspay/hyperswitch
juspay__hyperswitch-8855
Bug: [FEATURE] Add Gateway System Tracking in Feature Metadata for Routing Stickiness # Add Gateway System Tracking in Feature Metadata for Routing Stickiness ## Problem Statement Currently, payment routing decisions between Direct routing (hyperswitch) and Unified Connector Service (UCS) are made independently for each payment operation. This creates inconsistency issues where different operations for the same payment intent may be routed through different gateway systems. ### Current Behavior - Payment creation may route through Direct routing - Payment confirmation may route through UCS - Payment sync may route through Direct routing again - Each operation makes routing decisions without considering previous choices ### Impact 1. **Payment State Inconsistency**: Different operations using different gateway systems can lead to conflicting payment states 2. **Routing Conflicts**: Operations may fail due to gateway system mismatches 3. **Debugging Complexity**: Payment flows become difficult to trace when they span multiple gateway systems 4. **Potential Data Loss**: Inconsistent routing may cause payment data to be scattered across systems 5. **Merchant Experience**: Unpredictable payment behavior affects merchant confidence ## Proposed Solution Implement routing stickiness by tracking the gateway system used for initial payment routing and ensuring all subsequent operations use the same system. ### Technical Approach - Add `GatewaySystem` enum to track routing decisions (Direct vs UCS) - Store gateway system information in payment intent's feature metadata - Implement routing logic that considers previous gateway system usage - Add comprehensive logging for payment routing decisions - Update all payment operations to preserve routing consistency ### Key Components 1. **Gateway System Enum**: Define clear categorization of routing types 2. **Feature Metadata Storage**: Persist routing decisions for stickiness 3. **Routing Logic Enhancement**: Consider previous decisions in routing algorithms 4. **Observability**: Add logging for debugging and monitoring 5. **Data Consistency**: Ensure metadata is properly maintained across operations
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 41938fc23d3..32b6cdf4116 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2220,6 +2220,34 @@ pub enum PaymentMethod { MobilePayment, } +/// Indicates the gateway system through which the payment is processed. +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialOrd, + Ord, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::VariantNames, + strum::EnumIter, + strum::EnumString, + ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum GatewaySystem { + #[default] + Direct, + UnifiedConnectorService, +} + /// The type of the payment that differentiates between normal and various types of mandate payments. Use 'setup_mandate' in case of zero auth flow. #[derive( Clone, diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 0f56be31309..acc8d4b21f8 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -2,6 +2,7 @@ use common_enums::{PaymentMethodType, RequestIncrementalAuthorization}; use common_types::primitive_wrappers::RequestExtendedAuthorizationBool; use common_utils::{encryption::Encryption, pii, types::MinorUnit}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; +use masking::ExposeInterface; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -492,6 +493,7 @@ pub enum PaymentIntentUpdate { fingerprint_id: Option<String>, updated_by: String, incremental_authorization_allowed: Option<bool>, + feature_metadata: Option<masking::Secret<serde_json::Value>>, }, MetadataUpdate { metadata: serde_json::Value, @@ -517,6 +519,7 @@ pub enum PaymentIntentUpdate { status: storage_enums::IntentStatus, updated_by: String, incremental_authorization_allowed: Option<bool>, + feature_metadata: Option<masking::Secret<serde_json::Value>>, }, PaymentAttemptAndAttemptCountUpdate { active_attempt_id: String, @@ -625,6 +628,7 @@ pub struct PaymentIntentUpdateFields { pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, + pub feature_metadata: Option<masking::Secret<serde_json::Value>>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, @@ -845,6 +849,7 @@ pub struct PaymentIntentUpdateInternal { pub is_iframe_redirection_enabled: Option<bool>, pub extended_return_url: Option<String>, pub payment_channel: Option<common_enums::PaymentChannel>, + pub feature_metadata: Option<masking::Secret<serde_json::Value>>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, @@ -897,6 +902,7 @@ impl PaymentIntentUpdate { is_iframe_redirection_enabled, extended_return_url, payment_channel, + feature_metadata, tax_status, discount_amount, order_date, @@ -953,6 +959,9 @@ impl PaymentIntentUpdate { .or(source.is_iframe_redirection_enabled), extended_return_url: extended_return_url.or(source.extended_return_url), payment_channel: payment_channel.or(source.payment_channel), + feature_metadata: feature_metadata + .map(|value| value.expose()) + .or(source.feature_metadata), tax_status: tax_status.or(source.tax_status), discount_amount: discount_amount.or(source.discount_amount), order_date: order_date.or(source.order_date), @@ -1013,6 +1022,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, + feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, @@ -1062,6 +1072,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: value.is_iframe_redirection_enabled, extended_return_url: value.return_url, payment_channel: value.payment_channel, + feature_metadata: value.feature_metadata, tax_status: value.tax_status, discount_amount: value.discount_amount, order_date: value.order_date, @@ -1118,6 +1129,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: None, extended_return_url: return_url, payment_channel: None, + feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, @@ -1129,6 +1141,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { status, updated_by, incremental_authorization_allowed, + feature_metadata, } => Self { status: Some(status), modified_at: common_utils::date_time::now(), @@ -1170,6 +1183,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, + feature_metadata, tax_status: None, discount_amount: None, order_date: None, @@ -1223,6 +1237,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, + feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, @@ -1239,6 +1254,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { // customer_id, updated_by, incremental_authorization_allowed, + feature_metadata, } => Self { // amount, // currency: Some(currency), @@ -1283,6 +1299,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, + feature_metadata, tax_status: None, discount_amount: None, order_date: None, @@ -1335,6 +1352,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, + feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, @@ -1388,6 +1406,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, + feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, @@ -1440,6 +1459,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, + feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, @@ -1492,6 +1512,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, + feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, @@ -1543,6 +1564,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, + feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, @@ -1591,6 +1613,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, + feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, @@ -1641,6 +1664,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, + feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, @@ -1691,6 +1715,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, + feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, @@ -1739,6 +1764,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, + feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, @@ -1792,6 +1818,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, + feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs index 0cdb553059c..a13e1c7f265 100644 --- a/crates/diesel_models/src/types.rs +++ b/crates/diesel_models/src/types.rs @@ -101,7 +101,7 @@ impl FeatureMetadata { } #[cfg(feature = "v1")] -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)] +#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)] #[diesel(sql_type = Json)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios @@ -110,6 +110,8 @@ pub struct FeatureMetadata { pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, + /// The system that the gateway is integrated with, e.g., `Direct`(through hyperswitch), `UnifiedConnectorService`(through ucs), etc. + pub gateway_system: Option<common_enums::GatewaySystem>, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)] diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs index 4f6313ea31a..699d8dad7ee 100644 --- a/crates/external_services/src/grpc_client/unified_connector_service.rs +++ b/crates/external_services/src/grpc_client/unified_connector_service.rs @@ -186,7 +186,10 @@ impl UnifiedConnectorServiceClient { } } } - None => None, + None => { + router_env::logger::error!(?config.unified_connector_service, "Unified Connector Service config is missing"); + None + } } } diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index dac5aa13410..70f7c4830cf 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -121,6 +121,7 @@ impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata { search_tags, apple_pay_recurring_details: apple_pay_recurring_details .map(ApplePayRecurringDetails::convert_from), + gateway_system: None, } } @@ -129,6 +130,7 @@ impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata { redirect_response, search_tags, apple_pay_recurring_details, + .. } = self; ApiFeatureMetadata { diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 55f8252ac21..60158ebdc12 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -249,6 +249,7 @@ pub struct PaymentIntentUpdateFields { pub duty_amount: Option<MinorUnit>, pub is_confirm_operation: bool, pub payment_channel: Option<common_enums::PaymentChannel>, + pub feature_metadata: Option<Secret<serde_json::Value>>, pub enable_partial_authorization: Option<bool>, } @@ -261,6 +262,7 @@ pub enum PaymentIntentUpdate { updated_by: String, fingerprint_id: Option<String>, incremental_authorization_allowed: Option<bool>, + feature_metadata: Option<Secret<serde_json::Value>>, }, MetadataUpdate { metadata: serde_json::Value, @@ -286,6 +288,7 @@ pub enum PaymentIntentUpdate { status: common_enums::IntentStatus, incremental_authorization_allowed: Option<bool>, updated_by: String, + feature_metadata: Option<Secret<serde_json::Value>>, }, PaymentAttemptAndAttemptCountUpdate { active_attempt_id: String, @@ -437,6 +440,7 @@ pub struct PaymentIntentUpdateInternal { pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, + pub feature_metadata: Option<Secret<serde_json::Value>>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, @@ -874,11 +878,13 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { status, updated_by, incremental_authorization_allowed, + feature_metadata, } => Self { status: Some(status), modified_at: Some(common_utils::date_time::now()), updated_by, incremental_authorization_allowed, + feature_metadata, ..Default::default() }, PaymentIntentUpdate::MerchantStatusUpdate { @@ -903,6 +909,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { // customer_id, updated_by, incremental_authorization_allowed, + feature_metadata, } => Self { // amount, // currency: Some(currency), @@ -913,6 +920,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { modified_at: Some(common_utils::date_time::now()), updated_by, incremental_authorization_allowed, + feature_metadata, ..Default::default() }, PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { @@ -1034,12 +1042,14 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { fingerprint_id, updated_by, incremental_authorization_allowed, + feature_metadata, } => Self::ResponseUpdate { status, amount_captured, fingerprint_id, updated_by, incremental_authorization_allowed, + feature_metadata, }, PaymentIntentUpdate::MetadataUpdate { metadata, @@ -1081,6 +1091,7 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { force_3ds_challenge: value.force_3ds_challenge, is_iframe_redirection_enabled: value.is_iframe_redirection_enabled, payment_channel: value.payment_channel, + feature_metadata: value.feature_metadata, tax_status: value.tax_status, discount_amount: value.discount_amount, order_date: value.order_date, @@ -1121,10 +1132,12 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { status, updated_by, incremental_authorization_allowed, + feature_metadata, } => Self::PGStatusUpdate { status, updated_by, incremental_authorization_allowed, + feature_metadata, }, PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id, @@ -1246,6 +1259,7 @@ impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInt force_3ds_challenge, is_iframe_redirection_enabled, payment_channel, + feature_metadata, tax_status, discount_amount, order_date, @@ -1294,6 +1308,7 @@ impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInt is_iframe_redirection_enabled, extended_return_url: return_url, payment_channel, + feature_metadata, tax_status, discount_amount, order_date, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index b31550d4122..2637e134690 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -34,7 +34,7 @@ use api_models::{ mandates::RecurringDetails, payments::{self as payments_api}, }; -pub use common_enums::enums::CallConnectorAction; +pub use common_enums::enums::{CallConnectorAction, GatewaySystem}; use common_types::payments as common_payments_types; use common_utils::{ ext_traits::{AsyncExt, StringExt}, @@ -91,6 +91,8 @@ use self::{ operations::{BoxedOperation, Operation, PaymentResponse}, routing::{self as self_routing, SessionFlowRoutingInput}, }; +#[cfg(feature = "v1")] +use super::unified_connector_service::update_gateway_system_in_feature_metadata; use super::{ errors::StorageErrorExt, payment_methods::surcharge_decision_configs, routing::TransactionData, unified_connector_service::should_call_unified_connector_service, @@ -4043,7 +4045,22 @@ where services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { record_time_taken_with(|| async { - if should_call_unified_connector_service(state, merchant_context, &router_data).await? { + if should_call_unified_connector_service( + state, + merchant_context, + &router_data, + Some(payment_data), + ) + .await? + { + router_env::logger::info!( + "Processing payment through UCS gateway system - payment_id={}, attempt_id={}", + payment_data + .get_payment_intent() + .payment_id + .get_string_repr(), + payment_data.get_payment_attempt().attempt_id + ); if should_add_task_to_process_tracker(payment_data) { operation .to_domain()? @@ -4058,6 +4075,12 @@ where .ok(); } + // Update feature metadata to track UCS usage for stickiness + update_gateway_system_in_feature_metadata( + payment_data, + GatewaySystem::UnifiedConnectorService, + )?; + (_, *payment_data) = operation .to_update_tracker()? .update_trackers( @@ -4083,6 +4106,18 @@ where Ok((router_data, merchant_connector_account)) } else { + router_env::logger::info!( + "Processing payment through Direct gateway system - payment_id={}, attempt_id={}", + payment_data + .get_payment_intent() + .payment_id + .get_string_repr(), + payment_data.get_payment_attempt().attempt_id + ); + + // Update feature metadata to track Direct routing usage for stickiness + update_gateway_system_in_feature_metadata(payment_data, GatewaySystem::Direct)?; + call_connector_service( state, req_state, @@ -4440,8 +4475,13 @@ where .await?; // do order creation - let should_call_unified_connector_service = - should_call_unified_connector_service(state, merchant_context, &router_data).await?; + let should_call_unified_connector_service = should_call_unified_connector_service( + state, + merchant_context, + &router_data, + Some(payment_data), + ) + .await?; let (connector_request, should_continue_further) = if !should_call_unified_connector_service { let mut should_continue_further = true; @@ -4501,6 +4541,12 @@ where record_time_taken_with(|| async { if should_call_unified_connector_service { + router_env::logger::info!( + "Processing payment through UCS gateway system- payment_id={}, attempt_id={}", + payment_data.get_payment_intent().id.get_string_repr(), + payment_data.get_payment_attempt().id.get_string_repr() + ); + router_data .call_unified_connector_service( state, @@ -4556,7 +4602,19 @@ where services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { record_time_taken_with(|| async { - if should_call_unified_connector_service(state, merchant_context, &router_data).await? { + if should_call_unified_connector_service( + state, + merchant_context, + &router_data, + Some(payment_data), + ) + .await? + { + router_env::logger::info!( + "Executing payment through UCS gateway system - payment_id={}, attempt_id={}", + payment_data.get_payment_intent().id.get_string_repr(), + payment_data.get_payment_attempt().id.get_string_repr() + ); if should_add_task_to_process_tracker(payment_data) { operation .to_domain()? @@ -4596,6 +4654,12 @@ where Ok(router_data) } else { + router_env::logger::info!( + "Processing payment through Direct gateway system - payment_id={}, attempt_id={}", + payment_data.get_payment_intent().id.get_string_repr(), + payment_data.get_payment_attempt().id.get_string_repr() + ); + call_connector_service( state, req_state, diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index dfe3657b0f7..92c84985c9d 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -256,6 +256,11 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelReques status: enums::IntentStatus::Cancelled, updated_by: storage_scheme.to_string(), incremental_authorization_allowed: None, + feature_metadata: payment_data + .payment_intent + .feature_metadata + .clone() + .map(masking::Secret::new), }; (Some(payment_intent_update), enums::AttemptStatus::Voided) } else { diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 9b2f2d85e8e..7cc48fd6f44 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -2056,6 +2056,11 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for .is_iframe_redirection_enabled, is_confirm_operation: true, // Indicates that this is a confirm operation payment_channel: payment_data.payment_intent.payment_channel, + feature_metadata: payment_data + .payment_intent + .feature_metadata + .clone() + .map(masking::Secret::new), tax_status: payment_data.payment_intent.tax_status, discount_amount: payment_data.payment_intent.discount_amount, order_date: payment_data.payment_intent.order_date, diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 450ca96630f..29a1e43ec96 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -2113,6 +2113,11 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( updated_by: storage_scheme.to_string(), // make this false only if initial payment fails, if incremental authorization call fails don't make it false incremental_authorization_allowed: Some(false), + feature_metadata: payment_data + .payment_intent + .feature_metadata + .clone() + .map(masking::Secret::new), }, Ok(_) => storage::PaymentIntentUpdate::ResponseUpdate { status: api_models::enums::IntentStatus::foreign_from( @@ -2124,6 +2129,11 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( incremental_authorization_allowed: payment_data .payment_intent .incremental_authorization_allowed, + feature_metadata: payment_data + .payment_intent + .feature_metadata + .clone() + .map(masking::Secret::new), }, }; diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index e2e4fb824bd..6026a82e0d4 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -953,6 +953,11 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for .is_iframe_redirection_enabled, is_confirm_operation: false, // this is not a confirm operation payment_channel: payment_data.payment_intent.payment_channel, + feature_metadata: payment_data + .payment_intent + .feature_metadata + .clone() + .map(masking::Secret::new), tax_status: payment_data.payment_intent.tax_status, discount_amount: payment_data.payment_intent.discount_amount, order_date: payment_data.payment_intent.order_date, diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs index 4e32095dea7..b00440e89f3 100644 --- a/crates/router/src/core/unified_connector_service.rs +++ b/crates/router/src/core/unified_connector_service.rs @@ -1,6 +1,7 @@ use api_models::admin; -use common_enums::{AttemptStatus, PaymentMethodType}; +use common_enums::{AttemptStatus, GatewaySystem, PaymentMethodType}; use common_utils::{errors::CustomResult, ext_traits::ValueExt}; +use diesel_models::types::FeatureMetadata; use error_stack::ResultExt; use external_services::grpc_client::unified_connector_service::{ ConnectorAuthMetadata, UnifiedConnectorServiceError, @@ -23,9 +24,12 @@ use unified_connector_service_client::payments::{ use crate::{ consts, core::{ - errors::{ApiErrorResponse, RouterResult}, - payments::helpers::{ - is_ucs_enabled, should_execute_based_on_rollout, MerchantConnectorAccountType, + errors::{self, RouterResult}, + payments::{ + helpers::{ + is_ucs_enabled, should_execute_based_on_rollout, MerchantConnectorAccountType, + }, + OperationSessionGetters, OperationSessionSetters, }, utils::get_flow_name, }, @@ -39,21 +43,62 @@ pub mod transformers; // Re-export webhook transformer types for easier access pub use transformers::WebhookTransformData; -pub async fn should_call_unified_connector_service<F: Clone, T>( +/// Generic version of should_call_unified_connector_service that works with any type +/// implementing OperationSessionGetters trait +pub async fn should_call_unified_connector_service<F: Clone, T, D>( state: &SessionState, merchant_context: &MerchantContext, router_data: &RouterData<F, T, PaymentsResponseData>, -) -> RouterResult<bool> { + payment_data: Option<&D>, +) -> RouterResult<bool> +where + D: OperationSessionGetters<F>, +{ + // Check basic UCS availability first if state.grpc_client.unified_connector_service_client.is_none() { + router_env::logger::debug!( + "Unified Connector Service client is not available, skipping UCS decision" + ); return Ok(false); } let ucs_config_key = consts::UCS_ENABLED; - if !is_ucs_enabled(state, ucs_config_key).await { + router_env::logger::debug!( + "Unified Connector Service is not enabled, skipping UCS decision" + ); return Ok(false); } + // Apply stickiness logic if payment_data is available + if let Some(payment_data) = payment_data { + let previous_gateway_system = extract_gateway_system_from_payment_intent(payment_data); + + match previous_gateway_system { + Some(GatewaySystem::UnifiedConnectorService) => { + // Payment intent previously used UCS, maintain stickiness to UCS + router_env::logger::info!( + "Payment gateway system decision: UCS (sticky) - payment intent previously used UCS" + ); + return Ok(true); + } + Some(GatewaySystem::Direct) => { + // Payment intent previously used Direct, maintain stickiness to Direct (return false for UCS) + router_env::logger::info!( + "Payment gateway system decision: Direct (sticky) - payment intent previously used Direct" + ); + return Ok(false); + } + None => { + // No previous gateway system set, continue with normal gateway system logic + router_env::logger::debug!( + "UCS stickiness: No previous gateway system set, applying normal gateway system logic" + ); + } + } + } + + // Continue with normal UCS gateway system logic let merchant_id = merchant_context .get_merchant_account() .get_id() @@ -71,8 +116,13 @@ pub async fn should_call_unified_connector_service<F: Clone, T>( .is_some_and(|config| config.ucs_only_connectors.contains(&connector_name)); if is_ucs_only_connector { + router_env::logger::info!( + "Payment gateway system decision: UCS (forced) - merchant_id={}, connector={}, payment_method={}, flow={}", + merchant_id, connector_name, payment_method, flow_name + ); return Ok(true); } + let config_key = format!( "{}_{}_{}_{}_{}", consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX, @@ -83,9 +133,87 @@ pub async fn should_call_unified_connector_service<F: Clone, T>( ); let should_execute = should_execute_based_on_rollout(state, &config_key).await?; + + // Log gateway system decision + if should_execute { + router_env::logger::info!( + "Payment gateway system decision: UCS - merchant_id={}, connector={}, payment_method={}, flow={}", + merchant_id, connector_name, payment_method, flow_name + ); + } else { + router_env::logger::info!( + "Payment gateway system decision: Direct - merchant_id={}, connector={}, payment_method={}, flow={}", + merchant_id, connector_name, payment_method, flow_name + ); + } + Ok(should_execute) } +/// Extracts the gateway system from the payment intent's feature metadata +/// Returns None if metadata is missing, corrupted, or doesn't contain gateway_system +fn extract_gateway_system_from_payment_intent<F: Clone, D>( + payment_data: &D, +) -> Option<GatewaySystem> +where + D: OperationSessionGetters<F>, +{ + #[cfg(feature = "v1")] + { + payment_data + .get_payment_intent() + .feature_metadata + .as_ref() + .and_then(|metadata| { + // Try to parse the JSON value as FeatureMetadata + // Log errors but don't fail the flow for corrupted metadata + match serde_json::from_value::<FeatureMetadata>(metadata.clone()) { + Ok(feature_metadata) => feature_metadata.gateway_system, + Err(err) => { + router_env::logger::warn!( + "Failed to parse feature_metadata for gateway_system extraction: {}", + err + ); + None + } + } + }) + } + #[cfg(feature = "v2")] + { + None // V2 does not use feature metadata for gateway system tracking + } +} + +/// Updates the payment intent's feature metadata to track the gateway system being used +#[cfg(feature = "v1")] +pub fn update_gateway_system_in_feature_metadata<F: Clone, D>( + payment_data: &mut D, + gateway_system: GatewaySystem, +) -> RouterResult<()> +where + D: OperationSessionGetters<F> + OperationSessionSetters<F>, +{ + let mut payment_intent = payment_data.get_payment_intent().clone(); + + let existing_metadata = payment_intent.feature_metadata.as_ref(); + + let mut feature_metadata = existing_metadata + .and_then(|metadata| serde_json::from_value::<FeatureMetadata>(metadata.clone()).ok()) + .unwrap_or_default(); + + feature_metadata.gateway_system = Some(gateway_system); + + let updated_metadata = serde_json::to_value(feature_metadata) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to serialize feature metadata")?; + + payment_intent.feature_metadata = Some(updated_metadata.clone()); + payment_data.set_payment_intent(payment_intent); + + Ok(()) +} + pub async fn should_call_unified_connector_service_for_webhooks( state: &SessionState, merchant_context: &MerchantContext, @@ -422,7 +550,7 @@ pub async fn call_unified_connector_service_for_webhook( .unified_connector_service_client .as_ref() .ok_or_else(|| { - error_stack::report!(ApiErrorResponse::WebhookProcessingFailure) + error_stack::report!(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("UCS client is not available for webhook processing") })?; @@ -472,10 +600,10 @@ pub async fn call_unified_connector_service_for_webhook( build_unified_connector_service_auth_metadata(mca_type, merchant_context) }) .transpose() - .change_context(ApiErrorResponse::InternalServerError) + .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to build UCS auth metadata")? .ok_or_else(|| { - error_stack::report!(ApiErrorResponse::InternalServerError).attach_printable( + error_stack::report!(errors::ApiErrorResponse::InternalServerError).attach_printable( "Missing merchant connector account for UCS webhook transformation", ) })?; @@ -504,7 +632,7 @@ pub async fn call_unified_connector_service_for_webhook( } Err(err) => { // When UCS is configured, we don't fall back to direct connector processing - Err(ApiErrorResponse::WebhookProcessingFailure) + Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable(format!("UCS webhook processing failed: {err}")) } } diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index c5c25bcc3e3..52a72a2d020 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -139,7 +139,7 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow { .as_ref() .is_none() { - let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::PGStatusUpdate { status: api_models::enums::IntentStatus::Failed,updated_by: merchant_account.storage_scheme.to_string(), incremental_authorization_allowed: Some(false) }; + let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::PGStatusUpdate { status: api_models::enums::IntentStatus::Failed,updated_by: merchant_account.storage_scheme.to_string(), incremental_authorization_allowed: Some(false), feature_metadata: payment_data.payment_intent.feature_metadata.clone().map(masking::Secret::new), }; let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ErrorUpdate { connector: None,
2025-08-06T12:41:26Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description This change adds gateway system tracking in the feature metadata to enable routing stickiness and improve payment flow routing decisions. The implementation includes: - Adding a new `GatewaySystem` enum to track whether payments are processed through Direct routing (hyperswitch) or Unified Connector Service (UCS) - Storing the gateway system information in payment intent's feature metadata for routing stickiness - Implementing routing logic that considers previous gateway system usage when making routing decisions - Adding comprehensive logging for payment routing decisions for better observability - Updating all payment update operations to preserve feature metadata consistency ### Additional Changes - [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 Previously, payment routing decisions between Direct routing and UCS were made independently for each payment operation, which could lead to inconsistent routing for the same payment intent across different operations (confirm, capture, sync, etc.). This lack of stickiness could cause issues with: 1. Payment state consistency across different operations 2. Potential routing conflicts when different operations use different gateway systems 3. Difficulty in tracking and debugging payment flows that span multiple operations This change ensures that once a payment intent is routed through a specific gateway system (Direct or UCS), all subsequent operations for that payment maintain the same routing decision. ## How did you test it? - Tested payment creation, confirmation, and sync operations with both Direct and UCS routing - Verified that routing decisions are properly logged and persisted in feature metadata - Confirmed that stickiness logic correctly routes subsequent operations through the same gateway system - Tested error scenarios to ensure graceful fallback when metadata is corrupted or missing ##### Authorize ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ***************' \ --data-raw '{ "amount": 1000, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "Uzzu54523", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request.", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "upi", "payment_method_type": "upi_collect", "payment_method_data": { "upi": { "upi_collect": { "vpa_id": "success@razorpay" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "Swangi", "last_name": "Kumari" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "46282", "country": "IN", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "46282", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "all_keys_required": true }' ``` ```json { "payment_id": "pay_1NzPXUQFRkXlvHOIW3Jq", "merchant_id": "merchant_1754554769", "status": "requires_customer_action", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "razorpay", "client_secret": "pay_1NzPXUQFRkXlvHOIW3Jq_secret_bhXTPfgXbwB11rmrC0DR", "created": "2025-08-08T10:58:58.767Z", "currency": "INR", "customer_id": "Uzzu54523", "customer": { "id": "Uzzu54523", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request.", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "upi", "payment_method_data": { "upi": { "upi_collect": { "vpa_id": "su*****@razorpay" } }, "billing": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "Swangi", "last_name": "Kumari", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" } }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "46282", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" }, "billing": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "46282", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "upi_collect", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "Uzzu54523", "created_at": 1754650738, "expires": 1754654338, "secret": "epk_7a28f568d1834cf983b36bc50e45970f" }, "manual_retry_allowed": null, "connector_transaction_id": "pay_R2odTWpZA226ue", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "order_R2odSokuwuMexQ", "payment_link": null, "profile_id": "pro_NkNnZmnjCEuoOKyqoev5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_JtzW87JrlcfmX6fssydo", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-08T11:13:58.767Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-08T10:59:02.234Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": "{\"razorpay_payment_id\":\"pay_R2odTWpZA226ue\"}", "enable_partial_authorization": null } ``` ##### Psync ```bash curl --location 'http://localhost:8080/payments/pay_1NzPXUQFRkXlvHOIW3Jq?force_sync=true&expand_captures=true&expand_attempts=true' \ --header 'Accept: application/json' \ --header 'api-key: *****************************' ``` ```json { "payment_id": "pay_4dezIe3S2nraarfCsnly", "merchant_id": "merchant_1754554769", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "razorpay", "client_secret": "pay_4dezIe3S2nraarfCsnly_secret_fPafwmfIQcGWTr96zQtm", "created": "2025-08-07T11:07:00.954Z", "currency": "INR", "customer_id": "Uzzu54523", "customer": { "id": "Uzzu54523", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request.", "refunds": null, "disputes": null, "attempts": [ { "attempt_id": "pay_4dezIe3S2nraarfCsnly_1", "status": "authentication_pending", "amount": 1000, "order_tax_amount": null, "currency": "INR", "connector": "razorpay", "error_message": null, "payment_method": "upi", "connector_transaction_id": "pay_R2QErM6QamRIFx", "capture_method": "automatic", "authentication_type": "no_three_ds", "created_at": "2025-08-07T11:07:00.954Z", "modified_at": "2025-08-07T11:07:05.271Z", "cancellation_reason": null, "mandate_id": null, "error_code": null, "payment_token": null, "connector_metadata": null, "payment_experience": null, "payment_method_type": "upi_collect", "reference_id": "order_R2QEqgtrS7lSPD", "unified_code": null, "unified_message": null, "client_source": null, "client_version": null } ], "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "upi", "payment_method_data": { "upi": { "upi_collect": { "vpa_id": "su*****@razorpay" } }, "billing": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "Swangi", "last_name": "Kumari", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" } }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "46282", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" }, "billing": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "46282", "state": "California", "first_name": "joseph", "last_name": "Doe", "origin_zip": null }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "upi_collect", "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": "pay_R2QErM6QamRIFx", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "gateway_system": "unified_connector_service" }, "reference_id": "order_R2QEqgtrS7lSPD", "payment_link": null, "profile_id": "pro_NkNnZmnjCEuoOKyqoev5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_JtzW87JrlcfmX6fssydo", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-07T11:22:00.954Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "network_transaction_id": null, "payment_method_status": null, "updated": "2025-08-07T11:11:29.281Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": "{\"entity\":\"collection\",\"count\":1,\"items\":[{\"id\":\"pay_R2QErM6QamRIFx\",\"entity\":\"payment\",\"amount\":1000,\"currency\":\"INR\",\"status\":\"captured\",\"order_id\":\"order_R2QEqgtrS7lSPD\",\"invoice_id\":null,\"international\":false,\"method\":\"upi\",\"amount_refunded\":0,\"refund_status\":null,\"captured\":true,\"description\":\"Payment via Razorpay\",\"card_id\":null,\"bank\":null,\"wallet\":null,\"vpa\":\"success@razorpay\",\"email\":\"swangi.kumari@juspay.in\",\"contact\":\"+918056594427\",\"notes\":{\"optimizer_provider_name\":\"razorpay\"},\"fee\":25,\"tax\":4,\"error_code\":null,\"error_description\":null,\"error_source\":null,\"error_step\":null,\"error_reason\":null,\"acquirer_data\":{\"rrn\":\"232178449311\",\"upi_transaction_id\":\"007AC04E0A02D40AA98FE252C69C7305\"},\"gateway_provider\":\"Razorpay\",\"created_at\":1754564823,\"upi\":{\"vpa\":\"success@razorpay\"}}]}", "enable_partial_authorization": null } ``` #### What to look for? - in logs you will be able to see ```sh info:: Processing payment through Direct gateway system - payment_id=pay_4dezIe3S2nraarfCsnly, attempt_id=pay_4dezIe3S2nraarfCsnly_1 ``` ```sh info:: Payment gateway system decision: Direct (sticky) - payment intent previously used Direct ``` ###### Additional Note: This is also pushed to kafka topic for sessionizing <img width="1295" height="882" alt="Screenshot 2025-08-07 at 4 46 52β€―PM" src="https://github.com/user-attachments/assets/d4c69638-0191-4cda-96be-35cee3015e33" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt` - [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
v1.116.0
d4d8236e3102505553334b3d395496ae97ee8e14
d4d8236e3102505553334b3d395496ae97ee8e14
juspay/hyperswitch
juspay__hyperswitch-8851
Bug: [BUG] (connector): [Netcetera] Fix three_ds_requestor_challenge_ind field in Netcetera Response ### Bug Description Currently we are not recieving field **_three_ds_requestor_challenge_ind_** in Netcetera's authentication response since the struct is incorrectly declared in the transformers file. 1. **_three_ds_requestor_challenge_ind_** is currently a part of _**NetceteraAuthenticationSuccessResponse**_ enum, but it should be a field inside authenitcation request 2. **_three_ds_requestor_challenge_ind_** has type optional string, whereas it is vector of string (ref documentation - https://3dss.netcetera.com/3dsserver/doc/2.5.2.1/3ds-authentication) **Current structure** ``` NetceteraAuthenticationSuccessResponse{ .... three_ds_requestor_challenge_ind: Option<String> ...} ``` **Correct structure** ``` NetceteraAuthenticationSuccessResponse{ .... authentication_request: { three_ds_requestor_challenge_ind: Option<Vector<String>>, } ...} ``` ### Expected Behavior When the struct is fixed in code, expected behavior is to recieve **three_ds_requestor_challenge_ind** field in Netcetera's authentication response. **correct structure** ``` NetceteraAuthenticationSuccessResponse{ .... authentication_request: { three_ds_requestor_challenge_ind: Option<Vector<String>>, } ...} ``` ### Actual Behavior Currently we are not recieving field **_three_ds_requestor_challenge_ind_** in Netcetera's authentication response since the struct is incorrect, and as a result sending challengeCode as null to Cybersource ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs index fc334d68167..01189f6b926 100644 --- a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs @@ -158,6 +158,13 @@ impl } Some(ACSChallengeMandatedIndicator::N) | None => AuthNFlowType::Frictionless, }; + + let challenge_code = response + .authentication_request + .as_ref() + .and_then(|req| req.three_ds_requestor_challenge_ind.as_ref()) + .and_then(|v| v.first().cloned()); + Ok(AuthenticationResponseData::AuthNResponse { authn_flow_type, authentication_value: response.authentication_value, @@ -165,7 +172,7 @@ impl connector_metadata: None, ds_trans_id: response.authentication_response.ds_trans_id, eci: response.eci, - challenge_code: response.three_ds_requestor_challenge_ind, + challenge_code, challenge_cancel: response.challenge_cancel, challenge_code_reason: response.trans_status_reason, message_extension: response.message_extension.and_then(|v| { @@ -653,13 +660,12 @@ pub struct NetceteraAuthenticationSuccessResponse { pub authentication_value: Option<Secret<String>>, pub eci: Option<String>, pub acs_challenge_mandated: Option<ACSChallengeMandatedIndicator>, + pub authentication_request: Option<AuthenticationRequest>, pub authentication_response: AuthenticationResponse, #[serde(rename = "base64EncodedChallengeRequest")] pub encoded_challenge_request: Option<String>, pub challenge_cancel: Option<String>, pub trans_status_reason: Option<String>, - #[serde(rename = "threeDSRequestorChallengeInd")] - pub three_ds_requestor_challenge_ind: Option<String>, pub message_extension: Option<Vec<MessageExtensionAttribute>>, } @@ -669,6 +675,13 @@ pub struct NetceteraAuthenticationFailureResponse { pub error_details: NetceteraErrorDetails, } +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthenticationRequest { + #[serde(rename = "threeDSRequestorChallengeInd")] + pub three_ds_requestor_challenge_ind: Option<Vec<String>>, +} + #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthenticationResponse {
2025-08-06T10:59:53Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Currently we are not recieving field **_three_ds_requestor_challenge_ind_** in Netcetera's authentication response since the struct is incorrectly declared in the transformers file. 1. **_three_ds_requestor_challenge_ind_** is currently a part of _**NetceteraAuthenticationSuccessResponse**_ enum, but it should be a field inside **_authenitcation_request_** 2. **_three_ds_requestor_challenge_ind_** has type optional string currently, but it should be a vector of string (ref documentation - https://3dss.netcetera.com/3dsserver/doc/2.5.2.1/3ds-authentication) **Current structure** ``` NetceteraAuthenticationSuccessResponse{ .... three_ds_requestor_challenge_ind: Option<String> ...} ``` **Correct structure** ``` NetceteraAuthenticationSuccessResponse{ .... authentication_request: { three_ds_requestor_challenge_ind: Option<Vector<String>>, } ...} ``` This PR introduces the above fix in the struct. ### 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 netcetera's challenge via local hyperswitch sdk. As expected, we are now able to get **_three_ds_requestor_challenge_ind_** field in the NetceteraAuthenticationSuccessResponse. <img width="2560" height="135" alt="Screenshot 2025-08-06 at 4 29 03β€―PM" src="https://github.com/user-attachments/assets/45fee6c0-b785-4f3e-abb2-0d74468d2024" /> ## 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.115.0
640d0552f96721d63c14fda4a07fc5987cea29a0
640d0552f96721d63c14fda4a07fc5987cea29a0
juspay/hyperswitch
juspay__hyperswitch-8845
Bug: [BUG] Fix Refund Reason Type in Adyen ### Bug Description The reason field in AdyenRefundRequest is currently of type Option<String>, which allows any arbitrary string to be passed as the refund reason. Adyen supports only a fixed set of values (FRAUD, CUSTOMER REQUEST, RETURN, DUPLICATE, OTHER). If an unsupported value is passed, the connector throws an error at runtime. This results in a failure that could be avoided earlier in the flow. ### Expected Behavior The reason field should be strongly typed as Option<AdyenRefundRequestReason>, an enum with all supported values. Any value outside the allowed set should be mapped to OTHER internally, ensuring the connector does not throw unexpected errors. ### Actual Behavior Currently, if the refund reason is anything other than the accepted Adyen values, the connector fails and returns an error response. There’s no early validation or fallback mechanism to handle unsupported values. ### Steps To Reproduce 1. Set reason = Some("INVALID_REASON") in a refund request. 2. The system accepts the value since it's an Option<String>. 3. Connector forwards the request to Adyen. 4. Adyen rejects it due to unsupported reason. 5. The system returns an error response from the connector. ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: macOS 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/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 0b378a05718..3bba4ca57d0 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -114,6 +114,8 @@ payment_method_type = "apple_pay" payment_method_type = "google_pay" [[adyen.wallet]] payment_method_type = "paypal" +[[adyen.voucher]] + payment_method_type = "boleto" [adyen.connector_auth.BodyKey] api_key = "Adyen API Key" key1 = "Adyen Account Id" diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index 3d04375b106..1625ee900e7 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + #[cfg(feature = "payouts")] use api_models::payouts::{self, PayoutMethodData}; use api_models::{ @@ -1391,12 +1393,37 @@ pub struct DokuBankData { pub struct AdyenRefundRequest { merchant_account: Secret<String>, amount: Amount, - merchant_refund_reason: Option<String>, + merchant_refund_reason: Option<AdyenRefundRequestReason>, reference: String, splits: Option<Vec<AdyenSplitData>>, store: Option<String>, } +#[derive(Debug, Serialize, Deserialize)] +pub enum AdyenRefundRequestReason { + FRAUD, + #[serde(rename = "CUSTOMER REQUEST")] + CUSTOMERREQUEST, + RETURN, + DUPLICATE, + OTHER, +} + +impl FromStr for AdyenRefundRequestReason { + type Err = error_stack::Report<errors::ConnectorError>; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + match s.to_uppercase().as_str() { + "FRAUD" => Ok(Self::FRAUD), + "CUSTOMER REQUEST" => Ok(Self::CUSTOMERREQUEST), + "RETURN" => Ok(Self::RETURN), + "DUPLICATE" => Ok(Self::DUPLICATE), + "OTHER" => Ok(Self::OTHER), + _ => Ok(Self::OTHER), + } + } +} + #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenRefundResponse { @@ -4693,7 +4720,13 @@ impl<F> TryFrom<&AdyenRouterData<&RefundsRouterData<F>>> for AdyenRefundRequest currency: item.router_data.request.currency, value: item.amount, }, - merchant_refund_reason: item.router_data.request.reason.clone(), + merchant_refund_reason: item + .router_data + .request + .reason + .as_ref() + .map(|reason| AdyenRefundRequestReason::from_str(reason)) + .transpose()?, reference: item.router_data.request.refund_id.clone(), store, splits,
2025-08-06T04:03:19Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/8845) ## Description <!-- Describe your changes in detail --> This PR updates the reason field in AdyenRefundRequest from Option<String> to Option<AdyenRefundRequestReason>, a strongly typed enum. This change ensures only supported values (FRAUD, CUSTOMER REQUEST, RETURN, DUPLICATE, OTHER) are used. ### 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 A. Refund(with valid reason): Request: ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Emxcc7NEApdtpDZyA54Hc0hN43a4wvBTlJ0wIGGeGquavEbsE4lhVWQcyPV8jMFu' \ --data '{ "payment_id": "pay_aUwRQFUMFVSuIsfGRRiq", "amount": 100, "reason": "CUSTOMER REQUEST", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response: ``` { "refund_id": "ref_3UOUCY4WziTz0iWhRGjT", "payment_id": "pay_aUwRQFUMFVSuIsfGRRiq", "amount": 100, "currency": "USD", "status": "pending", "reason": "CUSTOMER REQUEST", "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-08-06T04:02:37.782Z", "updated_at": "2025-08-06T04:02:39.280Z", "connector": "adyen", "profile_id": "pro_H4NAjXx3vY9NI4nQbXom", "merchant_connector_id": "mca_EC2PLdAi5hhl8zAKbt0G", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ``` B. Refund (with invalid reason): Request: ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_8rgdhjpDZyA54Hc0hN43a4wvBTlJ0wIGGeGquavEbsa.kjsfhgubdhrsj' \ --data '{ "payment_id": "pay_dwfsrgdfnQSuIsfGRerjgh", "amount": 100, "reason": "customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response: ``` { "refund_id": "ref_7JGWziplkiWhRaSg", "payment_id": "pay_dwfsrgdfnQSuIsfGRerjgh", "amount": 100, "currency": "USD", "status": "pending", "reason": "OTHER", "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-08-06T04:02:37.782Z", "updated_at": "2025-08-06T04:02:39.280Z", "connector": "adyen", "profile_id": "pro_H4NAjXx3vY9NI4nQbXom", "merchant_connector_id": "mca_EC2PLdAi5hhl8zAKbt0G", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ``` ## 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.115.0
c1d982e3009ebe192b350c2067bf9c2a708d7320
c1d982e3009ebe192b350c2067bf9c2a708d7320
juspay/hyperswitch
juspay__hyperswitch-8847
Bug: feat: Add schema to store chat request response - add schema for chat, to store request and response - store chats to chat schema asynchronously - encrypt the sensitive data - have endpoint to list the chat data and decrypt it properly
diff --git a/config/config.example.toml b/config/config.example.toml index b725be102c1..134e0a49e84 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -1257,6 +1257,7 @@ allow_connected_merchants = false # Enable or disable connected merchant account [chat] enabled = false # Enable or disable chat features hyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow host +encryption_key = "" # Key to encrypt and decrypt chats [proxy_status_mapping] proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index bfba035c1f3..fe8b09cd7db 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -419,6 +419,7 @@ max_random_schedule_delay_in_seconds = 300 # max random delay in seconds to sche [chat] enabled = false # Enable or disable chat features hyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow host +encryption_key = "" # Key to encrypt and decrypt chats [proxy_status_mapping] proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response diff --git a/config/development.toml b/config/development.toml index 940e43b50ca..e4cbe3af226 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1368,6 +1368,7 @@ version = "HOSTNAME" [chat] enabled = false hyperswitch_ai_host = "http://0.0.0.0:8000" +encryption_key = "" [proxy_status_mapping] proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response diff --git a/config/docker_compose.toml b/config/docker_compose.toml index d299323f2c1..62f6830832c 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -1226,6 +1226,7 @@ allow_connected_merchants = true [chat] enabled = false hyperswitch_ai_host = "http://0.0.0.0:8000" +encryption_key = "" [authentication_providers] click_to_pay = {connector_list = "adyen, cybersource, trustpay"} diff --git a/crates/api_models/src/chat.rs b/crates/api_models/src/chat.rs index c66b42cc4f4..975197fd3fc 100644 --- a/crates/api_models/src/chat.rs +++ b/crates/api_models/src/chat.rs @@ -1,12 +1,13 @@ use common_utils::id_type; use masking::Secret; +use time::PrimitiveDateTime; #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct ChatRequest { pub message: Secret<String>, } -#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct ChatResponse { pub response: Secret<serde_json::Value>, pub merchant_id: id_type::MerchantId, @@ -16,3 +17,32 @@ pub struct ChatResponse { #[serde(skip_serializing)] pub row_count: Option<i32>, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct ChatListRequest { + pub merchant_id: Option<id_type::MerchantId>, + pub limit: Option<i64>, + pub offset: Option<i64>, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct ChatConversation { + pub id: String, + pub session_id: Option<String>, + pub user_id: Option<String>, + pub merchant_id: Option<String>, + pub profile_id: Option<String>, + pub org_id: Option<String>, + pub role_id: Option<String>, + pub user_query: Secret<String>, + pub response: Secret<serde_json::Value>, + pub database_query: Option<String>, + pub interaction_status: Option<String>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct ChatListResponse { + pub conversations: Vec<ChatConversation>, +} diff --git a/crates/api_models/src/events/chat.rs b/crates/api_models/src/events/chat.rs index 42fefe487e9..38f20b0c3bb 100644 --- a/crates/api_models/src/events/chat.rs +++ b/crates/api_models/src/events/chat.rs @@ -1,5 +1,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; -use crate::chat::{ChatRequest, ChatResponse}; +use crate::chat::{ChatListRequest, ChatListResponse, ChatRequest, ChatResponse}; -common_utils::impl_api_event_type!(Chat, (ChatRequest, ChatResponse)); +common_utils::impl_api_event_type!( + Chat, + (ChatRequest, ChatResponse, ChatListRequest, ChatListResponse) +); diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index 28508749f35..59ec5377690 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -197,3 +197,9 @@ pub const REQUEST_TIME_OUT: u64 = 30; /// API client request timeout for ai service (in seconds) pub const REQUEST_TIME_OUT_FOR_AI_SERVICE: u64 = 120; + +/// Default limit for list operations (can be used across different entities) +pub const DEFAULT_LIST_LIMIT: i64 = 100; + +/// Default offset for list operations (can be used across different entities) +pub const DEFAULT_LIST_OFFSET: i64 = 0; diff --git a/crates/diesel_models/src/hyperswitch_ai_interaction.rs b/crates/diesel_models/src/hyperswitch_ai_interaction.rs new file mode 100644 index 00000000000..a22bd288c19 --- /dev/null +++ b/crates/diesel_models/src/hyperswitch_ai_interaction.rs @@ -0,0 +1,49 @@ +use common_utils::encryption::Encryption; +use diesel::{self, Identifiable, Insertable, Queryable, Selectable}; +use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; + +use crate::schema::hyperswitch_ai_interaction; + +#[derive( + Clone, + Debug, + Deserialize, + Identifiable, + Queryable, + Selectable, + Serialize, + router_derive::DebugAsDisplay, +)] +#[diesel(table_name = hyperswitch_ai_interaction, primary_key(id, created_at), check_for_backend(diesel::pg::Pg))] +pub struct HyperswitchAiInteraction { + pub id: String, + pub session_id: Option<String>, + pub user_id: Option<String>, + pub merchant_id: Option<String>, + pub profile_id: Option<String>, + pub org_id: Option<String>, + pub role_id: Option<String>, + pub user_query: Option<Encryption>, + pub response: Option<Encryption>, + pub database_query: Option<String>, + pub interaction_status: Option<String>, + pub created_at: PrimitiveDateTime, +} + +#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] +#[diesel(table_name = hyperswitch_ai_interaction)] +pub struct HyperswitchAiInteractionNew { + pub id: String, + pub session_id: Option<String>, + pub user_id: Option<String>, + pub merchant_id: Option<String>, + pub profile_id: Option<String>, + pub org_id: Option<String>, + pub role_id: Option<String>, + pub user_query: Option<Encryption>, + pub response: Option<Encryption>, + pub database_query: Option<String>, + pub interaction_status: Option<String>, + pub created_at: PrimitiveDateTime, +} diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index caf979b2c5f..b715134f926 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -23,6 +23,7 @@ pub mod file; pub mod fraud_check; pub mod generic_link; pub mod gsm; +pub mod hyperswitch_ai_interaction; #[cfg(feature = "kv_store")] pub mod kv; pub mod locker_mock_up; @@ -69,10 +70,11 @@ pub type StorageResult<T> = error_stack::Result<T, errors::DatabaseError>; pub type PgPooledConn = async_bb8_diesel::Connection<diesel::PgConnection>; pub use self::{ address::*, api_keys::*, callback_mapper::*, cards_info::*, configs::*, customers::*, - dispute::*, ephemeral_key::*, events::*, file::*, generic_link::*, locker_mock_up::*, - mandate::*, merchant_account::*, merchant_connector_account::*, payment_attempt::*, - payment_intent::*, payment_method::*, payout_attempt::*, payouts::*, process_tracker::*, - refund::*, reverse_lookup::*, user_authentication_method::*, + dispute::*, ephemeral_key::*, events::*, file::*, generic_link::*, + hyperswitch_ai_interaction::*, locker_mock_up::*, mandate::*, merchant_account::*, + merchant_connector_account::*, payment_attempt::*, payment_intent::*, payment_method::*, + payout_attempt::*, payouts::*, process_tracker::*, refund::*, reverse_lookup::*, + user_authentication_method::*, }; /// The types and implementations provided by this module are required for the schema generated by /// `diesel_cli` 2.0 to work with the types defined in Rust code. This is because diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs index 17eae2427e7..2dc6c18a1a1 100644 --- a/crates/diesel_models/src/query.rs +++ b/crates/diesel_models/src/query.rs @@ -21,6 +21,7 @@ pub mod fraud_check; pub mod generic_link; pub mod generics; pub mod gsm; +pub mod hyperswitch_ai_interaction; pub mod locker_mock_up; pub mod mandate; pub mod merchant_account; diff --git a/crates/diesel_models/src/query/hyperswitch_ai_interaction.rs b/crates/diesel_models/src/query/hyperswitch_ai_interaction.rs new file mode 100644 index 00000000000..91db3ec468e --- /dev/null +++ b/crates/diesel_models/src/query/hyperswitch_ai_interaction.rs @@ -0,0 +1,32 @@ +use diesel::{associations::HasTable, ExpressionMethods}; + +use crate::{ + hyperswitch_ai_interaction::{HyperswitchAiInteraction, HyperswitchAiInteractionNew}, + query::generics, + schema::hyperswitch_ai_interaction::dsl, + PgPooledConn, StorageResult, +}; + +impl HyperswitchAiInteractionNew { + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<HyperswitchAiInteraction> { + generics::generic_insert(conn, self).await + } +} + +impl HyperswitchAiInteraction { + pub async fn filter_by_optional_merchant_id( + conn: &PgPooledConn, + merchant_id: Option<&common_utils::id_type::MerchantId>, + limit: i64, + offset: i64, + ) -> StorageResult<Vec<Self>> { + generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( + conn, + dsl::merchant_id.eq(merchant_id.cloned()), + Some(limit), + Some(offset), + Some(dsl::created_at.desc()), + ) + .await + } +} diff --git a/crates/diesel_models/src/query/utils.rs b/crates/diesel_models/src/query/utils.rs index fe2f43d419b..96a41f10ca0 100644 --- a/crates/diesel_models/src/query/utils.rs +++ b/crates/diesel_models/src/query/utils.rs @@ -52,6 +52,12 @@ mod composite_key { self.0 } } + impl CompositeKey for <schema::hyperswitch_ai_interaction::table as diesel::Table>::PrimaryKey { + type UK = schema::hyperswitch_ai_interaction::dsl::id; + fn get_local_unique_key(&self) -> Self::UK { + self.0 + } + } impl CompositeKey for <schema_v2::incremental_authorization::table as diesel::Table>::PrimaryKey { type UK = schema_v2::incremental_authorization::dsl::authorization_id; fn get_local_unique_key(&self) -> Self::UK { @@ -139,6 +145,7 @@ impl_get_primary_key_for_composite!( schema::customers::table, schema::blocklist::table, schema::incremental_authorization::table, + schema::hyperswitch_ai_interaction::table, schema_v2::incremental_authorization::table, schema_v2::blocklist::table ); diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 79df62ac4b2..271d2a79ba0 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -632,6 +632,62 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + hyperswitch_ai_interaction (id, created_at) { + #[max_length = 64] + id -> Varchar, + #[max_length = 64] + session_id -> Nullable<Varchar>, + #[max_length = 64] + user_id -> Nullable<Varchar>, + #[max_length = 64] + merchant_id -> Nullable<Varchar>, + #[max_length = 64] + profile_id -> Nullable<Varchar>, + #[max_length = 64] + org_id -> Nullable<Varchar>, + #[max_length = 64] + role_id -> Nullable<Varchar>, + user_query -> Nullable<Bytea>, + response -> Nullable<Bytea>, + database_query -> Nullable<Text>, + #[max_length = 64] + interaction_status -> Nullable<Varchar>, + created_at -> Timestamp, + } +} + +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + hyperswitch_ai_interaction_default (id, created_at) { + #[max_length = 64] + id -> Varchar, + #[max_length = 64] + session_id -> Nullable<Varchar>, + #[max_length = 64] + user_id -> Nullable<Varchar>, + #[max_length = 64] + merchant_id -> Nullable<Varchar>, + #[max_length = 64] + profile_id -> Nullable<Varchar>, + #[max_length = 64] + org_id -> Nullable<Varchar>, + #[max_length = 64] + role_id -> Nullable<Varchar>, + user_query -> Nullable<Bytea>, + response -> Nullable<Bytea>, + database_query -> Nullable<Text>, + #[max_length = 64] + interaction_status -> Nullable<Varchar>, + created_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1667,6 +1723,8 @@ diesel::allow_tables_to_appear_in_same_query!( fraud_check, gateway_status_map, generic_link, + hyperswitch_ai_interaction, + hyperswitch_ai_interaction_default, incremental_authorization, locker_mock_up, mandate, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index b2e674f34a5..4195475f88d 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -646,6 +646,62 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + hyperswitch_ai_interaction (id, created_at) { + #[max_length = 64] + id -> Varchar, + #[max_length = 64] + session_id -> Nullable<Varchar>, + #[max_length = 64] + user_id -> Nullable<Varchar>, + #[max_length = 64] + merchant_id -> Nullable<Varchar>, + #[max_length = 64] + profile_id -> Nullable<Varchar>, + #[max_length = 64] + org_id -> Nullable<Varchar>, + #[max_length = 64] + role_id -> Nullable<Varchar>, + user_query -> Nullable<Bytea>, + response -> Nullable<Bytea>, + database_query -> Nullable<Text>, + #[max_length = 64] + interaction_status -> Nullable<Varchar>, + created_at -> Timestamp, + } +} + +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + hyperswitch_ai_interaction_default (id, created_at) { + #[max_length = 64] + id -> Varchar, + #[max_length = 64] + session_id -> Nullable<Varchar>, + #[max_length = 64] + user_id -> Nullable<Varchar>, + #[max_length = 64] + merchant_id -> Nullable<Varchar>, + #[max_length = 64] + profile_id -> Nullable<Varchar>, + #[max_length = 64] + org_id -> Nullable<Varchar>, + #[max_length = 64] + role_id -> Nullable<Varchar>, + user_query -> Nullable<Bytea>, + response -> Nullable<Bytea>, + database_query -> Nullable<Text>, + #[max_length = 64] + interaction_status -> Nullable<Varchar>, + created_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1622,6 +1678,8 @@ diesel::allow_tables_to_appear_in_same_query!( fraud_check, gateway_status_map, generic_link, + hyperswitch_ai_interaction, + hyperswitch_ai_interaction_default, incremental_authorization, locker_mock_up, mandate, diff --git a/crates/hyperswitch_domain_models/src/chat.rs b/crates/hyperswitch_domain_models/src/chat.rs index 31b9f806db7..9243f535c07 100644 --- a/crates/hyperswitch_domain_models/src/chat.rs +++ b/crates/hyperswitch_domain_models/src/chat.rs @@ -12,4 +12,5 @@ pub struct HyperswitchAiDataRequest { pub profile_id: id_type::ProfileId, pub org_id: id_type::OrganizationId, pub query: GetDataMessage, + pub entity_type: common_enums::EntityType, } diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 3f85f8e2b3a..53ce32b033e 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -298,6 +298,29 @@ impl SecretsHandler for settings::UserAuthMethodSettings { } } +#[async_trait::async_trait] +impl SecretsHandler for settings::ChatSettings { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let chat_settings = value.get_inner(); + + let encryption_key = if chat_settings.enabled { + secret_management_client + .get_secret(chat_settings.encryption_key.clone()) + .await? + } else { + chat_settings.encryption_key.clone() + }; + + Ok(value.transition_state(|chat_settings| Self { + encryption_key, + ..chat_settings + })) + } +} + #[async_trait::async_trait] impl SecretsHandler for settings::NetworkTokenizationService { async fn convert_to_raw_secret( @@ -450,9 +473,14 @@ pub(crate) async fn fetch_raw_secrets( }) .await; + #[allow(clippy::expect_used)] + let chat = settings::ChatSettings::convert_to_raw_secret(conf.chat, secret_management_client) + .await + .expect("Failed to decrypt chat configs"); + Settings { server: conf.server, - chat: conf.chat, + chat, master_database, redis: conf.redis, log: conf.log, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 84bc63ca799..1923af66b35 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -71,7 +71,7 @@ pub struct Settings<S: SecretState> { pub server: Server, pub proxy: Proxy, pub env: Env, - pub chat: ChatSettings, + pub chat: SecretStateContainer<ChatSettings, S>, pub master_database: SecretStateContainer<Database, S>, #[cfg(feature = "olap")] pub replica_database: SecretStateContainer<Database, S>, @@ -207,6 +207,7 @@ pub struct Platform { pub struct ChatSettings { pub enabled: bool, pub hyperswitch_ai_host: String, + pub encryption_key: Secret<String>, } #[derive(Debug, Clone, Default, Deserialize)] @@ -1048,8 +1049,7 @@ impl Settings<SecuredSecret> { self.secrets.get_inner().validate()?; self.locker.validate()?; self.connectors.validate("connectors")?; - self.chat.validate()?; - + self.chat.get_inner().validate()?; self.cors.validate()?; self.scheduler diff --git a/crates/router/src/core/chat.rs b/crates/router/src/core/chat.rs index 837a259bed4..a690986a04a 100644 --- a/crates/router/src/core/chat.rs +++ b/crates/router/src/core/chat.rs @@ -1,18 +1,24 @@ use api_models::chat as chat_api; use common_utils::{ consts, + crypto::{DecodeMessage, GcmAes256}, errors::CustomResult, request::{Method, RequestBuilder, RequestContent}, }; use error_stack::ResultExt; use external_services::http_client; use hyperswitch_domain_models::chat as chat_domain; -use router_env::{instrument, logger, tracing}; +use masking::ExposeInterface; +use router_env::{ + instrument, logger, + tracing::{self, Instrument}, +}; use crate::{ db::errors::chat::ChatErrors, routes::{app::SessionStateInfo, SessionState}, - services::{authentication as auth, ApplicationResponse}, + services::{authentication as auth, authorization::roles, ApplicationResponse}, + utils, }; #[instrument(skip_all, fields(?session_id))] @@ -22,15 +28,34 @@ pub async fn get_data_from_hyperswitch_ai_workflow( req: chat_api::ChatRequest, session_id: Option<&str>, ) -> CustomResult<ApplicationResponse<chat_api::ChatResponse>, ChatErrors> { - let url = format!("{}/webhook", state.conf.chat.hyperswitch_ai_host); - let request_id = state.get_request_id(); + let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( + &state, + &user_from_token.role_id, + &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), + ) + .await + .change_context(ChatErrors::InternalServerError) + .attach_printable("Failed to retrieve role information")?; + let url = format!( + "{}/webhook", + state.conf.chat.get_inner().hyperswitch_ai_host + ); + let request_id = state + .get_request_id() + .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); + let request_body = chat_domain::HyperswitchAiDataRequest { query: chat_domain::GetDataMessage { - message: req.message, + message: req.message.clone(), }, - org_id: user_from_token.org_id, - merchant_id: user_from_token.merchant_id, - profile_id: user_from_token.profile_id, + org_id: user_from_token.org_id.clone(), + merchant_id: user_from_token.merchant_id.clone(), + profile_id: user_from_token.profile_id.clone(), + entity_type: role_info.get_entity_type(), }; logger::info!("Request for AI service: {:?}", request_body); @@ -38,11 +63,9 @@ pub async fn get_data_from_hyperswitch_ai_workflow( .method(Method::Post) .url(&url) .attach_default_headers() + .header(consts::X_REQUEST_ID, &request_id) .set_body(RequestContent::Json(Box::new(request_body.clone()))); - if let Some(request_id) = request_id { - request_builder = request_builder.header(consts::X_REQUEST_ID, &request_id); - } if let Some(session_id) = session_id { request_builder = request_builder.header(consts::X_CHAT_SESSION_ID, session_id); } @@ -57,10 +80,132 @@ pub async fn get_data_from_hyperswitch_ai_workflow( .await .change_context(ChatErrors::InternalServerError) .attach_printable("Error when sending request to AI service")? - .json::<_>() + .json::<chat_api::ChatResponse>() .await .change_context(ChatErrors::InternalServerError) .attach_printable("Error when deserializing response from AI service")?; - Ok(ApplicationResponse::Json(response)) + let response_to_return = response.clone(); + tokio::spawn( + async move { + let new_hyperswitch_ai_interaction = utils::chat::construct_hyperswitch_ai_interaction( + &state, + &user_from_token, + &req, + &response, + &request_id, + ) + .await; + + match new_hyperswitch_ai_interaction { + Ok(interaction) => { + let db = state.store.as_ref(); + if let Err(e) = db.insert_hyperswitch_ai_interaction(interaction).await { + logger::error!("Failed to insert hyperswitch_ai_interaction: {:?}", e); + } + } + Err(e) => { + logger::error!("Failed to construct hyperswitch_ai_interaction: {:?}", e); + } + } + } + .in_current_span(), + ); + + Ok(ApplicationResponse::Json(response_to_return)) +} + +#[instrument(skip_all)] +pub async fn list_chat_conversations( + state: SessionState, + user_from_token: auth::UserFromToken, + req: chat_api::ChatListRequest, +) -> CustomResult<ApplicationResponse<chat_api::ChatListResponse>, ChatErrors> { + let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( + &state, + &user_from_token.role_id, + &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), + ) + .await + .change_context(ChatErrors::InternalServerError) + .attach_printable("Failed to retrieve role information")?; + + if !role_info.is_internal() { + return Err(error_stack::Report::new(ChatErrors::UnauthorizedAccess) + .attach_printable("Only internal roles are allowed for this operation")); + } + + let db = state.store.as_ref(); + let hyperswitch_ai_interactions = db + .list_hyperswitch_ai_interactions( + req.merchant_id, + req.limit.unwrap_or(consts::DEFAULT_LIST_LIMIT), + req.offset.unwrap_or(consts::DEFAULT_LIST_OFFSET), + ) + .await + .change_context(ChatErrors::InternalServerError) + .attach_printable("Error when fetching hyperswitch_ai_interactions")?; + + let encryption_key = state.conf.chat.get_inner().encryption_key.clone().expose(); + let key = match hex::decode(&encryption_key) { + Ok(key) => key, + Err(e) => { + router_env::logger::error!("Failed to decode encryption key: {}", e); + encryption_key.as_bytes().to_vec() + } + }; + + let mut conversations = Vec::new(); + + for interaction in hyperswitch_ai_interactions { + let user_query_encrypted = interaction + .user_query + .ok_or(ChatErrors::InternalServerError) + .attach_printable("Missing user_query field in hyperswitch_ai_interaction")?; + let response_encrypted = interaction + .response + .ok_or(ChatErrors::InternalServerError) + .attach_printable("Missing response field in hyperswitch_ai_interaction")?; + + let user_query_decrypted_bytes = GcmAes256 + .decode_message(&key, user_query_encrypted.into_inner()) + .change_context(ChatErrors::InternalServerError) + .attach_printable("Failed to decrypt user query")?; + + let response_decrypted_bytes = GcmAes256 + .decode_message(&key, response_encrypted.into_inner()) + .change_context(ChatErrors::InternalServerError) + .attach_printable("Failed to decrypt response")?; + + let user_query_decrypted = String::from_utf8(user_query_decrypted_bytes) + .change_context(ChatErrors::InternalServerError) + .attach_printable("Failed to convert decrypted user query to string")?; + + let response_decrypted = serde_json::from_slice(&response_decrypted_bytes) + .change_context(ChatErrors::InternalServerError) + .attach_printable("Failed to deserialize decrypted response")?; + + conversations.push(chat_api::ChatConversation { + id: interaction.id, + session_id: interaction.session_id, + user_id: interaction.user_id, + merchant_id: interaction.merchant_id, + profile_id: interaction.profile_id, + org_id: interaction.org_id, + role_id: interaction.role_id, + user_query: user_query_decrypted.into(), + response: response_decrypted, + database_query: interaction.database_query, + interaction_status: interaction.interaction_status, + created_at: interaction.created_at, + }); + } + + return Ok(ApplicationResponse::Json(chat_api::ChatListResponse { + conversations, + })); } diff --git a/crates/router/src/core/errors/chat.rs b/crates/router/src/core/errors/chat.rs index a96afa67de8..d23f0e9bb77 100644 --- a/crates/router/src/core/errors/chat.rs +++ b/crates/router/src/core/errors/chat.rs @@ -6,6 +6,8 @@ pub enum ChatErrors { MissingConfigError, #[error("Chat response deserialization failed")] ChatResponseDeserializationFailed, + #[error("Unauthorized access")] + UnauthorizedAccess, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ChatErrors { @@ -22,6 +24,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::ChatResponseDeserializationFailed => { AER::BadRequest(ApiError::new(sub_code, 2, self.get_error_message(), None)) } + Self::UnauthorizedAccess => { + AER::Unauthorized(ApiError::new(sub_code, 3, self.get_error_message(), None)) + } } } } @@ -32,6 +37,7 @@ impl ChatErrors { Self::InternalServerError => "Something went wrong".to_string(), Self::MissingConfigError => "Missing webhook url".to_string(), Self::ChatResponseDeserializationFailed => "Failed to parse chat response".to_string(), + Self::UnauthorizedAccess => "Not authorized to access the resource".to_string(), } } } diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index f675e316aef..ab3b7cba577 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -20,6 +20,7 @@ pub mod fraud_check; pub mod generic_link; pub mod gsm; pub mod health_check; +pub mod hyperswitch_ai_interaction; pub mod kafka_store; pub mod locker_mock_up; pub mod mandate; @@ -137,6 +138,7 @@ pub trait StorageInterface: + user::sample_data::BatchSampleDataInterface + health_check::HealthCheckDbInterface + user_authentication_method::UserAuthenticationMethodInterface + + hyperswitch_ai_interaction::HyperswitchAiInteractionInterface + authentication::AuthenticationInterface + generic_link::GenericLinkInterface + relay::RelayInterface diff --git a/crates/router/src/db/hyperswitch_ai_interaction.rs b/crates/router/src/db/hyperswitch_ai_interaction.rs new file mode 100644 index 00000000000..4ecf741a088 --- /dev/null +++ b/crates/router/src/db/hyperswitch_ai_interaction.rs @@ -0,0 +1,123 @@ +use diesel_models::hyperswitch_ai_interaction as storage; +use error_stack::report; +use router_env::{instrument, tracing}; + +use super::MockDb; +use crate::{ + connection, + core::errors::{self, CustomResult}, + services::Store, +}; + +#[async_trait::async_trait] +pub trait HyperswitchAiInteractionInterface { + async fn insert_hyperswitch_ai_interaction( + &self, + hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew, + ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError>; + + async fn list_hyperswitch_ai_interactions( + &self, + merchant_id: Option<common_utils::id_type::MerchantId>, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError>; +} + +#[async_trait::async_trait] +impl HyperswitchAiInteractionInterface for Store { + #[instrument(skip_all)] + async fn insert_hyperswitch_ai_interaction( + &self, + hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew, + ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + hyperswitch_ai_interaction + .insert(&conn) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[instrument(skip_all)] + async fn list_hyperswitch_ai_interactions( + &self, + merchant_id: Option<common_utils::id_type::MerchantId>, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::HyperswitchAiInteraction::filter_by_optional_merchant_id( + &conn, + merchant_id.as_ref(), + limit, + offset, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } +} + +#[async_trait::async_trait] +impl HyperswitchAiInteractionInterface for MockDb { + async fn insert_hyperswitch_ai_interaction( + &self, + hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew, + ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError> { + let mut hyperswitch_ai_interactions = self.hyperswitch_ai_interactions.lock().await; + let hyperswitch_ai_interaction = storage::HyperswitchAiInteraction { + id: hyperswitch_ai_interaction.id, + session_id: hyperswitch_ai_interaction.session_id, + user_id: hyperswitch_ai_interaction.user_id, + merchant_id: hyperswitch_ai_interaction.merchant_id, + profile_id: hyperswitch_ai_interaction.profile_id, + org_id: hyperswitch_ai_interaction.org_id, + role_id: hyperswitch_ai_interaction.role_id, + user_query: hyperswitch_ai_interaction.user_query, + response: hyperswitch_ai_interaction.response, + database_query: hyperswitch_ai_interaction.database_query, + interaction_status: hyperswitch_ai_interaction.interaction_status, + created_at: hyperswitch_ai_interaction.created_at, + }; + hyperswitch_ai_interactions.push(hyperswitch_ai_interaction.clone()); + Ok(hyperswitch_ai_interaction) + } + + async fn list_hyperswitch_ai_interactions( + &self, + merchant_id: Option<common_utils::id_type::MerchantId>, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError> { + let hyperswitch_ai_interactions = self.hyperswitch_ai_interactions.lock().await; + + let offset_usize = offset.try_into().unwrap_or_else(|_| { + common_utils::consts::DEFAULT_LIST_OFFSET + .try_into() + .unwrap_or(usize::MIN) + }); + + let limit_usize = limit.try_into().unwrap_or_else(|_| { + common_utils::consts::DEFAULT_LIST_LIMIT + .try_into() + .unwrap_or(usize::MAX) + }); + + let filtered_interactions: Vec<storage::HyperswitchAiInteraction> = + hyperswitch_ai_interactions + .iter() + .filter( + |interaction| match (merchant_id.as_ref(), &interaction.merchant_id) { + (Some(merchant_id), Some(interaction_merchant_id)) => { + interaction_merchant_id == &merchant_id.get_string_repr().to_owned() + } + (None, _) => true, + _ => false, + }, + ) + .skip(offset_usize) + .take(limit_usize) + .cloned() + .collect(); + Ok(filtered_interactions) + } +} diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 9eaef17b9c5..68ef8d19619 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -43,6 +43,7 @@ use time::PrimitiveDateTime; use super::{ dashboard_metadata::DashboardMetadataInterface, ephemeral_key::ClientSecretInterface, + hyperswitch_ai_interaction::HyperswitchAiInteractionInterface, role::RoleInterface, user::{sample_data::BatchSampleDataInterface, theme::ThemeInterface, UserInterface}, user_authentication_method::UserAuthenticationMethodInterface, @@ -4127,6 +4128,29 @@ impl UserAuthenticationMethodInterface for KafkaStore { } } +#[async_trait::async_trait] +impl HyperswitchAiInteractionInterface for KafkaStore { + async fn insert_hyperswitch_ai_interaction( + &self, + hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew, + ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError> { + self.diesel_store + .insert_hyperswitch_ai_interaction(hyperswitch_ai_interaction) + .await + } + + async fn list_hyperswitch_ai_interactions( + &self, + merchant_id: Option<id_type::MerchantId>, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError> { + self.diesel_store + .list_hyperswitch_ai_interactions(merchant_id, limit, offset) + .await + } +} + #[async_trait::async_trait] impl ThemeInterface for KafkaStore { async fn insert_theme( diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index ef3f8081b9a..f12730d7b63 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2343,12 +2343,16 @@ pub struct Chat; impl Chat { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/chat").app_data(web::Data::new(state.clone())); - if state.conf.chat.enabled { + if state.conf.chat.get_inner().enabled { route = route.service( - web::scope("/ai").service( - web::resource("/data") - .route(web::post().to(chat::get_data_from_hyperswitch_ai_workflow)), - ), + web::scope("/ai") + .service( + web::resource("/data") + .route(web::post().to(chat::get_data_from_hyperswitch_ai_workflow)), + ) + .service( + web::resource("/list").route(web::get().to(chat::get_all_conversations)), + ), ); } route diff --git a/crates/router/src/routes/chat.rs b/crates/router/src/routes/chat.rs index e3970cc6a4c..f670bb8e166 100644 --- a/crates/router/src/routes/chat.rs +++ b/crates/router/src/routes/chat.rs @@ -45,3 +45,24 @@ pub async fn get_data_from_hyperswitch_ai_workflow( )) .await } + +#[instrument(skip_all)] +pub async fn get_all_conversations( + state: web::Data<AppState>, + http_req: HttpRequest, + payload: web::Query<chat_api::ChatListRequest>, +) -> HttpResponse { + let flow = Flow::ListAllChatInteractions; + Box::pin(api::server_wrap( + flow.clone(), + state, + &http_req, + payload.into_inner(), + |state, user: auth::UserFromToken, payload, _| { + chat_core::list_chat_conversations(state, user, payload) + }, + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 0c42909b457..c3efb561b42 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -315,7 +315,7 @@ impl From<Flow> for ApiIdentifier { | Flow::ListAllThemesInLineage | Flow::CloneConnector => Self::User, - Flow::GetDataFromHyperswitchAiFlow => Self::AiWorkflow, + Flow::GetDataFromHyperswitchAiFlow | Flow::ListAllChatInteractions => Self::AiWorkflow, Flow::ListRolesV2 | Flow::ListInvitableRolesAtEntityLevel diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 5d4c4a8bb29..e9c26dd30c2 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -21,6 +21,7 @@ pub mod file; pub mod fraud_check; pub mod generic_link; pub mod gsm; +pub mod hyperswitch_ai_interaction; #[cfg(feature = "kv_store")] pub mod kv; pub mod locker_mock_up; @@ -75,8 +76,9 @@ pub use self::{ blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*, callback_mapper::*, capture::*, cards_info::*, configs::*, customers::*, dashboard_metadata::*, dispute::*, dynamic_routing_stats::*, ephemeral_key::*, events::*, file::*, fraud_check::*, - generic_link::*, gsm::*, locker_mock_up::*, mandate::*, merchant_account::*, - merchant_connector_account::*, merchant_key_store::*, payment_link::*, payment_method::*, - process_tracker::*, refund::*, reverse_lookup::*, role::*, routing_algorithm::*, - subscription::*, unified_translations::*, user::*, user_authentication_method::*, user_role::*, + generic_link::*, gsm::*, hyperswitch_ai_interaction::*, locker_mock_up::*, mandate::*, + merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*, + payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*, + routing_algorithm::*, subscription::*, unified_translations::*, user::*, + user_authentication_method::*, user_role::*, }; diff --git a/crates/router/src/types/storage/hyperswitch_ai_interaction.rs b/crates/router/src/types/storage/hyperswitch_ai_interaction.rs new file mode 100644 index 00000000000..30ba3efb49d --- /dev/null +++ b/crates/router/src/types/storage/hyperswitch_ai_interaction.rs @@ -0,0 +1 @@ +pub use diesel_models::hyperswitch_ai_interaction::*; diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index e2acbc4db23..71f1ed404b2 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -1,3 +1,4 @@ +pub mod chat; #[cfg(feature = "olap")] pub mod connector_onboarding; pub mod currency; diff --git a/crates/router/src/utils/chat.rs b/crates/router/src/utils/chat.rs new file mode 100644 index 00000000000..c32b6190a95 --- /dev/null +++ b/crates/router/src/utils/chat.rs @@ -0,0 +1,70 @@ +use api_models::chat as chat_api; +use common_utils::{type_name, types::keymanager::Identifier}; +use diesel_models::hyperswitch_ai_interaction::{ + HyperswitchAiInteraction, HyperswitchAiInteractionNew, +}; +use error_stack::ResultExt; +use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; +use masking::ExposeInterface; + +use crate::{ + core::errors::{self, CustomResult}, + routes::SessionState, + services::authentication as auth, +}; + +pub async fn construct_hyperswitch_ai_interaction( + state: &SessionState, + user_from_token: &auth::UserFromToken, + req: &chat_api::ChatRequest, + response: &chat_api::ChatResponse, + request_id: &str, +) -> CustomResult<HyperswitchAiInteractionNew, errors::ApiErrorResponse> { + let encryption_key = state.conf.chat.get_inner().encryption_key.clone().expose(); + let key = match hex::decode(&encryption_key) { + Ok(key) => key, + Err(e) => { + router_env::logger::error!("Failed to decode encryption key: {}", e); + // Fallback to using the string as bytes, which was the previous behavior + encryption_key.as_bytes().to_vec() + } + }; + let encrypted_user_query = crypto_operation::<String, masking::WithType>( + &state.into(), + type_name!(HyperswitchAiInteraction), + CryptoOperation::Encrypt(req.message.clone()), + Identifier::Merchant(user_from_token.merchant_id.clone()), + &key, + ) + .await + .and_then(|val| val.try_into_operation()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encrypt user query")?; + + let encrypted_response = crypto_operation::<serde_json::Value, masking::WithType>( + &state.into(), + type_name!(HyperswitchAiInteraction), + CryptoOperation::Encrypt(response.response.clone()), + Identifier::Merchant(user_from_token.merchant_id.clone()), + &key, + ) + .await + .and_then(|val| val.try_into_operation()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encrypt response")?; + + Ok(HyperswitchAiInteractionNew { + id: request_id.to_owned(), + session_id: Some(request_id.to_string()), + user_id: Some(user_from_token.user_id.clone()), + merchant_id: Some(user_from_token.merchant_id.get_string_repr().to_string()), + profile_id: Some(user_from_token.profile_id.get_string_repr().to_string()), + org_id: Some(user_from_token.org_id.get_string_repr().to_string()), + role_id: Some(user_from_token.role_id.clone()), + user_query: Some(encrypted_user_query.into()), + response: Some(encrypted_response.into()), + database_query: response.query_executed.clone().map(|q| q.expose()), + interaction_status: Some(response.status.clone()), + created_at: common_utils::date_time::now(), + }) +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index ae5f34fd78f..2345469a4e1 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -357,6 +357,8 @@ pub enum Flow { GsmRuleDelete, /// Get data from embedded flow GetDataFromHyperswitchAiFlow, + // List all chat interactions + ListAllChatInteractions, /// User Sign Up UserSignUp, /// User Sign Up diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index 884d9747943..b3fc53fb8cf 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -65,6 +65,8 @@ pub struct MockDb { pub user_authentication_methods: Arc<Mutex<Vec<store::user_authentication_method::UserAuthenticationMethod>>>, pub themes: Arc<Mutex<Vec<store::user::theme::Theme>>>, + pub hyperswitch_ai_interactions: + Arc<Mutex<Vec<store::hyperswitch_ai_interaction::HyperswitchAiInteraction>>>, } impl MockDb { @@ -113,6 +115,7 @@ impl MockDb { user_key_store: Default::default(), user_authentication_methods: Default::default(), themes: Default::default(), + hyperswitch_ai_interactions: Default::default(), }) } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 7508208069d..d85f5251c39 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -829,8 +829,7 @@ billing_connectors_which_requires_invoice_sync_call = "recurly" [chat] enabled = false hyperswitch_ai_host = "http://0.0.0.0:8000" - - +encryption_key = "" [revenue_recovery.card_config.amex] max_retries_per_day = 20 @@ -846,4 +845,4 @@ max_retry_count_for_thirty_day = 20 [revenue_recovery.card_config.discover] max_retries_per_day = 20 -max_retry_count_for_thirty_day = 20 \ No newline at end of file +max_retry_count_for_thirty_day = 20 diff --git a/migrations/2025-07-21-120614_add_table_for_hyperswitch_ai_interactions/down.sql b/migrations/2025-07-21-120614_add_table_for_hyperswitch_ai_interactions/down.sql new file mode 100644 index 00000000000..8cd51507c46 --- /dev/null +++ b/migrations/2025-07-21-120614_add_table_for_hyperswitch_ai_interactions/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +-- CASCADE will automatically drop all child partitions +DROP TABLE IF EXISTS hyperswitch_ai_interaction CASCADE; diff --git a/migrations/2025-07-21-120614_add_table_for_hyperswitch_ai_interactions/up.sql b/migrations/2025-07-21-120614_add_table_for_hyperswitch_ai_interactions/up.sql new file mode 100644 index 00000000000..e67da66d139 --- /dev/null +++ b/migrations/2025-07-21-120614_add_table_for_hyperswitch_ai_interactions/up.sql @@ -0,0 +1,21 @@ +-- Your SQL goes here +CREATE TABLE hyperswitch_ai_interaction ( + id VARCHAR(64) NOT NULL, + session_id VARCHAR(64), + user_id VARCHAR(64), + merchant_id VARCHAR(64), + profile_id VARCHAR(64), + org_id VARCHAR(64), + role_id VARCHAR(64), + user_query BYTEA, + response BYTEA, + database_query TEXT, + interaction_status VARCHAR(64), + created_at TIMESTAMP NOT NULL, + PRIMARY KEY (id, created_at) +) PARTITION BY RANGE (created_at); + +-- Create a default partition +CREATE TABLE hyperswitch_ai_interaction_default + PARTITION OF hyperswitch_ai_interaction DEFAULT; +
2025-08-04T07:06:02Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Store the user query and response from the ai service for the analysis. - Allow the api only for internal user ### Additional Changes This pull request introduces support for encrypted chat conversations and adds database models and APIs for storing and retrieving chat interactions. The changes span configuration, API models, database schema, and core logic to enable secure chat storage and querying, with proper secret management for encryption keys. **Chat encryption and configuration:** * Added `encryption_key` to `[chat]` sections in all config files and updated `ChatSettings` to use a secret for the encryption key, with secret management integration for secure handling. **Chat API model extensions:** * Added new API models for listing chat conversations (`ChatListRequest`, `ChatConversation`, `ChatListResponse`) **Database schema and models for chat interactions:** * Introduced `hyperswitch_ai_interaction` table and corresponding Rust models for storing encrypted chat queries and **Core chat logic improvements:** * Enhanced chat workflow to fetch role information, set entity type, and use the decrypted chat encryption key for secure communication with the AI service. **Run this as part of migration** 1.Manual Partition creation for next two year. 2.Creates partitions for each 3-month range 3.Add calendar event to re run this after two year. ``` DO $$ DECLARE start_date date; end_date date; i int; partition_name text; BEGIN -- Get start date as the beginning of the current quarter start_date := date_trunc('quarter', current_date)::date; -- Create 8 quarterly partitions (2 years) FOR i IN 1..8 LOOP end_date := (start_date + interval '3 month')::date; partition_name := format( 'hyperswitch_ai_interaction_%s_q%s', to_char(start_date, 'YYYY'), extract(quarter from start_date) ); EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I PARTITION OF hyperswitch_ai_interaction FOR VALUES FROM (%L) TO (%L)', partition_name, start_date, end_date ); start_date := end_date; END LOOP; END$$; ``` **General enhancements and constants:** * Added default limit and offset constants for list operations, improving pagination support for chat conversation queries. - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes #8847 ## How did you test it? Hitting AI service, should store information in DB ``` curl --location 'http://localhost:8080/chat/ai/data' \ --header 'x-feature: integ-custom' \ --header 'x-chat-session-id: chat-dop' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "message": "total count of payments" }' ``` Can check hyperswitch AI interaction table for it. Internal roles can see the list of interactions for the given merchant id List ``` curl --location 'http://localhost:8080/chat/ai/list?merchant_id=merchant_id' \ --header 'Authorization: Bearer JWT' \ --data '' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.117.0
d6e925fd348af9b69bd3a756cd21142eeccd180a
d6e925fd348af9b69bd3a756cd21142eeccd180a
juspay/hyperswitch
juspay__hyperswitch-8844
Bug: [FEATURE] Add support for health check endpoint and setting up configs in v2 ### Feature Description v2 application needs to have an endpoint for setting up configs and health check endpoint. ### Possible Implementation Replicate the v1 implementation ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs index a6261da1be0..e782a3a100c 100644 --- a/crates/api_models/src/health_check.rs +++ b/crates/api_models/src/health_check.rs @@ -14,6 +14,7 @@ pub struct RouterHealthCheckResponse { pub grpc_health_check: HealthCheckMap, #[cfg(feature = "dynamic_routing")] pub decision_engine: bool, + pub unified_connector_service: Option<bool>, } impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {} diff --git a/crates/router/src/core/health_check.rs b/crates/router/src/core/health_check.rs index 7bc65e4d0e4..5df265ec4ee 100644 --- a/crates/router/src/core/health_check.rs +++ b/crates/router/src/core/health_check.rs @@ -40,6 +40,10 @@ pub trait HealthCheckInterface { async fn health_check_decision_engine( &self, ) -> CustomResult<HealthState, errors::HealthCheckDecisionEngineError>; + + async fn health_check_unified_connector_service( + &self, + ) -> CustomResult<HealthState, errors::HealthCheckUnifiedConnectorServiceError>; } #[async_trait::async_trait] @@ -210,4 +214,19 @@ impl HealthCheckInterface for app::SessionState { Ok(HealthState::NotApplicable) } } + + async fn health_check_unified_connector_service( + &self, + ) -> CustomResult<HealthState, errors::HealthCheckUnifiedConnectorServiceError> { + if let Some(_ucs_client) = &self.grpc_client.unified_connector_service_client { + // For now, we'll just check if the client exists and is configured + // In the future, this could be enhanced to make an actual health check call + // to the unified connector service if it supports health check endpoints + logger::debug!("Unified Connector Service client is configured and available"); + Ok(HealthState::Running) + } else { + logger::debug!("Unified Connector Service client not configured"); + Ok(HealthState::NotApplicable) + } + } } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 9584a9af160..08a0d0f386e 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -557,6 +557,7 @@ impl AppState { pub struct Health; +#[cfg(feature = "v1")] impl Health { pub fn server(state: AppState) -> Scope { web::scope("health") @@ -566,6 +567,16 @@ impl Health { } } +#[cfg(feature = "v2")] +impl Health { + pub fn server(state: AppState) -> Scope { + web::scope("/v2/health") + .app_data(web::Data::new(state)) + .service(web::resource("").route(web::get().to(health))) + .service(web::resource("/ready").route(web::get().to(deep_health_check))) + } +} + #[cfg(feature = "dummy_connector")] pub struct DummyConnector; @@ -1852,7 +1863,7 @@ impl Webhooks { pub struct Configs; -#[cfg(any(feature = "olap", feature = "oltp"))] +#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] impl Configs { pub fn server(config: AppState) -> Scope { web::scope("/configs") @@ -1867,6 +1878,21 @@ impl Configs { } } +#[cfg(all(feature = "v2", any(feature = "olap", feature = "oltp")))] +impl Configs { + pub fn server(config: AppState) -> Scope { + web::scope("/v2/configs") + .app_data(web::Data::new(config)) + .service(web::resource("/").route(web::post().to(config_key_create))) + .service( + web::resource("/{key}") + .route(web::get().to(config_key_retrieve)) + .route(web::post().to(config_key_update)) + .route(web::delete().to(config_key_delete)), + ) + } +} + pub struct ApplePayCertificatesMigration; #[cfg(all(feature = "olap", feature = "v1"))] diff --git a/crates/router/src/routes/configs.rs b/crates/router/src/routes/configs.rs index 74b9cd73b1e..1425fda32ba 100644 --- a/crates/router/src/routes/configs.rs +++ b/crates/router/src/routes/configs.rs @@ -8,6 +8,11 @@ use crate::{ types::api as api_types, }; +#[cfg(feature = "v1")] +const ADMIN_API_AUTH: auth::AdminApiAuth = auth::AdminApiAuth; +#[cfg(feature = "v2")] +const ADMIN_API_AUTH: auth::V2AdminApiAuth = auth::V2AdminApiAuth; + #[instrument(skip_all, fields(flow = ?Flow::CreateConfigKey))] pub async fn config_key_create( state: web::Data<AppState>, @@ -23,7 +28,7 @@ pub async fn config_key_create( &req, payload, |state, _, data, _| configs::set_config(state, data), - &auth::AdminApiAuth, + &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, ) .await @@ -43,7 +48,7 @@ pub async fn config_key_retrieve( &req, &key, |state, _, key, _| configs::read_config(state, key), - &auth::AdminApiAuth, + &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, ) .await @@ -66,7 +71,7 @@ pub async fn config_key_update( &req, &payload, |state, _, payload, _| configs::update_config(state, payload), - &auth::AdminApiAuth, + &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, ) .await @@ -87,7 +92,7 @@ pub async fn config_key_delete( &req, key, |state, _, key, _| configs::config_delete(state, key), - &auth::AdminApiAuth, + &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, ) .await diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs index f2ed05030da..b7818c0db5b 100644 --- a/crates/router/src/routes/health.rs +++ b/crates/router/src/routes/health.rs @@ -150,6 +150,21 @@ async fn deep_health_check_func( logger::debug!("Outgoing Request health check end"); + logger::debug!("Unified Connector Service health check begin"); + + let unified_connector_service_status = state + .health_check_unified_connector_service() + .await + .map_err(|error| { + let message = error.to_string(); + error.change_context(errors::ApiErrorResponse::HealthCheckError { + component: "Unified Connector Service", + message, + }) + })?; + + logger::debug!("Unified Connector Service health check end"); + let response = RouterHealthCheckResponse { database: db_status.into(), redis: redis_status.into(), @@ -163,6 +178,7 @@ async fn deep_health_check_func( grpc_health_check, #[cfg(feature = "dynamic_routing")] decision_engine: decision_engine_health_check.into(), + unified_connector_service: unified_connector_service_status.into(), }; Ok(api::ApplicationResponse::Json(response)) diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index 89326d9a71c..a2b4dad779b 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -294,3 +294,9 @@ pub enum HealthCheckDecisionEngineError { #[error("Failed to establish Decision Engine connection")] FailedToCallDecisionEngineService, } + +#[derive(Debug, Clone, thiserror::Error)] +pub enum HealthCheckUnifiedConnectorServiceError { + #[error("Failed to establish Unified Connector Service connection")] + FailedToCallUnifiedConnectorService, +}
2025-08-05T06:19:58Z
## 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 --> Introduced` /v2/configs` and `/v2/health` endpoints and for v2 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> introduced configs and health endpoints for v2 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Manual. 1. Hit V2 health endpoint. ``` curl --location '{{base_url}}/v2/health/ready' \ --header 'Content-Type: application/json' \ --header 'x-tenant-id: public' \ --data '' ``` response: ``` { "database": true, "redis": true, "analytics": true, "opensearch": false, "outgoing_request": true, "unified_connector_service": true } ``` 2. Create a test v2 config ``` curl --location '{{baseUrl}}/v2/configs/' \ --header 'Content-Type: application/json' \ --header 'x-tenant-id: public' \ --header 'authorization: admin-api-key=test_admin' \ --data ' { "key": "test_v2_config_1", "value": "true" } ' ``` 2. Retrive the test v2 config ``` curl --location '{{baseUrl}}/v2/configs/test_v2_config_1' \ --header 'Content-Type: application/json' \ --header 'x-tenant-id: public' \ --header 'authorization: admin-api-key=test_admin' \ --data '' ``` Response for 2 and 3: ``` { "key": "test_v2_config_1", "value": "true" } ``` 3. Config Update ``` curl --location '{{baseUrl}}/v2/configs/test_v2_config_1' \ --header 'Content-Type: application/json' \ --header 'x-tenant-id: public' \ --header 'authorization: admin-api-key=test_admin' \ --data '{ "value": "false" }' ``` Response: ``` { "key": "test_v2_config_1", "value": "true" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.115.0
90f3b09a77484a4262608b0a4eeca7d452a4c968
90f3b09a77484a4262608b0a4eeca7d452a4c968
juspay/hyperswitch
juspay__hyperswitch-8841
Bug: refactor(euclid): refactor logs for evaluation of equality for dynamic routing evaluate response Improve the logs for better diffs between legacy and decision_engine's euclid.
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 547f49ce552..19ddeb7f15f 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -48,7 +48,6 @@ use rand::SeedableRng; use router_env::{instrument, tracing}; use rustc_hash::FxHashMap; use storage_impl::redis::cache::{CacheKey, CGRAPH_CACHE, ROUTING_CACHE}; -use utils::perform_decision_euclid_routing; #[cfg(feature = "v2")] use crate::core::admin; @@ -492,33 +491,24 @@ pub async fn perform_static_routing_v1( .to_string(), }; - let de_euclid_connectors = if state.conf.open_router.static_routing_enabled { - let routing_events_wrapper = utils::RoutingEventsWrapper::new( - state.tenant.tenant_id.clone(), - state.request_id, - payment_id, - business_profile.get_id().to_owned(), - business_profile.merchant_id.to_owned(), - "DecisionEngine: Euclid Static Routing".to_string(), - None, - true, - false, - ); - - perform_decision_euclid_routing( + // Decision of de-routing is stored + let de_evaluated_connector = if !state.conf.open_router.static_routing_enabled { + logger::debug!("decision_engine_euclid: decision_engine routing not enabled"); + Vec::default() + } else { + utils::decision_engine_routing( state, backend_input.clone(), - business_profile.get_id().get_string_repr().to_string(), - routing_events_wrapper, + business_profile, + payment_id, get_merchant_fallback_config().await?, ) .await .map_err(|e| // errors are ignored as this is just for diff checking as of now (optional flow). logger::error!(decision_engine_euclid_evaluate_error=?e, "decision_engine_euclid: error in evaluation of rule") - ).unwrap_or_default() - } else { - Vec::default() + ) + .unwrap_or_default() }; let (routable_connectors, routing_approach) = match cached_algorithm.as_ref() { @@ -538,8 +528,14 @@ pub async fn perform_static_routing_v1( ), }; + // Results are logged for diff(between legacy and decision_engine's euclid) and have parameters as: + // is_equal: verifies all output are matching in order, + // is_equal_length: matches length of both outputs (useful for verifying volume based routing + // results) + // de_response: response from the decision_engine's euclid + // hs_response: response from legacy_euclid utils::compare_and_log_result( - de_euclid_connectors.clone(), + de_evaluated_connector.clone(), routable_connectors.clone(), "evaluate_routing".to_string(), ); @@ -549,7 +545,7 @@ pub async fn perform_static_routing_v1( state, business_profile, routable_connectors, - de_euclid_connectors, + de_evaluated_connector, ) .await, routing_approach, diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rs index d9d5ed1de26..3c7a081d41f 100644 --- a/crates/router/src/core/payments/routing/utils.rs +++ b/crates/router/src/core/payments/routing/utils.rs @@ -1,4 +1,7 @@ -use std::collections::{HashMap, HashSet}; +use std::{ + collections::{HashMap, HashSet}, + str::FromStr, +}; use api_models::{ open_router as or_types, @@ -9,7 +12,7 @@ use api_models::{ }, }; use async_trait::async_trait; -use common_enums::TransactionType; +use common_enums::{RoutableConnectors, TransactionType}; use common_utils::{ ext_traits::{BytesExt, StringExt}, id_type, @@ -30,6 +33,7 @@ use serde::{Deserialize, Serialize}; use super::RoutingResult; use crate::{ core::errors, + db::domain, routes::{app::SessionStateInfo, SessionState}, services::{self, logger}, types::transformers::ForeignInto, @@ -301,7 +305,7 @@ pub async fn perform_decision_euclid_routing( created_by: String, events_wrapper: RoutingEventsWrapper<RoutingEvaluateRequest>, fallback_output: Vec<RoutableConnectorChoice>, -) -> RoutingResult<Vec<RoutableConnectorChoice>> { +) -> RoutingResult<RoutingEvaluateResponse> { logger::debug!("decision_engine_euclid: evaluate api call for euclid routing evaluation"); let mut events_wrapper = events_wrapper; @@ -348,8 +352,254 @@ pub async fn perform_decision_euclid_routing( logger::debug!(decision_engine_euclid_response=?euclid_response,"decision_engine_euclid"); logger::debug!(decision_engine_euclid_selected_connector=?euclid_response.evaluated_output,"decision_engine_euclid"); + Ok(euclid_response) +} + +/// This function transforms the decision_engine response in a way that's usable for further flows: +/// It places evaluated_output connectors first, followed by remaining output connectors (no duplicates). +pub fn transform_de_output_for_router( + de_output: Vec<ConnectorInfo>, + de_evaluated_output: Vec<RoutableConnectorChoice>, +) -> RoutingResult<Vec<RoutableConnectorChoice>> { + let mut seen = HashSet::new(); + + // evaluated connectors on top, to ensure the fallback is based on other connectors. + let mut ordered = Vec::with_capacity(de_output.len() + de_evaluated_output.len()); + for eval_conn in de_evaluated_output { + if seen.insert(eval_conn.connector) { + ordered.push(eval_conn); + } + } + + // Add remaining connectors from de_output (only if not already seen), for fallback + for conn in de_output { + let key = RoutableConnectors::from_str(&conn.gateway_name).map_err(|_| { + errors::RoutingError::GenericConversionError { + from: "String".to_string(), + to: "RoutableConnectors".to_string(), + } + })?; + if seen.insert(key) { + let de_choice = DeRoutableConnectorChoice::try_from(conn)?; + ordered.push(RoutableConnectorChoice::from(de_choice)); + } + } + Ok(ordered) +} + +pub async fn decision_engine_routing( + state: &SessionState, + backend_input: BackendInput, + business_profile: &domain::Profile, + payment_id: String, + merchant_fallback_config: Vec<RoutableConnectorChoice>, +) -> RoutingResult<Vec<RoutableConnectorChoice>> { + let routing_events_wrapper = RoutingEventsWrapper::new( + state.tenant.tenant_id.clone(), + state.request_id, + payment_id, + business_profile.get_id().to_owned(), + business_profile.merchant_id.to_owned(), + "DecisionEngine: Euclid Static Routing".to_string(), + None, + true, + false, + ); + + let de_euclid_evaluate_response = perform_decision_euclid_routing( + state, + backend_input.clone(), + business_profile.get_id().get_string_repr().to_string(), + routing_events_wrapper, + merchant_fallback_config, + ) + .await; + + let Ok(de_euclid_response) = de_euclid_evaluate_response else { + logger::error!("decision_engine_euclid_evaluation_error: error in evaluation of rule"); + return Ok(Vec::default()); + }; + + let de_output_conenctor = extract_de_output_connectors(de_euclid_response.output) + .map_err(|e| { + logger::error!(error=?e, "decision_engine_euclid_evaluation_error: Failed to extract connector from Output"); + e + })?; + + transform_de_output_for_router( + de_output_conenctor.clone(), + de_euclid_response.evaluated_output.clone(), + ) + .map_err(|e| { + logger::error!(error=?e, "decision_engine_euclid_evaluation_error: failed to transform connector from de-output"); + e + }) +} + +/// Custom deserializer for output from decision_engine, this is required as untagged enum is +/// stored but the enum requires tagged deserialization, hence deserializing it into specific +/// variants +pub fn extract_de_output_connectors( + output_value: serde_json::Value, +) -> RoutingResult<Vec<ConnectorInfo>> { + const SINGLE: &str = "straight_through"; + const PRIORITY: &str = "priority"; + const VOLUME_SPLIT: &str = "volume_split"; + const VOLUME_SPLIT_PRIORITY: &str = "volume_split_priority"; + + let obj = output_value.as_object().ok_or_else(|| { + logger::error!("decision_engine_euclid_error: output is not a JSON object"); + errors::RoutingError::OpenRouterError("Expected output to be a JSON object".into()) + })?; + + let type_str = obj.get("type").and_then(|v| v.as_str()).ok_or_else(|| { + logger::error!("decision_engine_euclid_error: missing or invalid 'type' in output"); + errors::RoutingError::OpenRouterError("Missing or invalid 'type' field in output".into()) + })?; + + match type_str { + SINGLE => { + let connector_value = obj.get("connector").ok_or_else(|| { + logger::error!( + "decision_engine_euclid_error: missing 'connector' field for type=single" + ); + errors::RoutingError::OpenRouterError( + "Missing 'connector' field for single output".into(), + ) + })?; + let connector: ConnectorInfo = serde_json::from_value(connector_value.clone()) + .map_err(|e| { + logger::error!( + ?e, + "decision_engine_euclid_error: Failed to parse single connector" + ); + errors::RoutingError::OpenRouterError( + "Failed to deserialize single connector".into(), + ) + })?; + Ok(vec![connector]) + } + + PRIORITY => { + let connectors_value = obj.get("connectors").ok_or_else(|| { + logger::error!( + "decision_engine_euclid_error: missing 'connectors' field for type=priority" + ); + errors::RoutingError::OpenRouterError( + "Missing 'connectors' field for priority output".into(), + ) + })?; + let connectors: Vec<ConnectorInfo> = serde_json::from_value(connectors_value.clone()) + .map_err(|e| { + logger::error!( + ?e, + "decision_engine_euclid_error: Failed to parse connectors for priority" + ); + errors::RoutingError::OpenRouterError( + "Failed to deserialize priority connectors".into(), + ) + })?; + Ok(connectors) + } + + VOLUME_SPLIT => { + let splits_value = obj.get("splits").ok_or_else(|| { + logger::error!( + "decision_engine_euclid_error: missing 'splits' field for type=volume_split" + ); + errors::RoutingError::OpenRouterError( + "Missing 'splits' field for volume_split output".into(), + ) + })?; - Ok(euclid_response.evaluated_output) + // Transform each {connector, split} into {output, split} + let fixed_splits: Vec<_> = splits_value + .as_array() + .ok_or_else(|| { + logger::error!("decision_engine_euclid_error: 'splits' is not an array"); + errors::RoutingError::OpenRouterError("'splits' field must be an array".into()) + })? + .iter() + .map(|entry| { + let mut entry_map = entry.as_object().cloned().ok_or_else(|| { + logger::error!( + "decision_engine_euclid_error: invalid split entry in volume_split" + ); + errors::RoutingError::OpenRouterError( + "Invalid entry in splits array".into(), + ) + })?; + if let Some(connector) = entry_map.remove("connector") { + entry_map.insert("output".to_string(), connector); + } + Ok::<_, error_stack::Report<errors::RoutingError>>(serde_json::Value::Object( + entry_map, + )) + }) + .collect::<Result<Vec<_>, _>>()?; + + let splits: Vec<VolumeSplit<ConnectorInfo>> = + serde_json::from_value(serde_json::Value::Array(fixed_splits)).map_err(|e| { + logger::error!( + ?e, + "decision_engine_euclid_error: Failed to parse volume_split" + ); + errors::RoutingError::OpenRouterError( + "Failed to deserialize volume_split connectors".into(), + ) + })?; + + Ok(splits.into_iter().map(|s| s.output).collect()) + } + + VOLUME_SPLIT_PRIORITY => { + let splits_value = obj.get("splits").ok_or_else(|| { + logger::error!("decision_engine_euclid_error: missing 'splits' field for type=volume_split_priority"); + errors::RoutingError::OpenRouterError("Missing 'splits' field for volume_split_priority output".into()) + })?; + + // Transform each {connector: [...], split} into {output: [...], split} + let fixed_splits: Vec<_> = splits_value + .as_array() + .ok_or_else(|| { + logger::error!("decision_engine_euclid_error: 'splits' is not an array"); + errors::RoutingError::OpenRouterError("'splits' field must be an array".into()) + })? + .iter() + .map(|entry| { + let mut entry_map = entry.as_object().cloned().ok_or_else(|| { + logger::error!("decision_engine_euclid_error: invalid split entry in volume_split_priority"); + errors::RoutingError::OpenRouterError("Invalid entry in splits array".into()) + })?; + if let Some(connector) = entry_map.remove("connector") { + entry_map.insert("output".to_string(), connector); + } + Ok::<_, error_stack::Report<errors::RoutingError>>(serde_json::Value::Object(entry_map)) + }) + .collect::<Result<Vec<_>, _>>()?; + + let splits: Vec<VolumeSplit<Vec<ConnectorInfo>>> = + serde_json::from_value(serde_json::Value::Array(fixed_splits)).map_err(|e| { + logger::error!( + ?e, + "decision_engine_euclid_error: Failed to parse volume_split_priority" + ); + errors::RoutingError::OpenRouterError( + "Failed to deserialize volume_split_priority connectors".into(), + ) + })?; + + Ok(splits.into_iter().flat_map(|s| s.output).collect()) + } + + other => { + logger::error!(type_str=%other, "decision_engine_euclid_error: unknown output type"); + Err( + errors::RoutingError::OpenRouterError(format!("Unknown output type: {other}")) + .into(), + ) + } + } } pub async fn create_de_euclid_routing_algo( @@ -460,17 +710,13 @@ pub fn compare_and_log_result<T: RoutingEq<T> + Serialize>( result: Vec<T>, flow: String, ) { - let is_equal = de_result.len() == result.len() - && de_result - .iter() - .zip(result.iter()) - .all(|(a, b)| T::is_equal(a, b)); - - if is_equal { - router_env::logger::info!(routing_flow=?flow, is_equal=?is_equal, "decision_engine_euclid"); - } else { - router_env::logger::debug!(routing_flow=?flow, is_equal=?is_equal, de_response=?to_json_string(&de_result), hs_response=?to_json_string(&result), "decision_engine_euclid"); - } + let is_equal = de_result + .iter() + .zip(result.iter()) + .all(|(a, b)| T::is_equal(a, b)); + + let is_equal_in_length = de_result.len() == result.len(); + router_env::logger::debug!(routing_flow=?flow, is_equal=?is_equal, is_equal_length=?is_equal_in_length, de_response=?to_json_string(&de_result), hs_response=?to_json_string(&result), "decision_engine_euclid"); } pub trait RoutingEq<T> { @@ -685,6 +931,8 @@ impl DecisionEngineErrorsInterface for or_types::ErrorResponse { } } +pub type Metadata = HashMap<String, serde_json::Value>; + /// Represents a single comparison condition. #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -775,6 +1023,36 @@ pub struct ConnectorInfo { pub gateway_id: Option<String>, } +impl TryFrom<ConnectorInfo> for DeRoutableConnectorChoice { + type Error = error_stack::Report<errors::RoutingError>; + + fn try_from(c: ConnectorInfo) -> Result<Self, Self::Error> { + let gateway_id = c + .gateway_id + .map(|mca| { + id_type::MerchantConnectorAccountId::wrap(mca) + .change_context(errors::RoutingError::GenericConversionError { + from: "String".to_string(), + to: "MerchantConnectorAccountId".to_string(), + }) + .attach_printable("unable to convert MerchantConnectorAccountId from string") + }) + .transpose()?; + + let gateway_name = RoutableConnectors::from_str(&c.gateway_name) + .map_err(|_| errors::RoutingError::GenericConversionError { + from: "String".to_string(), + to: "RoutableConnectors".to_string(), + }) + .attach_printable("unable to convert connector name to RoutableConnectors")?; + + Ok(Self { + gateway_name, + gateway_id, + }) + } +} + impl ConnectorInfo { pub fn new(gateway_name: String, gateway_id: Option<String>) -> Self { Self { @@ -795,7 +1073,6 @@ pub enum Output { pub type Globals = HashMap<String, HashSet<ValueType>>; -pub type Metadata = HashMap<String, serde_json::Value>; /// The program, having a default connector selection and /// a bunch of rules. Also can hold arbitrary metadata. #[derive(Clone, Debug, Serialize, Deserialize)]
2025-08-04T12:02:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR refactors the routing logic to improve how **logs are emitted and connector evaluation is handled** when dynamic routing is performed using the Decision Engine (Euclid). Key updates include: - Replaces raw response propagation from `perform_decision_euclid_routing` with a wrapped `RoutingEvaluateResponse` containing both `output` and `evaluated_output`. - Introduces a new function `extract_de_output_connectors()` to deserialize and normalize `output` from Euclid into a list of `ConnectorInfo`. - Adds `transform_de_output_for_router()` to combine `output` and `evaluated_output`, ensuring deduplication and priority order. - Enhances logging in `compare_and_log_result` to include diff details between `de_result` and `router_result` more clearly. - Adds `TryFrom<ConnectorInfo> for DeRoutableConnectorChoice` to safely convert API inputs to internal representations. ## Diff Hunk Explanation ### `crates/router/src/core/payments/routing.rs` - Renamed `de_euclid_connectors` β†’ `de_evaluated_connector` to reflect the structured response. - Wrapped `perform_decision_euclid_routing` call with success match block to: - Extract connectors from `output` using `extract_de_output_connectors`. - Merge `output` and `evaluated_output` using `transform_de_output_for_router`. - Updated logs to emit clearer error/debug statements during extraction, transformation, and comparison. ### `crates/router/src/core/payments/routing/utils.rs` - Refactored `perform_decision_euclid_routing` to return `RoutingEvaluateResponse` instead of just connector list. - Added `extract_de_output_connectors`: deserializes various output types (`single`, `priority`, `volume_split`, etc.). - Added `transform_de_output_for_router`: deduplicates connectors and maintains priority between `evaluated_output` and fallback `output`. - Improved `compare_and_log_result` to log equality and diff details between Decision Engine result and final connector result. - Introduced `TryFrom<ConnectorInfo>` for `DeRoutableConnectorChoice`. This refactor sets the stage for cleaner observability and deterministic routing behavior between evaluated and fallback paths. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> The testing guidelines are present in this [doc](https://docs.google.com/document/d/1Atb-5bIgA-H_H2lS2O-plhtGUqHK4fcQ1XDXWjrcTHE/edit?usp=sharing). ## 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.115.0
d418e1e59e2f4fd725c07a70cccabb992e1c12c6
d418e1e59e2f4fd725c07a70cccabb992e1c12c6
juspay/hyperswitch
juspay__hyperswitch-8842
Bug: [FEATURE]:Store the user query of the chat bot Store the user query and response from the ai service for the analysis. Allow the api only for internal user
diff --git a/config/config.example.toml b/config/config.example.toml index b725be102c1..134e0a49e84 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -1257,6 +1257,7 @@ allow_connected_merchants = false # Enable or disable connected merchant account [chat] enabled = false # Enable or disable chat features hyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow host +encryption_key = "" # Key to encrypt and decrypt chats [proxy_status_mapping] proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index bfba035c1f3..fe8b09cd7db 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -419,6 +419,7 @@ max_random_schedule_delay_in_seconds = 300 # max random delay in seconds to sche [chat] enabled = false # Enable or disable chat features hyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow host +encryption_key = "" # Key to encrypt and decrypt chats [proxy_status_mapping] proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response diff --git a/config/development.toml b/config/development.toml index 940e43b50ca..e4cbe3af226 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1368,6 +1368,7 @@ version = "HOSTNAME" [chat] enabled = false hyperswitch_ai_host = "http://0.0.0.0:8000" +encryption_key = "" [proxy_status_mapping] proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response diff --git a/config/docker_compose.toml b/config/docker_compose.toml index d299323f2c1..62f6830832c 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -1226,6 +1226,7 @@ allow_connected_merchants = true [chat] enabled = false hyperswitch_ai_host = "http://0.0.0.0:8000" +encryption_key = "" [authentication_providers] click_to_pay = {connector_list = "adyen, cybersource, trustpay"} diff --git a/crates/api_models/src/chat.rs b/crates/api_models/src/chat.rs index c66b42cc4f4..975197fd3fc 100644 --- a/crates/api_models/src/chat.rs +++ b/crates/api_models/src/chat.rs @@ -1,12 +1,13 @@ use common_utils::id_type; use masking::Secret; +use time::PrimitiveDateTime; #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct ChatRequest { pub message: Secret<String>, } -#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct ChatResponse { pub response: Secret<serde_json::Value>, pub merchant_id: id_type::MerchantId, @@ -16,3 +17,32 @@ pub struct ChatResponse { #[serde(skip_serializing)] pub row_count: Option<i32>, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct ChatListRequest { + pub merchant_id: Option<id_type::MerchantId>, + pub limit: Option<i64>, + pub offset: Option<i64>, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct ChatConversation { + pub id: String, + pub session_id: Option<String>, + pub user_id: Option<String>, + pub merchant_id: Option<String>, + pub profile_id: Option<String>, + pub org_id: Option<String>, + pub role_id: Option<String>, + pub user_query: Secret<String>, + pub response: Secret<serde_json::Value>, + pub database_query: Option<String>, + pub interaction_status: Option<String>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct ChatListResponse { + pub conversations: Vec<ChatConversation>, +} diff --git a/crates/api_models/src/events/chat.rs b/crates/api_models/src/events/chat.rs index 42fefe487e9..38f20b0c3bb 100644 --- a/crates/api_models/src/events/chat.rs +++ b/crates/api_models/src/events/chat.rs @@ -1,5 +1,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; -use crate::chat::{ChatRequest, ChatResponse}; +use crate::chat::{ChatListRequest, ChatListResponse, ChatRequest, ChatResponse}; -common_utils::impl_api_event_type!(Chat, (ChatRequest, ChatResponse)); +common_utils::impl_api_event_type!( + Chat, + (ChatRequest, ChatResponse, ChatListRequest, ChatListResponse) +); diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index 28508749f35..59ec5377690 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -197,3 +197,9 @@ pub const REQUEST_TIME_OUT: u64 = 30; /// API client request timeout for ai service (in seconds) pub const REQUEST_TIME_OUT_FOR_AI_SERVICE: u64 = 120; + +/// Default limit for list operations (can be used across different entities) +pub const DEFAULT_LIST_LIMIT: i64 = 100; + +/// Default offset for list operations (can be used across different entities) +pub const DEFAULT_LIST_OFFSET: i64 = 0; diff --git a/crates/diesel_models/src/hyperswitch_ai_interaction.rs b/crates/diesel_models/src/hyperswitch_ai_interaction.rs new file mode 100644 index 00000000000..a22bd288c19 --- /dev/null +++ b/crates/diesel_models/src/hyperswitch_ai_interaction.rs @@ -0,0 +1,49 @@ +use common_utils::encryption::Encryption; +use diesel::{self, Identifiable, Insertable, Queryable, Selectable}; +use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; + +use crate::schema::hyperswitch_ai_interaction; + +#[derive( + Clone, + Debug, + Deserialize, + Identifiable, + Queryable, + Selectable, + Serialize, + router_derive::DebugAsDisplay, +)] +#[diesel(table_name = hyperswitch_ai_interaction, primary_key(id, created_at), check_for_backend(diesel::pg::Pg))] +pub struct HyperswitchAiInteraction { + pub id: String, + pub session_id: Option<String>, + pub user_id: Option<String>, + pub merchant_id: Option<String>, + pub profile_id: Option<String>, + pub org_id: Option<String>, + pub role_id: Option<String>, + pub user_query: Option<Encryption>, + pub response: Option<Encryption>, + pub database_query: Option<String>, + pub interaction_status: Option<String>, + pub created_at: PrimitiveDateTime, +} + +#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] +#[diesel(table_name = hyperswitch_ai_interaction)] +pub struct HyperswitchAiInteractionNew { + pub id: String, + pub session_id: Option<String>, + pub user_id: Option<String>, + pub merchant_id: Option<String>, + pub profile_id: Option<String>, + pub org_id: Option<String>, + pub role_id: Option<String>, + pub user_query: Option<Encryption>, + pub response: Option<Encryption>, + pub database_query: Option<String>, + pub interaction_status: Option<String>, + pub created_at: PrimitiveDateTime, +} diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index caf979b2c5f..b715134f926 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -23,6 +23,7 @@ pub mod file; pub mod fraud_check; pub mod generic_link; pub mod gsm; +pub mod hyperswitch_ai_interaction; #[cfg(feature = "kv_store")] pub mod kv; pub mod locker_mock_up; @@ -69,10 +70,11 @@ pub type StorageResult<T> = error_stack::Result<T, errors::DatabaseError>; pub type PgPooledConn = async_bb8_diesel::Connection<diesel::PgConnection>; pub use self::{ address::*, api_keys::*, callback_mapper::*, cards_info::*, configs::*, customers::*, - dispute::*, ephemeral_key::*, events::*, file::*, generic_link::*, locker_mock_up::*, - mandate::*, merchant_account::*, merchant_connector_account::*, payment_attempt::*, - payment_intent::*, payment_method::*, payout_attempt::*, payouts::*, process_tracker::*, - refund::*, reverse_lookup::*, user_authentication_method::*, + dispute::*, ephemeral_key::*, events::*, file::*, generic_link::*, + hyperswitch_ai_interaction::*, locker_mock_up::*, mandate::*, merchant_account::*, + merchant_connector_account::*, payment_attempt::*, payment_intent::*, payment_method::*, + payout_attempt::*, payouts::*, process_tracker::*, refund::*, reverse_lookup::*, + user_authentication_method::*, }; /// The types and implementations provided by this module are required for the schema generated by /// `diesel_cli` 2.0 to work with the types defined in Rust code. This is because diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs index 17eae2427e7..2dc6c18a1a1 100644 --- a/crates/diesel_models/src/query.rs +++ b/crates/diesel_models/src/query.rs @@ -21,6 +21,7 @@ pub mod fraud_check; pub mod generic_link; pub mod generics; pub mod gsm; +pub mod hyperswitch_ai_interaction; pub mod locker_mock_up; pub mod mandate; pub mod merchant_account; diff --git a/crates/diesel_models/src/query/hyperswitch_ai_interaction.rs b/crates/diesel_models/src/query/hyperswitch_ai_interaction.rs new file mode 100644 index 00000000000..91db3ec468e --- /dev/null +++ b/crates/diesel_models/src/query/hyperswitch_ai_interaction.rs @@ -0,0 +1,32 @@ +use diesel::{associations::HasTable, ExpressionMethods}; + +use crate::{ + hyperswitch_ai_interaction::{HyperswitchAiInteraction, HyperswitchAiInteractionNew}, + query::generics, + schema::hyperswitch_ai_interaction::dsl, + PgPooledConn, StorageResult, +}; + +impl HyperswitchAiInteractionNew { + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<HyperswitchAiInteraction> { + generics::generic_insert(conn, self).await + } +} + +impl HyperswitchAiInteraction { + pub async fn filter_by_optional_merchant_id( + conn: &PgPooledConn, + merchant_id: Option<&common_utils::id_type::MerchantId>, + limit: i64, + offset: i64, + ) -> StorageResult<Vec<Self>> { + generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( + conn, + dsl::merchant_id.eq(merchant_id.cloned()), + Some(limit), + Some(offset), + Some(dsl::created_at.desc()), + ) + .await + } +} diff --git a/crates/diesel_models/src/query/utils.rs b/crates/diesel_models/src/query/utils.rs index fe2f43d419b..96a41f10ca0 100644 --- a/crates/diesel_models/src/query/utils.rs +++ b/crates/diesel_models/src/query/utils.rs @@ -52,6 +52,12 @@ mod composite_key { self.0 } } + impl CompositeKey for <schema::hyperswitch_ai_interaction::table as diesel::Table>::PrimaryKey { + type UK = schema::hyperswitch_ai_interaction::dsl::id; + fn get_local_unique_key(&self) -> Self::UK { + self.0 + } + } impl CompositeKey for <schema_v2::incremental_authorization::table as diesel::Table>::PrimaryKey { type UK = schema_v2::incremental_authorization::dsl::authorization_id; fn get_local_unique_key(&self) -> Self::UK { @@ -139,6 +145,7 @@ impl_get_primary_key_for_composite!( schema::customers::table, schema::blocklist::table, schema::incremental_authorization::table, + schema::hyperswitch_ai_interaction::table, schema_v2::incremental_authorization::table, schema_v2::blocklist::table ); diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 79df62ac4b2..271d2a79ba0 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -632,6 +632,62 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + hyperswitch_ai_interaction (id, created_at) { + #[max_length = 64] + id -> Varchar, + #[max_length = 64] + session_id -> Nullable<Varchar>, + #[max_length = 64] + user_id -> Nullable<Varchar>, + #[max_length = 64] + merchant_id -> Nullable<Varchar>, + #[max_length = 64] + profile_id -> Nullable<Varchar>, + #[max_length = 64] + org_id -> Nullable<Varchar>, + #[max_length = 64] + role_id -> Nullable<Varchar>, + user_query -> Nullable<Bytea>, + response -> Nullable<Bytea>, + database_query -> Nullable<Text>, + #[max_length = 64] + interaction_status -> Nullable<Varchar>, + created_at -> Timestamp, + } +} + +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + hyperswitch_ai_interaction_default (id, created_at) { + #[max_length = 64] + id -> Varchar, + #[max_length = 64] + session_id -> Nullable<Varchar>, + #[max_length = 64] + user_id -> Nullable<Varchar>, + #[max_length = 64] + merchant_id -> Nullable<Varchar>, + #[max_length = 64] + profile_id -> Nullable<Varchar>, + #[max_length = 64] + org_id -> Nullable<Varchar>, + #[max_length = 64] + role_id -> Nullable<Varchar>, + user_query -> Nullable<Bytea>, + response -> Nullable<Bytea>, + database_query -> Nullable<Text>, + #[max_length = 64] + interaction_status -> Nullable<Varchar>, + created_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1667,6 +1723,8 @@ diesel::allow_tables_to_appear_in_same_query!( fraud_check, gateway_status_map, generic_link, + hyperswitch_ai_interaction, + hyperswitch_ai_interaction_default, incremental_authorization, locker_mock_up, mandate, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index b2e674f34a5..4195475f88d 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -646,6 +646,62 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + hyperswitch_ai_interaction (id, created_at) { + #[max_length = 64] + id -> Varchar, + #[max_length = 64] + session_id -> Nullable<Varchar>, + #[max_length = 64] + user_id -> Nullable<Varchar>, + #[max_length = 64] + merchant_id -> Nullable<Varchar>, + #[max_length = 64] + profile_id -> Nullable<Varchar>, + #[max_length = 64] + org_id -> Nullable<Varchar>, + #[max_length = 64] + role_id -> Nullable<Varchar>, + user_query -> Nullable<Bytea>, + response -> Nullable<Bytea>, + database_query -> Nullable<Text>, + #[max_length = 64] + interaction_status -> Nullable<Varchar>, + created_at -> Timestamp, + } +} + +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + hyperswitch_ai_interaction_default (id, created_at) { + #[max_length = 64] + id -> Varchar, + #[max_length = 64] + session_id -> Nullable<Varchar>, + #[max_length = 64] + user_id -> Nullable<Varchar>, + #[max_length = 64] + merchant_id -> Nullable<Varchar>, + #[max_length = 64] + profile_id -> Nullable<Varchar>, + #[max_length = 64] + org_id -> Nullable<Varchar>, + #[max_length = 64] + role_id -> Nullable<Varchar>, + user_query -> Nullable<Bytea>, + response -> Nullable<Bytea>, + database_query -> Nullable<Text>, + #[max_length = 64] + interaction_status -> Nullable<Varchar>, + created_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1622,6 +1678,8 @@ diesel::allow_tables_to_appear_in_same_query!( fraud_check, gateway_status_map, generic_link, + hyperswitch_ai_interaction, + hyperswitch_ai_interaction_default, incremental_authorization, locker_mock_up, mandate, diff --git a/crates/hyperswitch_domain_models/src/chat.rs b/crates/hyperswitch_domain_models/src/chat.rs index 31b9f806db7..9243f535c07 100644 --- a/crates/hyperswitch_domain_models/src/chat.rs +++ b/crates/hyperswitch_domain_models/src/chat.rs @@ -12,4 +12,5 @@ pub struct HyperswitchAiDataRequest { pub profile_id: id_type::ProfileId, pub org_id: id_type::OrganizationId, pub query: GetDataMessage, + pub entity_type: common_enums::EntityType, } diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 3f85f8e2b3a..53ce32b033e 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -298,6 +298,29 @@ impl SecretsHandler for settings::UserAuthMethodSettings { } } +#[async_trait::async_trait] +impl SecretsHandler for settings::ChatSettings { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let chat_settings = value.get_inner(); + + let encryption_key = if chat_settings.enabled { + secret_management_client + .get_secret(chat_settings.encryption_key.clone()) + .await? + } else { + chat_settings.encryption_key.clone() + }; + + Ok(value.transition_state(|chat_settings| Self { + encryption_key, + ..chat_settings + })) + } +} + #[async_trait::async_trait] impl SecretsHandler for settings::NetworkTokenizationService { async fn convert_to_raw_secret( @@ -450,9 +473,14 @@ pub(crate) async fn fetch_raw_secrets( }) .await; + #[allow(clippy::expect_used)] + let chat = settings::ChatSettings::convert_to_raw_secret(conf.chat, secret_management_client) + .await + .expect("Failed to decrypt chat configs"); + Settings { server: conf.server, - chat: conf.chat, + chat, master_database, redis: conf.redis, log: conf.log, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 84bc63ca799..1923af66b35 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -71,7 +71,7 @@ pub struct Settings<S: SecretState> { pub server: Server, pub proxy: Proxy, pub env: Env, - pub chat: ChatSettings, + pub chat: SecretStateContainer<ChatSettings, S>, pub master_database: SecretStateContainer<Database, S>, #[cfg(feature = "olap")] pub replica_database: SecretStateContainer<Database, S>, @@ -207,6 +207,7 @@ pub struct Platform { pub struct ChatSettings { pub enabled: bool, pub hyperswitch_ai_host: String, + pub encryption_key: Secret<String>, } #[derive(Debug, Clone, Default, Deserialize)] @@ -1048,8 +1049,7 @@ impl Settings<SecuredSecret> { self.secrets.get_inner().validate()?; self.locker.validate()?; self.connectors.validate("connectors")?; - self.chat.validate()?; - + self.chat.get_inner().validate()?; self.cors.validate()?; self.scheduler diff --git a/crates/router/src/core/chat.rs b/crates/router/src/core/chat.rs index 837a259bed4..a690986a04a 100644 --- a/crates/router/src/core/chat.rs +++ b/crates/router/src/core/chat.rs @@ -1,18 +1,24 @@ use api_models::chat as chat_api; use common_utils::{ consts, + crypto::{DecodeMessage, GcmAes256}, errors::CustomResult, request::{Method, RequestBuilder, RequestContent}, }; use error_stack::ResultExt; use external_services::http_client; use hyperswitch_domain_models::chat as chat_domain; -use router_env::{instrument, logger, tracing}; +use masking::ExposeInterface; +use router_env::{ + instrument, logger, + tracing::{self, Instrument}, +}; use crate::{ db::errors::chat::ChatErrors, routes::{app::SessionStateInfo, SessionState}, - services::{authentication as auth, ApplicationResponse}, + services::{authentication as auth, authorization::roles, ApplicationResponse}, + utils, }; #[instrument(skip_all, fields(?session_id))] @@ -22,15 +28,34 @@ pub async fn get_data_from_hyperswitch_ai_workflow( req: chat_api::ChatRequest, session_id: Option<&str>, ) -> CustomResult<ApplicationResponse<chat_api::ChatResponse>, ChatErrors> { - let url = format!("{}/webhook", state.conf.chat.hyperswitch_ai_host); - let request_id = state.get_request_id(); + let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( + &state, + &user_from_token.role_id, + &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), + ) + .await + .change_context(ChatErrors::InternalServerError) + .attach_printable("Failed to retrieve role information")?; + let url = format!( + "{}/webhook", + state.conf.chat.get_inner().hyperswitch_ai_host + ); + let request_id = state + .get_request_id() + .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); + let request_body = chat_domain::HyperswitchAiDataRequest { query: chat_domain::GetDataMessage { - message: req.message, + message: req.message.clone(), }, - org_id: user_from_token.org_id, - merchant_id: user_from_token.merchant_id, - profile_id: user_from_token.profile_id, + org_id: user_from_token.org_id.clone(), + merchant_id: user_from_token.merchant_id.clone(), + profile_id: user_from_token.profile_id.clone(), + entity_type: role_info.get_entity_type(), }; logger::info!("Request for AI service: {:?}", request_body); @@ -38,11 +63,9 @@ pub async fn get_data_from_hyperswitch_ai_workflow( .method(Method::Post) .url(&url) .attach_default_headers() + .header(consts::X_REQUEST_ID, &request_id) .set_body(RequestContent::Json(Box::new(request_body.clone()))); - if let Some(request_id) = request_id { - request_builder = request_builder.header(consts::X_REQUEST_ID, &request_id); - } if let Some(session_id) = session_id { request_builder = request_builder.header(consts::X_CHAT_SESSION_ID, session_id); } @@ -57,10 +80,132 @@ pub async fn get_data_from_hyperswitch_ai_workflow( .await .change_context(ChatErrors::InternalServerError) .attach_printable("Error when sending request to AI service")? - .json::<_>() + .json::<chat_api::ChatResponse>() .await .change_context(ChatErrors::InternalServerError) .attach_printable("Error when deserializing response from AI service")?; - Ok(ApplicationResponse::Json(response)) + let response_to_return = response.clone(); + tokio::spawn( + async move { + let new_hyperswitch_ai_interaction = utils::chat::construct_hyperswitch_ai_interaction( + &state, + &user_from_token, + &req, + &response, + &request_id, + ) + .await; + + match new_hyperswitch_ai_interaction { + Ok(interaction) => { + let db = state.store.as_ref(); + if let Err(e) = db.insert_hyperswitch_ai_interaction(interaction).await { + logger::error!("Failed to insert hyperswitch_ai_interaction: {:?}", e); + } + } + Err(e) => { + logger::error!("Failed to construct hyperswitch_ai_interaction: {:?}", e); + } + } + } + .in_current_span(), + ); + + Ok(ApplicationResponse::Json(response_to_return)) +} + +#[instrument(skip_all)] +pub async fn list_chat_conversations( + state: SessionState, + user_from_token: auth::UserFromToken, + req: chat_api::ChatListRequest, +) -> CustomResult<ApplicationResponse<chat_api::ChatListResponse>, ChatErrors> { + let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( + &state, + &user_from_token.role_id, + &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), + ) + .await + .change_context(ChatErrors::InternalServerError) + .attach_printable("Failed to retrieve role information")?; + + if !role_info.is_internal() { + return Err(error_stack::Report::new(ChatErrors::UnauthorizedAccess) + .attach_printable("Only internal roles are allowed for this operation")); + } + + let db = state.store.as_ref(); + let hyperswitch_ai_interactions = db + .list_hyperswitch_ai_interactions( + req.merchant_id, + req.limit.unwrap_or(consts::DEFAULT_LIST_LIMIT), + req.offset.unwrap_or(consts::DEFAULT_LIST_OFFSET), + ) + .await + .change_context(ChatErrors::InternalServerError) + .attach_printable("Error when fetching hyperswitch_ai_interactions")?; + + let encryption_key = state.conf.chat.get_inner().encryption_key.clone().expose(); + let key = match hex::decode(&encryption_key) { + Ok(key) => key, + Err(e) => { + router_env::logger::error!("Failed to decode encryption key: {}", e); + encryption_key.as_bytes().to_vec() + } + }; + + let mut conversations = Vec::new(); + + for interaction in hyperswitch_ai_interactions { + let user_query_encrypted = interaction + .user_query + .ok_or(ChatErrors::InternalServerError) + .attach_printable("Missing user_query field in hyperswitch_ai_interaction")?; + let response_encrypted = interaction + .response + .ok_or(ChatErrors::InternalServerError) + .attach_printable("Missing response field in hyperswitch_ai_interaction")?; + + let user_query_decrypted_bytes = GcmAes256 + .decode_message(&key, user_query_encrypted.into_inner()) + .change_context(ChatErrors::InternalServerError) + .attach_printable("Failed to decrypt user query")?; + + let response_decrypted_bytes = GcmAes256 + .decode_message(&key, response_encrypted.into_inner()) + .change_context(ChatErrors::InternalServerError) + .attach_printable("Failed to decrypt response")?; + + let user_query_decrypted = String::from_utf8(user_query_decrypted_bytes) + .change_context(ChatErrors::InternalServerError) + .attach_printable("Failed to convert decrypted user query to string")?; + + let response_decrypted = serde_json::from_slice(&response_decrypted_bytes) + .change_context(ChatErrors::InternalServerError) + .attach_printable("Failed to deserialize decrypted response")?; + + conversations.push(chat_api::ChatConversation { + id: interaction.id, + session_id: interaction.session_id, + user_id: interaction.user_id, + merchant_id: interaction.merchant_id, + profile_id: interaction.profile_id, + org_id: interaction.org_id, + role_id: interaction.role_id, + user_query: user_query_decrypted.into(), + response: response_decrypted, + database_query: interaction.database_query, + interaction_status: interaction.interaction_status, + created_at: interaction.created_at, + }); + } + + return Ok(ApplicationResponse::Json(chat_api::ChatListResponse { + conversations, + })); } diff --git a/crates/router/src/core/errors/chat.rs b/crates/router/src/core/errors/chat.rs index a96afa67de8..d23f0e9bb77 100644 --- a/crates/router/src/core/errors/chat.rs +++ b/crates/router/src/core/errors/chat.rs @@ -6,6 +6,8 @@ pub enum ChatErrors { MissingConfigError, #[error("Chat response deserialization failed")] ChatResponseDeserializationFailed, + #[error("Unauthorized access")] + UnauthorizedAccess, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ChatErrors { @@ -22,6 +24,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::ChatResponseDeserializationFailed => { AER::BadRequest(ApiError::new(sub_code, 2, self.get_error_message(), None)) } + Self::UnauthorizedAccess => { + AER::Unauthorized(ApiError::new(sub_code, 3, self.get_error_message(), None)) + } } } } @@ -32,6 +37,7 @@ impl ChatErrors { Self::InternalServerError => "Something went wrong".to_string(), Self::MissingConfigError => "Missing webhook url".to_string(), Self::ChatResponseDeserializationFailed => "Failed to parse chat response".to_string(), + Self::UnauthorizedAccess => "Not authorized to access the resource".to_string(), } } } diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index f675e316aef..ab3b7cba577 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -20,6 +20,7 @@ pub mod fraud_check; pub mod generic_link; pub mod gsm; pub mod health_check; +pub mod hyperswitch_ai_interaction; pub mod kafka_store; pub mod locker_mock_up; pub mod mandate; @@ -137,6 +138,7 @@ pub trait StorageInterface: + user::sample_data::BatchSampleDataInterface + health_check::HealthCheckDbInterface + user_authentication_method::UserAuthenticationMethodInterface + + hyperswitch_ai_interaction::HyperswitchAiInteractionInterface + authentication::AuthenticationInterface + generic_link::GenericLinkInterface + relay::RelayInterface diff --git a/crates/router/src/db/hyperswitch_ai_interaction.rs b/crates/router/src/db/hyperswitch_ai_interaction.rs new file mode 100644 index 00000000000..4ecf741a088 --- /dev/null +++ b/crates/router/src/db/hyperswitch_ai_interaction.rs @@ -0,0 +1,123 @@ +use diesel_models::hyperswitch_ai_interaction as storage; +use error_stack::report; +use router_env::{instrument, tracing}; + +use super::MockDb; +use crate::{ + connection, + core::errors::{self, CustomResult}, + services::Store, +}; + +#[async_trait::async_trait] +pub trait HyperswitchAiInteractionInterface { + async fn insert_hyperswitch_ai_interaction( + &self, + hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew, + ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError>; + + async fn list_hyperswitch_ai_interactions( + &self, + merchant_id: Option<common_utils::id_type::MerchantId>, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError>; +} + +#[async_trait::async_trait] +impl HyperswitchAiInteractionInterface for Store { + #[instrument(skip_all)] + async fn insert_hyperswitch_ai_interaction( + &self, + hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew, + ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + hyperswitch_ai_interaction + .insert(&conn) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[instrument(skip_all)] + async fn list_hyperswitch_ai_interactions( + &self, + merchant_id: Option<common_utils::id_type::MerchantId>, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::HyperswitchAiInteraction::filter_by_optional_merchant_id( + &conn, + merchant_id.as_ref(), + limit, + offset, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } +} + +#[async_trait::async_trait] +impl HyperswitchAiInteractionInterface for MockDb { + async fn insert_hyperswitch_ai_interaction( + &self, + hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew, + ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError> { + let mut hyperswitch_ai_interactions = self.hyperswitch_ai_interactions.lock().await; + let hyperswitch_ai_interaction = storage::HyperswitchAiInteraction { + id: hyperswitch_ai_interaction.id, + session_id: hyperswitch_ai_interaction.session_id, + user_id: hyperswitch_ai_interaction.user_id, + merchant_id: hyperswitch_ai_interaction.merchant_id, + profile_id: hyperswitch_ai_interaction.profile_id, + org_id: hyperswitch_ai_interaction.org_id, + role_id: hyperswitch_ai_interaction.role_id, + user_query: hyperswitch_ai_interaction.user_query, + response: hyperswitch_ai_interaction.response, + database_query: hyperswitch_ai_interaction.database_query, + interaction_status: hyperswitch_ai_interaction.interaction_status, + created_at: hyperswitch_ai_interaction.created_at, + }; + hyperswitch_ai_interactions.push(hyperswitch_ai_interaction.clone()); + Ok(hyperswitch_ai_interaction) + } + + async fn list_hyperswitch_ai_interactions( + &self, + merchant_id: Option<common_utils::id_type::MerchantId>, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError> { + let hyperswitch_ai_interactions = self.hyperswitch_ai_interactions.lock().await; + + let offset_usize = offset.try_into().unwrap_or_else(|_| { + common_utils::consts::DEFAULT_LIST_OFFSET + .try_into() + .unwrap_or(usize::MIN) + }); + + let limit_usize = limit.try_into().unwrap_or_else(|_| { + common_utils::consts::DEFAULT_LIST_LIMIT + .try_into() + .unwrap_or(usize::MAX) + }); + + let filtered_interactions: Vec<storage::HyperswitchAiInteraction> = + hyperswitch_ai_interactions + .iter() + .filter( + |interaction| match (merchant_id.as_ref(), &interaction.merchant_id) { + (Some(merchant_id), Some(interaction_merchant_id)) => { + interaction_merchant_id == &merchant_id.get_string_repr().to_owned() + } + (None, _) => true, + _ => false, + }, + ) + .skip(offset_usize) + .take(limit_usize) + .cloned() + .collect(); + Ok(filtered_interactions) + } +} diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 9eaef17b9c5..68ef8d19619 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -43,6 +43,7 @@ use time::PrimitiveDateTime; use super::{ dashboard_metadata::DashboardMetadataInterface, ephemeral_key::ClientSecretInterface, + hyperswitch_ai_interaction::HyperswitchAiInteractionInterface, role::RoleInterface, user::{sample_data::BatchSampleDataInterface, theme::ThemeInterface, UserInterface}, user_authentication_method::UserAuthenticationMethodInterface, @@ -4127,6 +4128,29 @@ impl UserAuthenticationMethodInterface for KafkaStore { } } +#[async_trait::async_trait] +impl HyperswitchAiInteractionInterface for KafkaStore { + async fn insert_hyperswitch_ai_interaction( + &self, + hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew, + ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError> { + self.diesel_store + .insert_hyperswitch_ai_interaction(hyperswitch_ai_interaction) + .await + } + + async fn list_hyperswitch_ai_interactions( + &self, + merchant_id: Option<id_type::MerchantId>, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError> { + self.diesel_store + .list_hyperswitch_ai_interactions(merchant_id, limit, offset) + .await + } +} + #[async_trait::async_trait] impl ThemeInterface for KafkaStore { async fn insert_theme( diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index ef3f8081b9a..f12730d7b63 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2343,12 +2343,16 @@ pub struct Chat; impl Chat { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/chat").app_data(web::Data::new(state.clone())); - if state.conf.chat.enabled { + if state.conf.chat.get_inner().enabled { route = route.service( - web::scope("/ai").service( - web::resource("/data") - .route(web::post().to(chat::get_data_from_hyperswitch_ai_workflow)), - ), + web::scope("/ai") + .service( + web::resource("/data") + .route(web::post().to(chat::get_data_from_hyperswitch_ai_workflow)), + ) + .service( + web::resource("/list").route(web::get().to(chat::get_all_conversations)), + ), ); } route diff --git a/crates/router/src/routes/chat.rs b/crates/router/src/routes/chat.rs index e3970cc6a4c..f670bb8e166 100644 --- a/crates/router/src/routes/chat.rs +++ b/crates/router/src/routes/chat.rs @@ -45,3 +45,24 @@ pub async fn get_data_from_hyperswitch_ai_workflow( )) .await } + +#[instrument(skip_all)] +pub async fn get_all_conversations( + state: web::Data<AppState>, + http_req: HttpRequest, + payload: web::Query<chat_api::ChatListRequest>, +) -> HttpResponse { + let flow = Flow::ListAllChatInteractions; + Box::pin(api::server_wrap( + flow.clone(), + state, + &http_req, + payload.into_inner(), + |state, user: auth::UserFromToken, payload, _| { + chat_core::list_chat_conversations(state, user, payload) + }, + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 0c42909b457..c3efb561b42 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -315,7 +315,7 @@ impl From<Flow> for ApiIdentifier { | Flow::ListAllThemesInLineage | Flow::CloneConnector => Self::User, - Flow::GetDataFromHyperswitchAiFlow => Self::AiWorkflow, + Flow::GetDataFromHyperswitchAiFlow | Flow::ListAllChatInteractions => Self::AiWorkflow, Flow::ListRolesV2 | Flow::ListInvitableRolesAtEntityLevel diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 5d4c4a8bb29..e9c26dd30c2 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -21,6 +21,7 @@ pub mod file; pub mod fraud_check; pub mod generic_link; pub mod gsm; +pub mod hyperswitch_ai_interaction; #[cfg(feature = "kv_store")] pub mod kv; pub mod locker_mock_up; @@ -75,8 +76,9 @@ pub use self::{ blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*, callback_mapper::*, capture::*, cards_info::*, configs::*, customers::*, dashboard_metadata::*, dispute::*, dynamic_routing_stats::*, ephemeral_key::*, events::*, file::*, fraud_check::*, - generic_link::*, gsm::*, locker_mock_up::*, mandate::*, merchant_account::*, - merchant_connector_account::*, merchant_key_store::*, payment_link::*, payment_method::*, - process_tracker::*, refund::*, reverse_lookup::*, role::*, routing_algorithm::*, - subscription::*, unified_translations::*, user::*, user_authentication_method::*, user_role::*, + generic_link::*, gsm::*, hyperswitch_ai_interaction::*, locker_mock_up::*, mandate::*, + merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*, + payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*, + routing_algorithm::*, subscription::*, unified_translations::*, user::*, + user_authentication_method::*, user_role::*, }; diff --git a/crates/router/src/types/storage/hyperswitch_ai_interaction.rs b/crates/router/src/types/storage/hyperswitch_ai_interaction.rs new file mode 100644 index 00000000000..30ba3efb49d --- /dev/null +++ b/crates/router/src/types/storage/hyperswitch_ai_interaction.rs @@ -0,0 +1 @@ +pub use diesel_models::hyperswitch_ai_interaction::*; diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index e2acbc4db23..71f1ed404b2 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -1,3 +1,4 @@ +pub mod chat; #[cfg(feature = "olap")] pub mod connector_onboarding; pub mod currency; diff --git a/crates/router/src/utils/chat.rs b/crates/router/src/utils/chat.rs new file mode 100644 index 00000000000..c32b6190a95 --- /dev/null +++ b/crates/router/src/utils/chat.rs @@ -0,0 +1,70 @@ +use api_models::chat as chat_api; +use common_utils::{type_name, types::keymanager::Identifier}; +use diesel_models::hyperswitch_ai_interaction::{ + HyperswitchAiInteraction, HyperswitchAiInteractionNew, +}; +use error_stack::ResultExt; +use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; +use masking::ExposeInterface; + +use crate::{ + core::errors::{self, CustomResult}, + routes::SessionState, + services::authentication as auth, +}; + +pub async fn construct_hyperswitch_ai_interaction( + state: &SessionState, + user_from_token: &auth::UserFromToken, + req: &chat_api::ChatRequest, + response: &chat_api::ChatResponse, + request_id: &str, +) -> CustomResult<HyperswitchAiInteractionNew, errors::ApiErrorResponse> { + let encryption_key = state.conf.chat.get_inner().encryption_key.clone().expose(); + let key = match hex::decode(&encryption_key) { + Ok(key) => key, + Err(e) => { + router_env::logger::error!("Failed to decode encryption key: {}", e); + // Fallback to using the string as bytes, which was the previous behavior + encryption_key.as_bytes().to_vec() + } + }; + let encrypted_user_query = crypto_operation::<String, masking::WithType>( + &state.into(), + type_name!(HyperswitchAiInteraction), + CryptoOperation::Encrypt(req.message.clone()), + Identifier::Merchant(user_from_token.merchant_id.clone()), + &key, + ) + .await + .and_then(|val| val.try_into_operation()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encrypt user query")?; + + let encrypted_response = crypto_operation::<serde_json::Value, masking::WithType>( + &state.into(), + type_name!(HyperswitchAiInteraction), + CryptoOperation::Encrypt(response.response.clone()), + Identifier::Merchant(user_from_token.merchant_id.clone()), + &key, + ) + .await + .and_then(|val| val.try_into_operation()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encrypt response")?; + + Ok(HyperswitchAiInteractionNew { + id: request_id.to_owned(), + session_id: Some(request_id.to_string()), + user_id: Some(user_from_token.user_id.clone()), + merchant_id: Some(user_from_token.merchant_id.get_string_repr().to_string()), + profile_id: Some(user_from_token.profile_id.get_string_repr().to_string()), + org_id: Some(user_from_token.org_id.get_string_repr().to_string()), + role_id: Some(user_from_token.role_id.clone()), + user_query: Some(encrypted_user_query.into()), + response: Some(encrypted_response.into()), + database_query: response.query_executed.clone().map(|q| q.expose()), + interaction_status: Some(response.status.clone()), + created_at: common_utils::date_time::now(), + }) +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index ae5f34fd78f..2345469a4e1 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -357,6 +357,8 @@ pub enum Flow { GsmRuleDelete, /// Get data from embedded flow GetDataFromHyperswitchAiFlow, + // List all chat interactions + ListAllChatInteractions, /// User Sign Up UserSignUp, /// User Sign Up diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index 884d9747943..b3fc53fb8cf 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -65,6 +65,8 @@ pub struct MockDb { pub user_authentication_methods: Arc<Mutex<Vec<store::user_authentication_method::UserAuthenticationMethod>>>, pub themes: Arc<Mutex<Vec<store::user::theme::Theme>>>, + pub hyperswitch_ai_interactions: + Arc<Mutex<Vec<store::hyperswitch_ai_interaction::HyperswitchAiInteraction>>>, } impl MockDb { @@ -113,6 +115,7 @@ impl MockDb { user_key_store: Default::default(), user_authentication_methods: Default::default(), themes: Default::default(), + hyperswitch_ai_interactions: Default::default(), }) } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 7508208069d..d85f5251c39 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -829,8 +829,7 @@ billing_connectors_which_requires_invoice_sync_call = "recurly" [chat] enabled = false hyperswitch_ai_host = "http://0.0.0.0:8000" - - +encryption_key = "" [revenue_recovery.card_config.amex] max_retries_per_day = 20 @@ -846,4 +845,4 @@ max_retry_count_for_thirty_day = 20 [revenue_recovery.card_config.discover] max_retries_per_day = 20 -max_retry_count_for_thirty_day = 20 \ No newline at end of file +max_retry_count_for_thirty_day = 20 diff --git a/migrations/2025-07-21-120614_add_table_for_hyperswitch_ai_interactions/down.sql b/migrations/2025-07-21-120614_add_table_for_hyperswitch_ai_interactions/down.sql new file mode 100644 index 00000000000..8cd51507c46 --- /dev/null +++ b/migrations/2025-07-21-120614_add_table_for_hyperswitch_ai_interactions/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +-- CASCADE will automatically drop all child partitions +DROP TABLE IF EXISTS hyperswitch_ai_interaction CASCADE; diff --git a/migrations/2025-07-21-120614_add_table_for_hyperswitch_ai_interactions/up.sql b/migrations/2025-07-21-120614_add_table_for_hyperswitch_ai_interactions/up.sql new file mode 100644 index 00000000000..e67da66d139 --- /dev/null +++ b/migrations/2025-07-21-120614_add_table_for_hyperswitch_ai_interactions/up.sql @@ -0,0 +1,21 @@ +-- Your SQL goes here +CREATE TABLE hyperswitch_ai_interaction ( + id VARCHAR(64) NOT NULL, + session_id VARCHAR(64), + user_id VARCHAR(64), + merchant_id VARCHAR(64), + profile_id VARCHAR(64), + org_id VARCHAR(64), + role_id VARCHAR(64), + user_query BYTEA, + response BYTEA, + database_query TEXT, + interaction_status VARCHAR(64), + created_at TIMESTAMP NOT NULL, + PRIMARY KEY (id, created_at) +) PARTITION BY RANGE (created_at); + +-- Create a default partition +CREATE TABLE hyperswitch_ai_interaction_default + PARTITION OF hyperswitch_ai_interaction DEFAULT; +
2025-08-04T07:06:02Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Store the user query and response from the ai service for the analysis. - Allow the api only for internal user ### Additional Changes This pull request introduces support for encrypted chat conversations and adds database models and APIs for storing and retrieving chat interactions. The changes span configuration, API models, database schema, and core logic to enable secure chat storage and querying, with proper secret management for encryption keys. **Chat encryption and configuration:** * Added `encryption_key` to `[chat]` sections in all config files and updated `ChatSettings` to use a secret for the encryption key, with secret management integration for secure handling. **Chat API model extensions:** * Added new API models for listing chat conversations (`ChatListRequest`, `ChatConversation`, `ChatListResponse`) **Database schema and models for chat interactions:** * Introduced `hyperswitch_ai_interaction` table and corresponding Rust models for storing encrypted chat queries and **Core chat logic improvements:** * Enhanced chat workflow to fetch role information, set entity type, and use the decrypted chat encryption key for secure communication with the AI service. **Run this as part of migration** 1.Manual Partition creation for next two year. 2.Creates partitions for each 3-month range 3.Add calendar event to re run this after two year. ``` DO $$ DECLARE start_date date; end_date date; i int; partition_name text; BEGIN -- Get start date as the beginning of the current quarter start_date := date_trunc('quarter', current_date)::date; -- Create 8 quarterly partitions (2 years) FOR i IN 1..8 LOOP end_date := (start_date + interval '3 month')::date; partition_name := format( 'hyperswitch_ai_interaction_%s_q%s', to_char(start_date, 'YYYY'), extract(quarter from start_date) ); EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I PARTITION OF hyperswitch_ai_interaction FOR VALUES FROM (%L) TO (%L)', partition_name, start_date, end_date ); start_date := end_date; END LOOP; END$$; ``` **General enhancements and constants:** * Added default limit and offset constants for list operations, improving pagination support for chat conversation queries. - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes #8847 ## How did you test it? Hitting AI service, should store information in DB ``` curl --location 'http://localhost:8080/chat/ai/data' \ --header 'x-feature: integ-custom' \ --header 'x-chat-session-id: chat-dop' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "message": "total count of payments" }' ``` Can check hyperswitch AI interaction table for it. Internal roles can see the list of interactions for the given merchant id List ``` curl --location 'http://localhost:8080/chat/ai/list?merchant_id=merchant_id' \ --header 'Authorization: Bearer JWT' \ --data '' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.117.0
d6e925fd348af9b69bd3a756cd21142eeccd180a
d6e925fd348af9b69bd3a756cd21142eeccd180a
juspay/hyperswitch
juspay__hyperswitch-8807
Bug: [FIX]: Take merchant ID from headers in API Key Revoke (v2) For `API Key - Revoke` in v2, the merchant ID is currently being passed in the path. We need to instead read the `X-Merchant-ID` header to get the merchant ID.
diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index d76b338dc36..34b421d9e14 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -425,18 +425,18 @@ pub async fn update_api_key_expiry_task( #[instrument(skip_all)] pub async fn revoke_api_key( state: SessionState, - merchant_id: &common_utils::id_type::MerchantId, + merchant_id: common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> RouterResponse<api::RevokeApiKeyResponse> { let store = state.store.as_ref(); let api_key = store - .find_api_key_by_merchant_id_key_id_optional(merchant_id, key_id) + .find_api_key_by_merchant_id_key_id_optional(&merchant_id, key_id) .await .to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?; let revoked = store - .revoke_api_key(merchant_id, key_id) + .revoke_api_key(&merchant_id, key_id) .await .to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?; diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index 3acb1c07064..e6ad485e2a2 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -243,7 +243,9 @@ pub async fn api_key_revoke( state, &req, (&merchant_id, &key_id), - |state, _, (merchant_id, key_id), _| api_keys::revoke_api_key(state, merchant_id, key_id), + |state, _, (merchant_id, key_id), _| { + api_keys::revoke_api_key(state, merchant_id.clone(), key_id) + }, auth::auth_type( &auth::PlatformOrgAdminAuthWithMerchantIdFromRoute { merchant_id_from_route: merchant_id.clone(), @@ -265,24 +267,25 @@ pub async fn api_key_revoke( pub async fn api_key_revoke( state: web::Data<AppState>, req: HttpRequest, - path: web::Path<( - common_utils::id_type::MerchantId, - common_utils::id_type::ApiKeyId, - )>, + path: web::Path<common_utils::id_type::ApiKeyId>, ) -> impl Responder { let flow = Flow::ApiKeyRevoke; - let (merchant_id, key_id) = path.into_inner(); + let key_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, - (&merchant_id, &key_id), - |state, _, (merchant_id, key_id), _| api_keys::revoke_api_key(state, merchant_id, key_id), + &key_id, + |state, + auth::AuthenticationDataWithoutProfile { + merchant_account, .. + }, + key_id, + _| api_keys::revoke_api_key(state, merchant_account.get_id().to_owned(), key_id), auth::auth_type( - &auth::V2AdminApiAuth, - &auth::JWTAuthMerchantFromRoute { - merchant_id: merchant_id.clone(), + &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantApiKeyWrite, }, req.headers(),
2025-07-31T08:31:25Z
## 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 --> - Removed merchant ID from path in `API Keys - Revoke` - Changed auth to read merchant ID from headers ### 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 #8807 ## 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)? --> - V1: Request: ``` curl --location --request DELETE 'http://localhost:8080/api_keys/merchant_1753949938/dev_8Xwp8SIyp0R4ItROu0tR' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` Response: ```json { "merchant_id": "merchant_1753949938", "key_id": "dev_8Xwp8SIyp0R4ItROu0tR", "revoked": true } ``` - V2: Request: ``` curl --location --request DELETE 'http://localhost:8080/v2/api-keys/dev_DULXUEOAUgYKxuxE7PQN' \ --header 'x-merchant-id: cloth_seller_v2_hFIzh6a4wFsbtEkKYLxD' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'api-key: test_admin' ``` Response: ```json { "merchant_id": "cloth_seller_v2_hFIzh6a4wFsbtEkKYLxD", "key_id": "dev_DULXUEOAUgYKxuxE7PQN", "revoked": true } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.115.0
794dce168e6b4d280c9c742a6e8a3b3283e09602
794dce168e6b4d280c9c742a6e8a3b3283e09602
juspay/hyperswitch
juspay__hyperswitch-8840
Bug: [FEATURE]: Add support for Void after Capture - Add core flow for Void after Capture - Add PostCaptureVoid Flow in worldpayVantiv connector
diff --git a/api-reference/docs.json b/api-reference/docs.json index 17050ceb9fc..aa3cae620fc 100644 --- a/api-reference/docs.json +++ b/api-reference/docs.json @@ -42,6 +42,7 @@ "v1/payments/payments--confirm", "v1/payments/payments--retrieve", "v1/payments/payments--cancel", + "v1/payments/payments--cancel-post-capture", "v1/payments/payments--capture", "v1/payments/payments--incremental-authorization", "v1/payments/payments--session-token", diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index cf48cef794c..92e6eb893a0 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -1083,6 +1083,67 @@ ] } }, + "/payments/{payment_id}/cancel_post_capture": { + "post": { + "tags": [ + "Payments" + ], + "summary": "Payments - Cancel Post Capture", + "description": "A Payment could can be cancelled when it is in one of these statuses: `succeeded`, `partially_captured`, `partially_captured_and_capturable`.", + "operationId": "Cancel a Payment Post Capture", + "parameters": [ + { + "name": "payment_id", + "in": "path", + "description": "The identifier for payment", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentsCancelPostCaptureRequest" + }, + "examples": { + "Cancel the payment post capture with cancellation reason": { + "value": { + "cancellation_reason": "requested_by_customer" + } + }, + "Cancel the payment post capture with minimal fields": { + "value": {} + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Payment canceled post capture" + }, + "400": { + "description": "Missing mandatory fields", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GenericErrorResponseOpenApi" + } + } + } + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, "/payments/list": { "get": { "tags": [ @@ -7826,6 +7887,7 @@ "authorizing", "cod_initiated", "voided", + "voided_post_charge", "void_initiated", "capture_initiated", "capture_failed", @@ -14639,6 +14701,7 @@ "payment_failed", "payment_processing", "payment_cancelled", + "payment_cancelled_post_capture", "payment_authorized", "payment_captured", "payment_expired", @@ -16486,6 +16549,7 @@ "succeeded", "failed", "cancelled", + "cancelled_post_capture", "processing", "requires_customer_action", "requires_merchant_action", @@ -21937,6 +22001,17 @@ "recurring_mandate" ] }, + "PaymentsCancelPostCaptureRequest": { + "type": "object", + "description": "Request to cancel a payment when the payment is already captured", + "properties": { + "cancellation_reason": { + "type": "string", + "description": "The reason for the payment cancel", + "nullable": true + } + } + }, "PaymentsCancelRequest": { "type": "object", "properties": { @@ -31421,6 +31496,7 @@ "AUTHORIZING", "C_O_D_INITIATED", "VOIDED", + "VOIDED_POST_CHARGE", "VOID_INITIATED", "NOP", "CAPTURE_INITIATED", diff --git a/api-reference/v1/payments/payments--cancel-post-capture.mdx b/api-reference/v1/payments/payments--cancel-post-capture.mdx new file mode 100644 index 00000000000..74aa3bc14ee --- /dev/null +++ b/api-reference/v1/payments/payments--cancel-post-capture.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /payments/{payment_id}/cancel_post_capture +--- \ No newline at end of file diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index dc3578ef61c..7576cd7030a 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -4834,6 +4834,7 @@ "authorizing", "cod_initiated", "voided", + "voided_post_charge", "void_initiated", "capture_initiated", "capture_failed", @@ -10686,6 +10687,7 @@ "payment_failed", "payment_processing", "payment_cancelled", + "payment_cancelled_post_capture", "payment_authorized", "payment_captured", "payment_expired", @@ -12645,6 +12647,7 @@ "succeeded", "failed", "cancelled", + "cancelled_post_capture", "processing", "requires_customer_action", "requires_merchant_action", diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index ec4c8667f45..19f708c866f 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -12,8 +12,8 @@ use crate::{ payment_methods::PaymentMethodListResponse, payments::{ ExtendedCardInfoResponse, PaymentIdType, PaymentListFilterConstraints, - PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelRequest, - PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, + PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelPostCaptureRequest, + PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse, PaymentsExternalAuthenticationRequest, PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest, @@ -132,6 +132,15 @@ impl ApiEventMetric for PaymentsCancelRequest { } } +#[cfg(feature = "v1")] +impl ApiEventMetric for PaymentsCancelPostCaptureRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Payment { + payment_id: self.payment_id.clone(), + }) + } +} + #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsApproveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index 02ded9713f6..0365d4b6d50 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -221,6 +221,7 @@ pub enum TxnStatus { Authorizing, CODInitiated, Voided, + VoidedPostCharge, VoidInitiated, Nop, CaptureInitiated, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 0c238d18c2a..3419e780da6 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -7637,6 +7637,16 @@ pub struct PaymentsCancelRequest { pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } +/// Request to cancel a payment when the payment is already captured +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] +pub struct PaymentsCancelPostCaptureRequest { + /// The identifier for the payment + #[serde(skip)] + pub payment_id: id_type::PaymentId, + /// The reason for the payment cancel + pub cancellation_reason: Option<String>, +} + #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 99b8c2e600e..e2ba3a88ca9 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -141,6 +141,7 @@ pub enum AttemptStatus { Authorizing, CodInitiated, Voided, + VoidedPostCharge, VoidInitiated, CaptureInitiated, CaptureFailed, @@ -166,6 +167,7 @@ impl AttemptStatus { | Self::Charged | Self::AutoRefunded | Self::Voided + | Self::VoidedPostCharge | Self::VoidFailed | Self::CaptureFailed | Self::Failure @@ -1501,6 +1503,7 @@ impl EventClass { EventType::PaymentFailed, EventType::PaymentProcessing, EventType::PaymentCancelled, + EventType::PaymentCancelledPostCapture, EventType::PaymentAuthorized, EventType::PaymentCaptured, EventType::PaymentExpired, @@ -1555,6 +1558,7 @@ pub enum EventType { PaymentFailed, PaymentProcessing, PaymentCancelled, + PaymentCancelledPostCapture, PaymentAuthorized, PaymentCaptured, PaymentExpired, @@ -1659,6 +1663,8 @@ pub enum IntentStatus { Failed, /// This payment has been cancelled. Cancelled, + /// This payment has been cancelled post capture. + CancelledPostCapture, /// This payment is still being processed by the payment processor. /// The status update might happen through webhooks or polling with the connector. Processing, @@ -1690,6 +1696,7 @@ impl IntentStatus { Self::Succeeded | Self::Failed | Self::Cancelled + | Self::CancelledPostCapture | Self::PartiallyCaptured | Self::Expired => true, Self::Processing @@ -1713,6 +1720,7 @@ impl IntentStatus { | Self::Succeeded | Self::Failed | Self::Cancelled + | Self::CancelledPostCapture | Self::PartiallyCaptured | Self::RequiresCapture | Self::Conflicted | Self::Expired=> false, Self::Processing @@ -1826,6 +1834,7 @@ impl From<AttemptStatus> for PaymentMethodStatus { match attempt_status { AttemptStatus::Failure | AttemptStatus::Voided + | AttemptStatus::VoidedPostCharge | AttemptStatus::Started | AttemptStatus::Pending | AttemptStatus::Unresolved diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index 8d1549b80ae..15c0f958371 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -2123,6 +2123,7 @@ impl From<AttemptStatus> for IntentStatus { | AttemptStatus::CaptureFailed | AttemptStatus::Failure => Self::Failed, AttemptStatus::Voided => Self::Cancelled, + AttemptStatus::VoidedPostCharge => Self::CancelledPostCapture, AttemptStatus::Expired => Self::Expired, } } @@ -2138,6 +2139,7 @@ impl From<IntentStatus> for Option<EventType> { | IntentStatus::RequiresCustomerAction | IntentStatus::Conflicted => Some(EventType::ActionRequired), IntentStatus::Cancelled => Some(EventType::PaymentCancelled), + IntentStatus::CancelledPostCapture => Some(EventType::PaymentCancelledPostCapture), IntentStatus::Expired => Some(EventType::PaymentExpired), IntentStatus::PartiallyCaptured | IntentStatus::PartiallyCapturedAndCapturable => { Some(EventType::PaymentCaptured) diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index 6bb4cf345f7..d0817482c83 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -697,6 +697,7 @@ impl TryFrom<enums::AttemptStatus> for ChargebeeRecordStatus { | enums::AttemptStatus::Authorizing | enums::AttemptStatus::CodInitiated | enums::AttemptStatus::Voided + | enums::AttemptStatus::VoidedPostCharge | enums::AttemptStatus::VoidInitiated | enums::AttemptStatus::CaptureInitiated | enums::AttemptStatus::VoidFailed diff --git a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs index 7c25b7a6e96..ca17c9f984c 100644 --- a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs @@ -2706,6 +2706,7 @@ impl TryFrom<PaymentsCaptureResponseRouterData<PaypalCaptureResponse>> | storage_enums::AttemptStatus::ConfirmationAwaited | storage_enums::AttemptStatus::DeviceDataCollectionPending | storage_enums::AttemptStatus::Voided + | storage_enums::AttemptStatus::VoidedPostCharge | storage_enums::AttemptStatus::Expired => 0, storage_enums::AttemptStatus::Charged | storage_enums::AttemptStatus::PartialCharged diff --git a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs index 4aef739b979..7aa82e69da4 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs @@ -269,6 +269,7 @@ impl TryFrom<enums::AttemptStatus> for RecurlyRecordStatus { | enums::AttemptStatus::Authorizing | enums::AttemptStatus::CodInitiated | enums::AttemptStatus::Voided + | enums::AttemptStatus::VoidedPostCharge | enums::AttemptStatus::VoidInitiated | enums::AttemptStatus::CaptureInitiated | enums::AttemptStatus::VoidFailed diff --git a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs index 01736d1f474..fab73fb95c4 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs @@ -16,21 +16,24 @@ 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}, + payments::{ + Authorize, Capture, PSync, PaymentMethodToken, PostCaptureVoid, Session, SetupMandate, + Void, + }, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, - RefundsData, SetupMandateRequestData, + PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, + PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ - PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, - PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, + PaymentsAuthorizeRouterData, PaymentsCancelPostCaptureRouterData, PaymentsCancelRouterData, + PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ @@ -75,6 +78,7 @@ impl api::Refund for Worldpayvantiv {} impl api::RefundExecute for Worldpayvantiv {} impl api::RefundSync for Worldpayvantiv {} impl api::PaymentToken for Worldpayvantiv {} +impl api::PaymentPostCaptureVoid for Worldpayvantiv {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Worldpayvantiv @@ -544,6 +548,96 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Wo } } +impl ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData> + for Worldpayvantiv +{ + fn get_headers( + &self, + req: &PaymentsCancelPostCaptureRouterData, + 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: &PaymentsCancelPostCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(self.base_url(connectors).to_owned()) + } + + fn get_request_body( + &self, + req: &PaymentsCancelPostCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req_object = worldpayvantiv::CnpOnlineRequest::try_from(req)?; + router_env::logger::info!(raw_connector_request=?connector_req_object); + + let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes( + &connector_req_object, + worldpayvantiv::worldpayvantiv_constants::XML_VERSION, + Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING), + None, + None, + )?; + + Ok(RequestContent::RawBytes(connector_req)) + } + + fn build_request( + &self, + req: &PaymentsCancelPostCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsPostCaptureVoidType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsPostCaptureVoidType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsPostCaptureVoidType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsCancelPostCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCancelPostCaptureRouterData, errors::ConnectorError> { + let response: worldpayvantiv::CnpOnlineResponse = + connector_utils::deserialize_xml_to_struct(&res.response)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Worldpayvantiv { fn get_headers( &self, diff --git a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs index 3fd7456e2ce..2e2251b1e8f 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs @@ -8,13 +8,13 @@ use hyperswitch_domain_models::{ }, router_flow_types::refunds::{Execute, RSync}, router_request_types::{ - PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, - ResponseId, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, + PaymentsCaptureData, PaymentsSyncData, ResponseId, }, router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData}, types::{ - PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, - RefundsRouterData, + PaymentsAuthorizeRouterData, PaymentsCancelPostCaptureRouterData, PaymentsCancelRouterData, + PaymentsCaptureRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{consts, errors}; @@ -79,6 +79,8 @@ pub enum OperationId { Auth, Capture, Void, + // VoidPostCapture + VoidPC, Refund, } @@ -128,6 +130,8 @@ pub struct CnpOnlineRequest { #[serde(skip_serializing_if = "Option::is_none")] pub auth_reversal: Option<AuthReversal>, #[serde(skip_serializing_if = "Option::is_none")] + pub void: Option<Void>, + #[serde(skip_serializing_if = "Option::is_none")] pub credit: Option<RefundRequest>, } @@ -137,6 +141,16 @@ pub struct Authentication { pub password: Secret<String>, } +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Void { + #[serde(rename = "@id")] + pub id: String, + #[serde(rename = "@reportGroup")] + pub report_group: String, + pub cnp_txn_id: String, +} + #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuthReversal { @@ -586,6 +600,7 @@ impl TryFrom<&WorldpayvantivRouterData<&PaymentsAuthorizeRouterData>> for CnpOnl capture: None, auth_reversal: None, credit: None, + void: None, }) } } @@ -692,6 +707,7 @@ impl TryFrom<&WorldpayvantivRouterData<&PaymentsCaptureRouterData>> for CnpOnlin capture, auth_reversal: None, credit: None, + void: None, }) } } @@ -747,6 +763,7 @@ impl<F> TryFrom<&WorldpayvantivRouterData<&RefundsRouterData<F>>> for CnpOnlineR capture: None, auth_reversal: None, credit, + void: None, }) } } @@ -770,6 +787,7 @@ pub struct CnpOnlineResponse { pub sale_response: Option<PaymentResponse>, pub capture_response: Option<CaptureResponse>, pub auth_reversal_response: Option<AuthReversalResponse>, + pub void_response: Option<VoidResponse>, pub credit_response: Option<CreditResponse>, } @@ -896,6 +914,21 @@ pub struct AuthReversalResponse { pub location: Option<String>, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct VoidResponse { + #[serde(rename = "@id")] + pub id: String, + #[serde(rename = "@reportGroup")] + pub report_group: String, + pub cnp_txn_id: String, + pub response: WorldpayvantivResponseCode, + pub response_time: String, + pub post_date: Option<String>, + pub message: String, + pub location: Option<String>, +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CreditResponse { @@ -1049,6 +1082,84 @@ impl<F> TryFrom<ResponseRouterData<F, CnpOnlineResponse, PaymentsCancelData, Pay } } +impl<F> + TryFrom< + ResponseRouterData< + F, + CnpOnlineResponse, + PaymentsCancelPostCaptureData, + PaymentsResponseData, + >, + > for RouterData<F, PaymentsCancelPostCaptureData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + F, + CnpOnlineResponse, + PaymentsCancelPostCaptureData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response.void_response { + Some(void_response) => { + let status = + get_attempt_status(WorldpayvantivPaymentFlow::VoidPC, void_response.response)?; + if connector_utils::is_payment_failure(status) { + Ok(Self { + status, + response: Err(ErrorResponse { + code: void_response.response.to_string(), + message: void_response.message.clone(), + reason: Some(void_response.message.clone()), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(void_response.cnp_txn_id), + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }), + ..item.data + }) + } else { + Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + void_response.cnp_txn_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 + }) + } + } + None => Ok(Self { + // Incase of API failure + status: common_enums::AttemptStatus::VoidFailed, + response: Err(ErrorResponse { + code: item.response.response_code, + message: item.response.message.clone(), + reason: Some(item.response.message.clone()), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }), + ..item.data + }), + } + } +} + impl TryFrom<RefundsResponseRouterData<Execute, CnpOnlineResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( @@ -1136,6 +1247,48 @@ impl TryFrom<&PaymentsCancelRouterData> for CnpOnlineRequest { capture: None, auth_reversal, credit: None, + void: None, + }) + } +} + +impl TryFrom<&PaymentsCancelPostCaptureRouterData> for CnpOnlineRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &PaymentsCancelPostCaptureRouterData) -> Result<Self, Self::Error> { + let report_group_metadata: WorldpayvantivPaymentMetadata = + connector_utils::to_connector_meta(item.request.connector_meta.clone())?; + let report_group = report_group_metadata.report_group.clone().ok_or( + errors::ConnectorError::RequestEncodingFailedWithReason( + "Failed to obtain report_group from metadata".to_string(), + ), + )?; + let void = Some(Void { + id: format!( + "{}_{}", + OperationId::VoidPC, + item.connector_request_reference_id + ), + report_group, + cnp_txn_id: item.request.connector_transaction_id.clone(), + }); + + let worldpayvantiv_auth_type = WorldpayvantivAuthType::try_from(&item.connector_auth_type)?; + let authentication = Authentication { + user: worldpayvantiv_auth_type.user, + password: worldpayvantiv_auth_type.password, + }; + + Ok(Self { + version: worldpayvantiv_constants::WORLDPAYVANTIV_VERSION.to_string(), + xmlns: worldpayvantiv_constants::XMLNS.to_string(), + merchant_id: worldpayvantiv_auth_type.merchant_id, + authentication, + authorization: None, + sale: None, + capture: None, + void, + auth_reversal: None, + credit: None, }) } } @@ -1340,6 +1493,9 @@ fn determine_attempt_status<F>( } WorldpayvantivPaymentFlow::Auth => Ok(common_enums::AttemptStatus::Authorized), WorldpayvantivPaymentFlow::Void => Ok(common_enums::AttemptStatus::Voided), + WorldpayvantivPaymentFlow::VoidPC => { + Ok(common_enums::AttemptStatus::VoidedPostCharge) + } }, PaymentStatus::TransactionDeclined => match flow_type { WorldpayvantivPaymentFlow::Sale | WorldpayvantivPaymentFlow::Capture => { @@ -1349,6 +1505,7 @@ fn determine_attempt_status<F>( Ok(common_enums::AttemptStatus::AuthorizationFailed) } WorldpayvantivPaymentFlow::Void => Ok(common_enums::AttemptStatus::VoidFailed), + WorldpayvantivPaymentFlow::VoidPC => Ok(common_enums::AttemptStatus::VoidFailed), }, PaymentStatus::PaymentStatusNotFound | PaymentStatus::NotYetProcessed @@ -2456,6 +2613,8 @@ pub enum WorldpayvantivPaymentFlow { Auth, Capture, Void, + //VoidPostCapture + VoidPC, } fn get_payment_flow_type(input: &str) -> Result<WorldpayvantivPaymentFlow, errors::ConnectorError> { @@ -2463,6 +2622,8 @@ fn get_payment_flow_type(input: &str) -> Result<WorldpayvantivPaymentFlow, error Ok(WorldpayvantivPaymentFlow::Auth) } else if input.contains("sale") { Ok(WorldpayvantivPaymentFlow::Sale) + } else if input.contains("voidpc") { + Ok(WorldpayvantivPaymentFlow::VoidPC) } else if input.contains("void") { Ok(WorldpayvantivPaymentFlow::Void) } else if input.contains("capture") { @@ -2497,6 +2658,9 @@ fn get_attempt_status( WorldpayvantivPaymentFlow::Auth => Ok(common_enums::AttemptStatus::Authorizing), WorldpayvantivPaymentFlow::Capture => Ok(common_enums::AttemptStatus::CaptureInitiated), WorldpayvantivPaymentFlow::Void => Ok(common_enums::AttemptStatus::VoidInitiated), + WorldpayvantivPaymentFlow::VoidPC => { + Ok(common_enums::AttemptStatus::VoidInitiated) + } }, WorldpayvantivResponseCode::ShopperCheckoutExpired | WorldpayvantivResponseCode::ProcessingNetworkUnavailable @@ -2847,7 +3011,8 @@ fn get_attempt_status( WorldpayvantivPaymentFlow::Sale => Ok(common_enums::AttemptStatus::Failure), WorldpayvantivPaymentFlow::Auth => Ok(common_enums::AttemptStatus::AuthorizationFailed), WorldpayvantivPaymentFlow::Capture => Ok(common_enums::AttemptStatus::CaptureFailed), - WorldpayvantivPaymentFlow::Void => Ok(common_enums::AttemptStatus::VoidFailed) + WorldpayvantivPaymentFlow::Void => Ok(common_enums::AttemptStatus::VoidFailed), + WorldpayvantivPaymentFlow::VoidPC => Ok(common_enums::AttemptStatus::VoidFailed) } } } diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 67821e66d72..74661c0ecae 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -52,8 +52,9 @@ use hyperswitch_domain_models::{ mandate_revoke::MandateRevoke, payments::{ Approve, AuthorizeSessionToken, CalculateTax, CompleteAuthorize, - CreateConnectorCustomer, CreateOrder, IncrementalAuthorization, PostProcessing, - PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, UpdateMetadata, + CreateConnectorCustomer, CreateOrder, IncrementalAuthorization, PostCaptureVoid, + PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, + UpdateMetadata, }, webhooks::VerifyWebhookSource, Authenticate, AuthenticationConfirmation, ExternalVaultCreateFlow, ExternalVaultDeleteFlow, @@ -68,11 +69,12 @@ use hyperswitch_domain_models::{ }, AcceptDisputeRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, - MandateRevokeRequestData, PaymentsApproveData, PaymentsIncrementalAuthorizationData, - PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, - PaymentsRejectData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, - RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SubmitEvidenceRequestData, - UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData, + MandateRevokeRequestData, PaymentsApproveData, PaymentsCancelPostCaptureData, + PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, + PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, + PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RetrieveFileRequestData, + SdkPaymentsSessionUpdateData, SubmitEvidenceRequestData, UploadFileRequestData, + VaultRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse, @@ -110,8 +112,8 @@ use hyperswitch_interfaces::{ files::{FileUpload, RetrieveFile, UploadFile}, payments::{ ConnectorCustomer, PaymentApprove, PaymentAuthorizeSessionToken, - PaymentIncrementalAuthorization, PaymentPostSessionTokens, PaymentReject, - PaymentSessionUpdate, PaymentUpdateMetadata, PaymentsCompleteAuthorize, + PaymentIncrementalAuthorization, PaymentPostCaptureVoid, PaymentPostSessionTokens, + PaymentReject, PaymentSessionUpdate, PaymentUpdateMetadata, PaymentsCompleteAuthorize, PaymentsCreateOrder, PaymentsPostProcessing, PaymentsPreProcessing, TaxCalculation, }, revenue_recovery::RevenueRecovery, @@ -959,6 +961,145 @@ default_imp_for_update_metadata!( connectors::CtpMastercard ); +macro_rules! default_imp_for_cancel_post_capture { + ($($path:ident::$connector:ident),*) => { + $( impl PaymentPostCaptureVoid for $path::$connector {} + impl + ConnectorIntegration< + PostCaptureVoid, + PaymentsCancelPostCaptureData, + PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_cancel_post_capture!( + connectors::Aci, + connectors::Adyen, + connectors::Adyenplatform, + connectors::Affirm, + connectors::Airwallex, + connectors::Amazonpay, + connectors::Archipel, + connectors::Authipay, + connectors::Authorizedotnet, + connectors::Bambora, + connectors::Bamboraapac, + connectors::Bankofamerica, + connectors::Barclaycard, + connectors::Bitpay, + connectors::Blackhawknetwork, + connectors::Bluecode, + connectors::Bluesnap, + connectors::Braintree, + connectors::Boku, + connectors::Breadpay, + connectors::Billwerk, + connectors::Cashtocode, + connectors::Celero, + connectors::Chargebee, + connectors::Checkbook, + connectors::Checkout, + connectors::Coinbase, + connectors::Coingate, + connectors::Cryptopay, + connectors::Custombilling, + connectors::Cybersource, + connectors::Datatrans, + connectors::Digitalvirgo, + connectors::Dlocal, + connectors::Dwolla, + connectors::Ebanx, + connectors::Elavon, + connectors::Facilitapay, + connectors::Fiserv, + connectors::Fiservemea, + connectors::Forte, + connectors::Getnet, + connectors::Helcim, + connectors::HyperswitchVault, + connectors::Iatapay, + connectors::Inespay, + connectors::Itaubank, + connectors::Jpmorgan, + connectors::Juspaythreedsserver, + connectors::Katapult, + connectors::Klarna, + connectors::Paypal, + connectors::Rapyd, + connectors::Razorpay, + connectors::Recurly, + connectors::Redsys, + connectors::Santander, + connectors::Shift4, + connectors::Silverflow, + connectors::Signifyd, + connectors::Square, + connectors::Stax, + connectors::Stripe, + connectors::Stripebilling, + connectors::Taxjar, + connectors::Mifinity, + connectors::Mollie, + connectors::Moneris, + connectors::Mpgs, + connectors::Multisafepay, + connectors::Netcetera, + connectors::Nomupay, + connectors::Noon, + connectors::Nordea, + connectors::Novalnet, + connectors::Nexinets, + connectors::Nexixpay, + connectors::Opayo, + connectors::Opennode, + connectors::Nuvei, + connectors::Nmi, + connectors::Paybox, + connectors::Payeezy, + connectors::Payload, + connectors::Payme, + connectors::Paystack, + connectors::Paytm, + connectors::Payu, + connectors::Phonepe, + connectors::Placetopay, + connectors::Plaid, + connectors::Payone, + connectors::Fiuu, + connectors::Flexiti, + connectors::Globalpay, + connectors::Globepay, + connectors::Gocardless, + connectors::Gpayments, + connectors::Hipay, + connectors::Wise, + connectors::Worldline, + connectors::Worldpay, + connectors::Worldpayxml, + connectors::Wellsfargo, + connectors::Wellsfargopayout, + connectors::Xendit, + connectors::Powertranz, + connectors::Prophetpay, + connectors::Riskified, + connectors::Threedsecureio, + connectors::Thunes, + connectors::Tokenio, + connectors::Trustpay, + connectors::Trustpayments, + connectors::Tsys, + connectors::UnifiedAuthenticationService, + connectors::Deutschebank, + connectors::Vgs, + connectors::Volt, + connectors::Zen, + connectors::Zsl, + connectors::CtpMastercard +); + use crate::connectors; macro_rules! default_imp_for_complete_authorize { ($($path:ident::$connector:ident),*) => { @@ -7395,6 +7536,15 @@ impl<const T: u8> { } +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PaymentPostCaptureVoid for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData> + for connectors::DummyConnector<T> +{ +} + #[cfg(feature = "dummy_connector")] impl<const T: u8> UasPreAuthentication for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 72cb5a3cf3b..fedb562e516 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -18,8 +18,8 @@ use hyperswitch_domain_models::{ payments::{ Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, IncrementalAuthorization, PSync, - PaymentMethodToken, PostProcessing, PostSessionTokens, PreProcessing, Reject, - SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, + PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, + Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, refunds::{Execute, RSync}, revenue_recovery::{ @@ -38,10 +38,10 @@ use hyperswitch_domain_models::{ AcceptDisputeRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, - PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, - PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, - PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, - PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, + PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, + PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, + PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, + PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, SubmitEvidenceRequestData, UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData, @@ -98,10 +98,11 @@ use hyperswitch_interfaces::{ payments_v2::{ ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2, PaymentAuthorizeV2, PaymentCaptureV2, PaymentCreateOrderV2, - PaymentIncrementalAuthorizationV2, PaymentPostSessionTokensV2, PaymentRejectV2, - PaymentSessionUpdateV2, PaymentSessionV2, PaymentSyncV2, PaymentTokenV2, - PaymentUpdateMetadataV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2, - PaymentsPostProcessingV2, PaymentsPreProcessingV2, TaxCalculationV2, + PaymentIncrementalAuthorizationV2, PaymentPostCaptureVoidV2, + PaymentPostSessionTokensV2, PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, + PaymentSyncV2, PaymentTokenV2, PaymentUpdateMetadataV2, PaymentV2, PaymentVoidV2, + PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, + TaxCalculationV2, }, refunds_v2::{RefundExecuteV2, RefundSyncV2, RefundV2}, revenue_recovery_v2::{ @@ -127,6 +128,7 @@ macro_rules! default_imp_for_new_connector_integration_payment { impl PaymentAuthorizeSessionTokenV2 for $path::$connector{} impl PaymentSyncV2 for $path::$connector{} impl PaymentVoidV2 for $path::$connector{} + impl PaymentPostCaptureVoidV2 for $path::$connector{} impl PaymentApproveV2 for $path::$connector{} impl PaymentRejectV2 for $path::$connector{} impl PaymentCaptureV2 for $path::$connector{} @@ -154,6 +156,9 @@ macro_rules! default_imp_for_new_connector_integration_payment { ConnectorIntegrationV2<Void, PaymentFlowData, PaymentsCancelData, PaymentsResponseData> for $path::$connector{} impl + ConnectorIntegrationV2<PostCaptureVoid, PaymentFlowData, PaymentsCancelPostCaptureData, PaymentsResponseData> + for $path::$connector{} + impl ConnectorIntegrationV2<Approve,PaymentFlowData, PaymentsApproveData, PaymentsResponseData> for $path::$connector{} impl diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index d2ee231d144..5f262a90acd 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -436,6 +436,7 @@ pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool { | AttemptStatus::Authorizing | AttemptStatus::CodInitiated | AttemptStatus::Voided + | AttemptStatus::VoidedPostCharge | AttemptStatus::VoidInitiated | AttemptStatus::CaptureInitiated | AttemptStatus::AutoRefunded @@ -6327,6 +6328,7 @@ impl FrmTransactionRouterDataRequest for FrmTransactionRouterData { | AttemptStatus::RouterDeclined | AttemptStatus::AuthorizationFailed | AttemptStatus::Voided + | AttemptStatus::VoidedPostCharge | AttemptStatus::CaptureFailed | AttemptStatus::Failure | AttemptStatus::AutoRefunded diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index 8cdcfe7e456..572ddcc30c2 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -702,6 +702,7 @@ impl common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the capturable amount when it reaches terminal / capturable state @@ -739,6 +740,7 @@ impl } // No amount is captured common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the amount captured when it reaches terminal state @@ -914,6 +916,7 @@ impl common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the capturable amount when it reaches terminal / capturable state @@ -954,6 +957,7 @@ impl } // No amount is captured common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), common_enums::IntentStatus::RequiresCapture => { @@ -1151,6 +1155,7 @@ impl common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the capturable amount when it reaches terminal / capturable state @@ -1190,6 +1195,7 @@ impl } // No amount is captured common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the amount captured when it reaches terminal state @@ -1385,6 +1391,7 @@ impl common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the capturable amount when it reaches terminal / capturable state @@ -1422,6 +1429,7 @@ impl } // No amount is captured common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the amount captured when it reaches terminal state diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs index 660c9fae4e2..1129f529971 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs @@ -26,6 +26,9 @@ pub struct PSync; #[derive(Debug, Clone)] pub struct Void; +#[derive(Debug, Clone)] +pub struct PostCaptureVoid; + #[derive(Debug, Clone)] pub struct Reject; diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index c33603ab279..2d0199c2664 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -567,6 +567,16 @@ pub struct PaymentsCancelData { pub capture_method: Option<storage_enums::CaptureMethod>, } +#[derive(Debug, Default, Clone)] +pub struct PaymentsCancelPostCaptureData { + pub currency: Option<storage_enums::Currency>, + pub connector_transaction_id: String, + pub cancellation_reason: Option<String>, + pub connector_meta: Option<serde_json::Value>, + // minor amount data for amount framework + pub minor_amount: Option<MinorUnit>, +} + #[derive(Debug, Default, Clone)] pub struct PaymentsRejectData { pub amount: Option<i64>, diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs index 1e7b6f23184..2dc507cf200 100644 --- a/crates/hyperswitch_domain_models/src/types.rs +++ b/crates/hyperswitch_domain_models/src/types.rs @@ -8,9 +8,9 @@ use crate::{ Authenticate, AuthenticationConfirmation, Authorize, AuthorizeSessionToken, BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, Execute, IncrementalAuthorization, - PSync, PaymentMethodToken, PostAuthenticate, PostSessionTokens, PreAuthenticate, - PreProcessing, RSync, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, - VerifyWebhookSource, Void, + PSync, PaymentMethodToken, PostAuthenticate, PostCaptureVoid, PostSessionTokens, + PreAuthenticate, PreProcessing, RSync, SdkSessionUpdate, Session, SetupMandate, + UpdateMetadata, VerifyWebhookSource, Void, }, router_request_types::{ revenue_recovery::{ @@ -25,9 +25,9 @@ use crate::{ AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, - PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostSessionTokensData, - PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, - PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, + PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, + PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsSessionData, + PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, VaultRequestData, VerifyWebhookSourceRequestData, }, @@ -52,6 +52,8 @@ pub type PaymentsPreProcessingRouterData = pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>; +pub type PaymentsCancelPostCaptureRouterData = + RouterData<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>; pub type SetupMandateRouterData = RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>; diff --git a/crates/hyperswitch_interfaces/src/api/payments.rs b/crates/hyperswitch_interfaces/src/api/payments.rs index 8b017be37da..b923d85a9b6 100644 --- a/crates/hyperswitch_interfaces/src/api/payments.rs +++ b/crates/hyperswitch_interfaces/src/api/payments.rs @@ -5,16 +5,16 @@ use hyperswitch_domain_models::{ payments::{ Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, IncrementalAuthorization, PSync, PaymentMethodToken, - PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, - SetupMandate, UpdateMetadata, Void, + PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, + SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, CreateOrder, }, router_request_types::{ AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, PaymentMethodTokenizationData, PaymentsApproveData, - PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, - PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, + PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, @@ -35,6 +35,7 @@ pub trait Payment: + PaymentSync + PaymentCapture + PaymentVoid + + PaymentPostCaptureVoid + PaymentApprove + PaymentReject + MandateSetup @@ -87,6 +88,12 @@ pub trait PaymentVoid: { } +/// trait PaymentPostCaptureVoid +pub trait PaymentPostCaptureVoid: + api::ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData> +{ +} + /// trait PaymentApprove pub trait PaymentApprove: api::ConnectorIntegration<Approve, PaymentsApproveData, PaymentsResponseData> diff --git a/crates/hyperswitch_interfaces/src/api/payments_v2.rs b/crates/hyperswitch_interfaces/src/api/payments_v2.rs index dbc7b364791..63a876c2128 100644 --- a/crates/hyperswitch_interfaces/src/api/payments_v2.rs +++ b/crates/hyperswitch_interfaces/src/api/payments_v2.rs @@ -5,14 +5,14 @@ use hyperswitch_domain_models::{ router_flow_types::payments::{ Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, IncrementalAuthorization, PSync, PaymentMethodToken, - PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, - SetupMandate, UpdateMetadata, Void, + PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, + SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, router_request_types::{ AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, PaymentMethodTokenizationData, PaymentsApproveData, - PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, - PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, + PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, @@ -53,6 +53,17 @@ pub trait PaymentVoidV2: { } +/// trait PaymentPostCaptureVoidV2 +pub trait PaymentPostCaptureVoidV2: + ConnectorIntegrationV2< + PostCaptureVoid, + PaymentFlowData, + PaymentsCancelPostCaptureData, + PaymentsResponseData, +> +{ +} + /// trait PaymentApproveV2 pub trait PaymentApproveV2: ConnectorIntegrationV2<Approve, PaymentFlowData, PaymentsApproveData, PaymentsResponseData> @@ -210,6 +221,7 @@ pub trait PaymentV2: + PaymentSyncV2 + PaymentCaptureV2 + PaymentVoidV2 + + PaymentPostCaptureVoidV2 + PaymentApproveV2 + PaymentRejectV2 + MandateSetupV2 diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs index d2f90998c80..c23a4c6c6ce 100644 --- a/crates/hyperswitch_interfaces/src/types.rs +++ b/crates/hyperswitch_interfaces/src/types.rs @@ -11,8 +11,8 @@ use hyperswitch_domain_models::{ payments::{ Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, IncrementalAuthorization, InitPayment, PSync, - PaymentMethodToken, PostProcessing, PostSessionTokens, PreProcessing, SdkSessionUpdate, - Session, SetupMandate, UpdateMetadata, Void, + PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, + SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, refunds::{Execute, RSync}, revenue_recovery::{BillingConnectorPaymentsSync, RecoveryRecordBack}, @@ -39,8 +39,8 @@ use hyperswitch_domain_models::{ AcceptDisputeRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, - PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, - PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, + PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, @@ -139,6 +139,9 @@ pub type PaymentsSessionType = /// Type alias for `ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData>` pub type PaymentsVoidType = dyn ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData>; +/// Type alias for `ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>` +pub type PaymentsPostCaptureVoidType = + dyn ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>; /// Type alias for `ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>` pub type TokenizationType = dyn ConnectorIntegration< diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 58e178f5b9a..b9c53dfa28e 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -78,6 +78,7 @@ Never share your secret api keys. Keep them guarded and secure. routes::payments::payments_capture, routes::payments::payments_connector_session, routes::payments::payments_cancel, + routes::payments::payments_cancel_post_capture, routes::payments::payments_list, routes::payments::payments_incremental_authorization, routes::payment_link::payment_link_retrieve, @@ -532,6 +533,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::SamsungPayTokenData, api_models::payments::ApplepayPaymentMethod, api_models::payments::PaymentsCancelRequest, + api_models::payments::PaymentsCancelPostCaptureRequest, api_models::payments::PaymentListConstraints, api_models::payments::PaymentListResponse, api_models::payments::CashappQr, diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs index 70c83f23392..d3abd208e9a 100644 --- a/crates/openapi/src/routes/payments.rs +++ b/crates/openapi/src/routes/payments.rs @@ -812,6 +812,40 @@ pub fn payments_connector_session() {} )] pub fn payments_cancel() {} +/// Payments - Cancel Post Capture +/// +/// A Payment could can be cancelled when it is in one of these statuses: `succeeded`, `partially_captured`, `partially_captured_and_capturable`. +#[utoipa::path( + post, + path = "/payments/{payment_id}/cancel_post_capture", + request_body ( + content = PaymentsCancelPostCaptureRequest, + examples( + ( + "Cancel the payment post capture with minimal fields" = ( + value = json!({}) + ) + ), + ( + "Cancel the payment post capture with cancellation reason" = ( + value = json!({"cancellation_reason": "requested_by_customer"}) + ) + ), + ) + ), + params( + ("payment_id" = String, Path, description = "The identifier for payment") + ), + responses( + (status = 200, description = "Payment canceled post capture"), + (status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi) + ), + tag = "Payments", + operation_id = "Cancel a Payment Post Capture", + security(("api_key" = [])) +)] +pub fn payments_cancel_post_capture() {} + /// Payments - List /// /// To list the *payments* diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index acf2f5e03ab..b67988a1503 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -430,7 +430,9 @@ impl From<api_enums::IntentStatus> for StripePaymentStatus { api_enums::IntentStatus::RequiresConfirmation => Self::RequiresConfirmation, api_enums::IntentStatus::RequiresCapture | api_enums::IntentStatus::PartiallyCapturedAndCapturable => Self::RequiresCapture, - api_enums::IntentStatus::Cancelled => Self::Canceled, + api_enums::IntentStatus::Cancelled | api_enums::IntentStatus::CancelledPostCapture => { + Self::Canceled + } } } } diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 90df416ec76..531977842ef 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -324,7 +324,9 @@ impl From<api_enums::IntentStatus> for StripeSetupStatus { logger::error!("Invalid status change"); Self::Canceled } - api_enums::IntentStatus::Cancelled => Self::Canceled, + api_enums::IntentStatus::Cancelled | api_enums::IntentStatus::CancelledPostCapture => { + Self::Canceled + } } } } diff --git a/crates/router/src/compatibility/stripe/webhooks.rs b/crates/router/src/compatibility/stripe/webhooks.rs index 5dad60120ec..196ab4cc43b 100644 --- a/crates/router/src/compatibility/stripe/webhooks.rs +++ b/crates/router/src/compatibility/stripe/webhooks.rs @@ -271,6 +271,7 @@ fn get_stripe_event_type(event_type: api_models::enums::EventType) -> &'static s api_models::enums::EventType::PaymentFailed => "payment_intent.payment_failed", api_models::enums::EventType::PaymentProcessing => "payment_intent.processing", api_models::enums::EventType::PaymentCancelled + | api_models::enums::EventType::PaymentCancelledPostCapture | api_models::enums::EventType::PaymentExpired => "payment_intent.canceled", // the below are not really stripe compatible because stripe doesn't provide this diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 5deeeadb41f..016f950fbca 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -2193,6 +2193,7 @@ impl FrmTransactionRouterDataRequest for fraud_check::FrmTransactionRouterData { | storage_enums::AttemptStatus::RouterDeclined | storage_enums::AttemptStatus::AuthorizationFailed | storage_enums::AttemptStatus::Voided + | storage_enums::AttemptStatus::VoidedPostCharge | storage_enums::AttemptStatus::CaptureFailed | storage_enums::AttemptStatus::Failure | storage_enums::AttemptStatus::AutoRefunded @@ -2238,6 +2239,7 @@ pub fn is_payment_failure(status: enums::AttemptStatus) -> bool { | common_enums::AttemptStatus::Authorizing | common_enums::AttemptStatus::CodInitiated | common_enums::AttemptStatus::Voided + | common_enums::AttemptStatus::VoidedPostCharge | common_enums::AttemptStatus::VoidInitiated | common_enums::AttemptStatus::CaptureInitiated | common_enums::AttemptStatus::AutoRefunded diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index a912dc27b82..9e9700e7a5a 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -81,9 +81,9 @@ use time; #[cfg(feature = "v1")] pub use self::operations::{ - PaymentApprove, PaymentCancel, PaymentCapture, PaymentConfirm, PaymentCreate, - PaymentIncrementalAuthorization, PaymentPostSessionTokens, PaymentReject, PaymentSession, - PaymentSessionUpdate, PaymentStatus, PaymentUpdate, PaymentUpdateMetadata, + PaymentApprove, PaymentCancel, PaymentCancelPostCapture, PaymentCapture, PaymentConfirm, + PaymentCreate, PaymentIncrementalAuthorization, PaymentPostSessionTokens, PaymentReject, + PaymentSession, PaymentSessionUpdate, PaymentStatus, PaymentUpdate, PaymentUpdateMetadata, }; use self::{ conditional_configs::perform_decision_management, @@ -3137,6 +3137,7 @@ impl ValidateStatusForOperation for &PaymentRedirectSync { | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresMerchantAction @@ -6881,6 +6882,12 @@ where storage_enums::IntentStatus::RequiresCapture | storage_enums::IntentStatus::PartiallyCapturedAndCapturable ), + "PaymentCancelPostCapture" => matches!( + payment_data.get_payment_intent().status, + storage_enums::IntentStatus::Succeeded + | storage_enums::IntentStatus::PartiallyCaptured + | storage_enums::IntentStatus::PartiallyCapturedAndCapturable + ), "PaymentCapture" => { matches!( payment_data.get_payment_intent().status, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 2cae2f0600d..039dda34771 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -1,6 +1,7 @@ pub mod approve_flow; pub mod authorize_flow; pub mod cancel_flow; +pub mod cancel_post_capture_flow; pub mod capture_flow; pub mod complete_authorize_flow; pub mod incremental_authorization_flow; diff --git a/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs b/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs new file mode 100644 index 00000000000..67ccd612a9d --- /dev/null +++ b/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs @@ -0,0 +1,141 @@ +use async_trait::async_trait; + +use super::{ConstructFlowSpecificData, Feature}; +use crate::{ + core::{ + errors::{ConnectorErrorExt, RouterResult}, + payments::{self, access_token, helpers, transformers, PaymentData}, + }, + routes::{metrics, SessionState}, + services, + types::{self, api, domain}, +}; + +#[async_trait] +impl + ConstructFlowSpecificData< + api::PostCaptureVoid, + types::PaymentsCancelPostCaptureData, + types::PaymentsResponseData, + > for PaymentData<api::PostCaptureVoid> +{ + #[cfg(feature = "v2")] + async fn construct_router_data<'a>( + &self, + _state: &SessionState, + _connector_id: &str, + _merchant_context: &domain::MerchantContext, + _customer: &Option<domain::Customer>, + _merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, + _merchant_recipient_data: Option<types::MerchantRecipientData>, + _header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, + ) -> RouterResult<types::PaymentsCancelPostCaptureRouterData> { + todo!() + } + + #[cfg(feature = "v1")] + async fn construct_router_data<'a>( + &self, + state: &SessionState, + connector_id: &str, + merchant_context: &domain::MerchantContext, + customer: &Option<domain::Customer>, + merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, + ) -> RouterResult<types::PaymentsCancelPostCaptureRouterData> { + Box::pin(transformers::construct_payment_router_data::< + api::PostCaptureVoid, + types::PaymentsCancelPostCaptureData, + >( + state, + self.clone(), + connector_id, + merchant_context, + customer, + merchant_connector_account, + merchant_recipient_data, + header_payload, + )) + .await + } +} + +#[async_trait] +impl Feature<api::PostCaptureVoid, types::PaymentsCancelPostCaptureData> + for types::RouterData< + api::PostCaptureVoid, + types::PaymentsCancelPostCaptureData, + types::PaymentsResponseData, + > +{ + async fn decide_flows<'a>( + self, + state: &SessionState, + connector: &api::ConnectorData, + call_connector_action: payments::CallConnectorAction, + connector_request: Option<services::Request>, + _business_profile: &domain::Profile, + _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + _return_raw_connector_response: Option<bool>, + ) -> RouterResult<Self> { + metrics::PAYMENT_CANCEL_COUNT.add( + 1, + router_env::metric_attributes!(("connector", connector.connector_name.to_string())), + ); + + let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< + api::PostCaptureVoid, + types::PaymentsCancelPostCaptureData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + let resp = services::execute_connector_processing_step( + state, + connector_integration, + &self, + call_connector_action, + connector_request, + None, + ) + .await + .to_payment_failed_response()?; + + Ok(resp) + } + + async fn add_access_token<'a>( + &self, + state: &SessionState, + connector: &api::ConnectorData, + merchant_context: &domain::MerchantContext, + creds_identifier: Option<&str>, + ) -> RouterResult<types::AddAccessTokenResult> { + access_token::add_access_token(state, connector, merchant_context, self, creds_identifier) + .await + } + + async fn build_flow_specific_connector_request( + &mut self, + state: &SessionState, + connector: &api::ConnectorData, + call_connector_action: payments::CallConnectorAction, + ) -> RouterResult<(Option<services::Request>, bool)> { + let request = match call_connector_action { + payments::CallConnectorAction::Trigger => { + let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< + api::PostCaptureVoid, + types::PaymentsCancelPostCaptureData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + connector_integration + .build_request(self, &state.conf.connectors) + .to_payment_failed_response()? + } + _ => None, + }; + + Ok((request, true)) + } +} diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 0e7ccdcac8e..8e44424339e 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -4398,6 +4398,7 @@ pub fn get_attempt_type( | enums::AttemptStatus::PartialCharged | enums::AttemptStatus::PartialChargedAndChargeable | enums::AttemptStatus::Voided + | enums::AttemptStatus::VoidedPostCharge | enums::AttemptStatus::AutoRefunded | enums::AttemptStatus::PaymentMethodAwaited | enums::AttemptStatus::DeviceDataCollectionPending @@ -4453,6 +4454,7 @@ pub fn get_attempt_type( } } enums::IntentStatus::Cancelled + | enums::IntentStatus::CancelledPostCapture | enums::IntentStatus::RequiresCapture | enums::IntentStatus::PartiallyCaptured | enums::IntentStatus::PartiallyCapturedAndCapturable @@ -4703,6 +4705,7 @@ pub fn is_manual_retry_allowed( | enums::AttemptStatus::PartialCharged | enums::AttemptStatus::PartialChargedAndChargeable | enums::AttemptStatus::Voided + | enums::AttemptStatus::VoidedPostCharge | enums::AttemptStatus::AutoRefunded | enums::AttemptStatus::PaymentMethodAwaited | enums::AttemptStatus::DeviceDataCollectionPending @@ -4721,6 +4724,7 @@ pub fn is_manual_retry_allowed( | enums::AttemptStatus::Failure => Some(true), }, enums::IntentStatus::Cancelled + | enums::IntentStatus::CancelledPostCapture | enums::IntentStatus::RequiresCapture | enums::IntentStatus::PartiallyCaptured | enums::IntentStatus::PartiallyCapturedAndCapturable diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index 9823c7abee3..6a21d1b6d85 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -3,6 +3,8 @@ pub mod payment_approve; #[cfg(feature = "v1")] pub mod payment_cancel; #[cfg(feature = "v1")] +pub mod payment_cancel_post_capture; +#[cfg(feature = "v1")] pub mod payment_capture; #[cfg(feature = "v1")] pub mod payment_complete_authorize; @@ -72,11 +74,11 @@ pub use self::payment_update_intent::PaymentUpdateIntent; #[cfg(feature = "v1")] pub use self::{ payment_approve::PaymentApprove, payment_cancel::PaymentCancel, - payment_capture::PaymentCapture, payment_confirm::PaymentConfirm, - payment_create::PaymentCreate, payment_post_session_tokens::PaymentPostSessionTokens, - payment_reject::PaymentReject, payment_session::PaymentSession, payment_start::PaymentStart, - payment_status::PaymentStatus, payment_update::PaymentUpdate, - payment_update_metadata::PaymentUpdateMetadata, + payment_cancel_post_capture::PaymentCancelPostCapture, payment_capture::PaymentCapture, + payment_confirm::PaymentConfirm, payment_create::PaymentCreate, + payment_post_session_tokens::PaymentPostSessionTokens, payment_reject::PaymentReject, + payment_session::PaymentSession, payment_start::PaymentStart, payment_status::PaymentStatus, + payment_update::PaymentUpdate, payment_update_metadata::PaymentUpdateMetadata, payments_incremental_authorization::PaymentIncrementalAuthorization, tax_calculation::PaymentSessionUpdate, }; diff --git a/crates/router/src/core/payments/operations/payment_attempt_record.rs b/crates/router/src/core/payments/operations/payment_attempt_record.rs index 3c5259b6bf1..f0b548891db 100644 --- a/crates/router/src/core/payments/operations/payment_attempt_record.rs +++ b/crates/router/src/core/payments/operations/payment_attempt_record.rs @@ -80,6 +80,7 @@ impl ValidateStatusForOperation for PaymentAttemptRecord { | common_enums::IntentStatus::Failed => Ok(()), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::RequiresCustomerAction diff --git a/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs new file mode 100644 index 00000000000..66b8f0fc479 --- /dev/null +++ b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs @@ -0,0 +1,323 @@ +use std::marker::PhantomData; + +use api_models::enums::FrmSuggestion; +use async_trait::async_trait; +use error_stack::ResultExt; +use router_derive; +use router_env::{instrument, tracing}; + +use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; +use crate::{ + core::{ + errors::{self, RouterResult, StorageErrorExt}, + payments::{self, helpers, operations, PaymentData}, + }, + routes::{app::ReqState, SessionState}, + services, + types::{ + self as core_types, + api::{self, PaymentIdTypeExt}, + domain, + storage::{self, enums}, + }, + utils::OptionExt, +}; + +#[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] +#[operation(operations = "all", flow = "cancel_post_capture")] +pub struct PaymentCancelPostCapture; + +type PaymentCancelPostCaptureOperation<'b, F> = + BoxedOperation<'b, F, api::PaymentsCancelPostCaptureRequest, PaymentData<F>>; + +#[async_trait] +impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelPostCaptureRequest> + for PaymentCancelPostCapture +{ + #[instrument(skip_all)] + async fn get_trackers<'a>( + &'a self, + state: &'a SessionState, + payment_id: &api::PaymentIdType, + request: &api::PaymentsCancelPostCaptureRequest, + merchant_context: &domain::MerchantContext, + _auth_flow: services::AuthFlow, + _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + ) -> RouterResult< + operations::GetTrackerResponse< + 'a, + F, + api::PaymentsCancelPostCaptureRequest, + PaymentData<F>, + >, + > { + let db = &*state.store; + let key_manager_state = &state.into(); + + let merchant_id = merchant_context.get_merchant_account().get_id(); + let storage_scheme = merchant_context.get_merchant_account().storage_scheme; + let payment_id = payment_id + .get_payment_intent_id() + .change_context(errors::ApiErrorResponse::PaymentNotFound)?; + + let payment_intent = db + .find_payment_intent_by_payment_id_merchant_id( + key_manager_state, + &payment_id, + merchant_id, + merchant_context.get_merchant_key_store(), + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + helpers::validate_payment_status_against_allowed_statuses( + payment_intent.status, + &[ + enums::IntentStatus::Succeeded, + enums::IntentStatus::PartiallyCaptured, + enums::IntentStatus::PartiallyCapturedAndCapturable, + ], + "cancel_post_capture", + )?; + + let mut payment_attempt = db + .find_payment_attempt_by_payment_id_merchant_id_attempt_id( + &payment_intent.payment_id, + merchant_id, + payment_intent.active_attempt.get_id().as_str(), + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + let shipping_address = helpers::get_address_by_id( + state, + payment_intent.shipping_address_id.clone(), + merchant_context.get_merchant_key_store(), + &payment_intent.payment_id, + merchant_id, + merchant_context.get_merchant_account().storage_scheme, + ) + .await?; + + let billing_address = helpers::get_address_by_id( + state, + payment_intent.billing_address_id.clone(), + merchant_context.get_merchant_key_store(), + &payment_intent.payment_id, + merchant_id, + merchant_context.get_merchant_account().storage_scheme, + ) + .await?; + + let payment_method_billing = helpers::get_address_by_id( + state, + payment_attempt.payment_method_billing_address_id.clone(), + merchant_context.get_merchant_key_store(), + &payment_intent.payment_id, + merchant_id, + merchant_context.get_merchant_account().storage_scheme, + ) + .await?; + + let currency = payment_attempt.currency.get_required_value("currency")?; + let amount = payment_attempt.get_total_amount().into(); + + payment_attempt + .cancellation_reason + .clone_from(&request.cancellation_reason); + + let profile_id = payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("'profile_id' not set in payment intent")?; + + let business_profile = db + .find_business_profile_by_profile_id( + key_manager_state, + merchant_context.get_merchant_key_store(), + profile_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { + id: profile_id.get_string_repr().to_owned(), + })?; + + let payment_data = PaymentData { + flow: PhantomData, + payment_intent, + payment_attempt, + currency, + amount, + email: None, + mandate_id: None, + mandate_connector: None, + setup_mandate: None, + customer_acceptance: None, + token: None, + token_data: None, + address: core_types::PaymentAddress::new( + shipping_address.as_ref().map(From::from), + billing_address.as_ref().map(From::from), + payment_method_billing.as_ref().map(From::from), + business_profile.use_billing_as_payment_method_billing, + ), + confirm: None, + payment_method_data: None, + payment_method_token: None, + payment_method_info: None, + force_sync: None, + all_keys_required: None, + refunds: vec![], + disputes: vec![], + attempts: None, + sessions_token: vec![], + card_cvc: None, + creds_identifier: None, + pm_token: None, + connector_customer_id: None, + recurring_mandate_payment_data: None, + ephemeral_key: None, + multiple_capture_data: None, + redirect_response: None, + surcharge_details: None, + frm_message: None, + payment_link_data: None, + incremental_authorization_details: None, + authorizations: vec![], + authentication: None, + recurring_details: None, + poll_config: None, + tax_data: None, + session_id: None, + service_details: None, + card_testing_guard_data: None, + vault_operation: None, + threeds_method_comp_ind: None, + whole_connector_response: None, + }; + + let get_trackers_response = operations::GetTrackerResponse { + operation: Box::new(self), + customer_details: None, + payment_data, + business_profile, + mandate_type: None, + }; + + Ok(get_trackers_response) + } +} + +#[async_trait] +impl<F: Clone + Send + Sync> Domain<F, api::PaymentsCancelPostCaptureRequest, PaymentData<F>> + for PaymentCancelPostCapture +{ + #[instrument(skip_all)] + async fn get_or_create_customer_details<'a>( + &'a self, + _state: &SessionState, + _payment_data: &mut PaymentData<F>, + _request: Option<payments::CustomerDetails>, + _merchant_key_store: &domain::MerchantKeyStore, + _storage_scheme: enums::MerchantStorageScheme, + ) -> errors::CustomResult< + ( + PaymentCancelPostCaptureOperation<'a, F>, + Option<domain::Customer>, + ), + errors::StorageError, + > { + Ok((Box::new(self), None)) + } + + #[instrument(skip_all)] + async fn make_pm_data<'a>( + &'a self, + _state: &'a SessionState, + _payment_data: &mut PaymentData<F>, + _storage_scheme: enums::MerchantStorageScheme, + _merchant_key_store: &domain::MerchantKeyStore, + _customer: &Option<domain::Customer>, + _business_profile: &domain::Profile, + _should_retry_with_pan: bool, + ) -> RouterResult<( + PaymentCancelPostCaptureOperation<'a, F>, + Option<domain::PaymentMethodData>, + Option<String>, + )> { + Ok((Box::new(self), None, None)) + } + + async fn get_connector<'a>( + &'a self, + _merchant_context: &domain::MerchantContext, + state: &SessionState, + _request: &api::PaymentsCancelPostCaptureRequest, + _payment_intent: &storage::PaymentIntent, + ) -> errors::CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { + helpers::get_connector_default(state, None).await + } + + #[instrument(skip_all)] + async fn guard_payment_against_blocklist<'a>( + &'a self, + _state: &SessionState, + _merchant_context: &domain::MerchantContext, + _payment_data: &mut PaymentData<F>, + ) -> errors::CustomResult<bool, errors::ApiErrorResponse> { + Ok(false) + } +} + +#[async_trait] +impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelPostCaptureRequest> + for PaymentCancelPostCapture +{ + #[instrument(skip_all)] + async fn update_trackers<'b>( + &'b self, + _state: &'b SessionState, + _req_state: ReqState, + payment_data: PaymentData<F>, + _customer: Option<domain::Customer>, + _storage_scheme: enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, + _key_store: &domain::MerchantKeyStore, + _frm_suggestion: Option<FrmSuggestion>, + _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + ) -> RouterResult<(PaymentCancelPostCaptureOperation<'b, F>, PaymentData<F>)> + where + F: 'b + Send, + { + Ok((Box::new(self), payment_data)) + } +} + +impl<F: Send + Clone + Sync> + ValidateRequest<F, api::PaymentsCancelPostCaptureRequest, PaymentData<F>> + for PaymentCancelPostCapture +{ + #[instrument(skip_all)] + fn validate_request<'a, 'b>( + &'b self, + request: &api::PaymentsCancelPostCaptureRequest, + merchant_context: &'a domain::MerchantContext, + ) -> RouterResult<( + PaymentCancelPostCaptureOperation<'b, F>, + operations::ValidateResult, + )> { + Ok(( + Box::new(self), + operations::ValidateResult { + merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), + payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()), + storage_scheme: merchant_context.get_merchant_account().storage_scheme, + requeue: false, + }, + )) + } +} 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 13100e7762f..9c2e766e558 100644 --- a/crates/router/src/core/payments/operations/payment_capture_v2.rs +++ b/crates/router/src/core/payments/operations/payment_capture_v2.rs @@ -38,6 +38,7 @@ impl ValidateStatusForOperation for PaymentsCapture { | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction 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 a3b81afb4f8..73aa834613d 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -47,6 +47,7 @@ impl ValidateStatusForOperation for PaymentIntentConfirm { | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction diff --git a/crates/router/src/core/payments/operations/payment_get.rs b/crates/router/src/core/payments/operations/payment_get.rs index 621a6e71a70..3f4fb5ee6a3 100644 --- a/crates/router/src/core/payments/operations/payment_get.rs +++ b/crates/router/src/core/payments/operations/payment_get.rs @@ -42,6 +42,7 @@ impl ValidateStatusForOperation for PaymentGet { | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Ok(()), // These statuses are not valid for this operation diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 425173d4441..84deb90605a 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -61,7 +61,7 @@ use crate::{ #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation( operations = "post_update_tracker", - flow = "sync_data, cancel_data, authorize_data, capture_data, complete_authorize_data, approve_data, reject_data, setup_mandate_data, session_data,incremental_authorization_data, sdk_session_update_data, post_session_tokens_data, update_metadata_data" + flow = "sync_data, cancel_data, authorize_data, capture_data, complete_authorize_data, approve_data, reject_data, setup_mandate_data, session_data,incremental_authorization_data, sdk_session_update_data, post_session_tokens_data, update_metadata_data, cancel_post_capture_data" )] pub struct PaymentResponse; @@ -1023,6 +1023,49 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelData> f } } +#[cfg(feature = "v1")] +#[async_trait] +impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelPostCaptureData> + for PaymentResponse +{ + async fn update_tracker<'b>( + &'b self, + db: &'b SessionState, + mut payment_data: PaymentData<F>, + router_data: types::RouterData< + F, + types::PaymentsCancelPostCaptureData, + types::PaymentsResponseData, + >, + key_store: &domain::MerchantKeyStore, + storage_scheme: enums::MerchantStorageScheme, + locale: &Option<String>, + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec< + RoutableConnectorChoice, + >, + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile, + ) -> RouterResult<PaymentData<F>> + where + F: 'b + Send, + { + payment_data = Box::pin(payment_response_update_tracker( + db, + payment_data, + router_data, + key_store, + storage_scheme, + locale, + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] + routable_connector, + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] + business_profile, + )) + .await?; + + Ok(payment_data) + } +} + #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsApproveData> @@ -2559,6 +2602,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthor | common_enums::AttemptStatus::RouterDeclined | common_enums::AttemptStatus::AuthorizationFailed | common_enums::AttemptStatus::Voided + | common_enums::AttemptStatus::VoidedPostCharge | common_enums::AttemptStatus::VoidInitiated | common_enums::AttemptStatus::CaptureFailed | common_enums::AttemptStatus::VoidFailed diff --git a/crates/router/src/core/payments/operations/payment_session_intent.rs b/crates/router/src/core/payments/operations/payment_session_intent.rs index d713c5175b2..da6a8b9e049 100644 --- a/crates/router/src/core/payments/operations/payment_session_intent.rs +++ b/crates/router/src/core/payments/operations/payment_session_intent.rs @@ -33,6 +33,7 @@ impl ValidateStatusForOperation for PaymentSessionIntent { match intent_status { common_enums::IntentStatus::RequiresPaymentMethod => Ok(()), common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rs index 6e500e3eb0b..b8f19580f12 100644 --- a/crates/router/src/core/payments/operations/payment_update_intent.rs +++ b/crates/router/src/core/payments/operations/payment_update_intent.rs @@ -53,6 +53,7 @@ impl ValidateStatusForOperation for PaymentUpdateIntent { | common_enums::IntentStatus::Conflicted => Ok(()), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction 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 3994fd8ef05..9170b36462a 100644 --- a/crates/router/src/core/payments/operations/proxy_payments_intent.rs +++ b/crates/router/src/core/payments/operations/proxy_payments_intent.rs @@ -49,6 +49,7 @@ impl ValidateStatusForOperation for PaymentProxyIntent { common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresCapture diff --git a/crates/router/src/core/payments/payment_methods.rs b/crates/router/src/core/payments/payment_methods.rs index 9bf9d3cc921..01beb8df7a6 100644 --- a/crates/router/src/core/payments/payment_methods.rs +++ b/crates/router/src/core/payments/payment_methods.rs @@ -364,6 +364,7 @@ fn validate_payment_status_for_payment_method_list( | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index b435bd191ef..0ce5bd54674 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -782,6 +782,7 @@ impl<F: Send + Clone + Sync, FData: Send + Sync> | storage_enums::AttemptStatus::Authorizing | storage_enums::AttemptStatus::CodInitiated | storage_enums::AttemptStatus::Voided + | storage_enums::AttemptStatus::VoidedPostCharge | storage_enums::AttemptStatus::VoidInitiated | storage_enums::AttemptStatus::CaptureInitiated | storage_enums::AttemptStatus::RouterDeclined diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index dd9b41ee9d2..c0d1504e12e 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -4160,6 +4160,42 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelDa } } +#[cfg(feature = "v2")] +impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelPostCaptureData { + type Error = error_stack::Report<errors::ApiErrorResponse>; + + fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { + todo!() + } +} + +#[cfg(feature = "v1")] +impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelPostCaptureData { + type Error = error_stack::Report<errors::ApiErrorResponse>; + + fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { + let payment_data = additional_data.payment_data; + let connector = api::ConnectorData::get_connector_by_name( + &additional_data.state.conf.connectors, + &additional_data.connector_name, + api::GetToken::Connector, + payment_data.payment_attempt.merchant_connector_id.clone(), + )?; + let amount = payment_data.payment_attempt.get_total_amount(); + + Ok(Self { + minor_amount: Some(amount), + currency: Some(payment_data.currency), + connector_transaction_id: connector + .connector + .connector_transaction_id(&payment_data.payment_attempt)? + .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, + cancellation_reason: payment_data.payment_attempt.cancellation_reason, + connector_meta: payment_data.payment_attempt.connector_metadata, + }) + } +} + impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsApproveData { type Error = error_stack::Report<errors::ApiErrorResponse>; diff --git a/crates/router/src/core/revenue_recovery/transformers.rs b/crates/router/src/core/revenue_recovery/transformers.rs index 76f987673da..7faccbd0d7c 100644 --- a/crates/router/src/core/revenue_recovery/transformers.rs +++ b/crates/router/src/core/revenue_recovery/transformers.rs @@ -28,6 +28,7 @@ impl ForeignFrom<AttemptStatus> for RevenueRecoveryPaymentsAttemptStatus { | AttemptStatus::Failure => Self::Failed, AttemptStatus::Voided + | AttemptStatus::VoidedPostCharge | AttemptStatus::ConfirmationAwaited | AttemptStatus::PartialCharged | AttemptStatus::PartialChargedAndChargeable diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 5d5a16912e2..b43f0138f39 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -1705,6 +1705,7 @@ fn get_desired_payment_status_for_dynamic_routing_metrics( | common_enums::AttemptStatus::Authorizing | common_enums::AttemptStatus::CodInitiated | common_enums::AttemptStatus::Voided + | common_enums::AttemptStatus::VoidedPostCharge | common_enums::AttemptStatus::VoidInitiated | common_enums::AttemptStatus::CaptureInitiated | common_enums::AttemptStatus::VoidFailed @@ -1736,6 +1737,7 @@ impl ForeignFrom<common_enums::AttemptStatus> for open_router::TxnStatus { common_enums::AttemptStatus::Voided | common_enums::AttemptStatus::Expired => { Self::Voided } + common_enums::AttemptStatus::VoidedPostCharge => Self::VoidedPostCharge, common_enums::AttemptStatus::VoidInitiated => Self::VoidInitiated, common_enums::AttemptStatus::CaptureInitiated => Self::CaptureInitiated, common_enums::AttemptStatus::CaptureFailed => Self::CaptureFailed, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 9584a9af160..0fbb177120b 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -805,6 +805,9 @@ impl Payments { .service( web::resource("/{payment_id}/cancel").route(web::post().to(payments::payments_cancel)), ) + .service( + web::resource("/{payment_id}/cancel_post_capture").route(web::post().to(payments::payments_cancel_post_capture)), + ) .service( web::resource("/{payment_id}/capture").route(web::post().to(payments::payments_capture)), ) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 58865de64af..8defd917053 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -142,6 +142,7 @@ impl From<Flow> for ApiIdentifier { | Flow::PaymentsConfirm | Flow::PaymentsCapture | Flow::PaymentsCancel + | Flow::PaymentsCancelPostCapture | Flow::PaymentsApprove | Flow::PaymentsReject | Flow::PaymentsSessionToken diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 74e6c580ff4..8687a5f9d06 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -1491,6 +1491,60 @@ pub async fn payments_cancel( .await } +#[cfg(feature = "v1")] +#[instrument(skip_all, fields(flow = ?Flow::PaymentsCancelPostCapture, payment_id))] +pub async fn payments_cancel_post_capture( + state: web::Data<app::AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<payment_types::PaymentsCancelPostCaptureRequest>, + path: web::Path<common_utils::id_type::PaymentId>, +) -> impl Responder { + let flow = Flow::PaymentsCancelPostCapture; + let mut payload = json_payload.into_inner(); + let payment_id = path.into_inner(); + + tracing::Span::current().record("payment_id", payment_id.get_string_repr()); + + payload.payment_id = payment_id; + 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| { + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( + domain::Context(auth.merchant_account, auth.key_store), + )); + payments::payments_core::< + api_types::PostCaptureVoid, + payment_types::PaymentsResponse, + _, + _, + _, + payments::PaymentData<api_types::PostCaptureVoid>, + >( + state, + req_state, + merchant_context, + auth.profile_id, + payments::PaymentCancelPostCapture, + req, + api::AuthFlow::Merchant, + payments::CallConnectorAction::Trigger, + None, + HeaderPayload::default(), + ) + }, + &auth::HeaderAuth(auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: true, + }), + locking_action, + )) + .await +} + #[instrument(skip_all, fields(flow = ?Flow::PaymentsList))] #[cfg(all(feature = "olap", feature = "v1"))] pub async fn payments_list( @@ -2507,6 +2561,23 @@ impl GetLockingInput for payment_types::PaymentsCancelRequest { } } +#[cfg(feature = "v1")] +impl GetLockingInput for payment_types::PaymentsCancelPostCaptureRequest { + fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction + where + F: types::FlowMetric, + lock_utils::ApiIdentifier: From<F>, + { + api_locking::LockAction::Hold { + input: api_locking::LockingInput { + unique_locking_key: self.payment_id.get_string_repr().to_owned(), + api_identifier: lock_utils::ApiIdentifier::from(flow), + override_lock_retries: None, + }, + } + } +} + #[cfg(feature = "v1")] impl GetLockingInput for payment_types::PaymentsCaptureRequest { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 780093fd012..85a159f55f6 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1147,6 +1147,7 @@ impl Authenticate for api_models::payments::PaymentsRetrieveRequest { } } impl Authenticate for api_models::payments::PaymentsCancelRequest {} +impl Authenticate for api_models::payments::PaymentsCancelPostCaptureRequest {} impl Authenticate for api_models::payments::PaymentsCaptureRequest {} impl Authenticate for api_models::payments::PaymentsIncrementalAuthorizationRequest {} impl Authenticate for api_models::payments::PaymentsStartRequest {} diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 3a51c628b82..579e8d91722 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -38,8 +38,8 @@ use hyperswitch_domain_models::router_flow_types::{ payments::{ Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, IncrementalAuthorization, - InitPayment, PSync, PostProcessing, PostSessionTokens, PreProcessing, Reject, - SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, + InitPayment, PSync, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, + Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, refunds::{Execute, RSync}, webhooks::VerifyWebhookSource, @@ -72,10 +72,10 @@ pub use hyperswitch_domain_models::{ CompleteAuthorizeRedirectResponse, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, DestinationChargeRefund, DirectChargeRefund, MandateRevokeRequestData, MultipleCaptureRequestData, PaymentMethodTokenizationData, - PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, - PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, - PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, - PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, + PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, + PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, + PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, + PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, ResponseId, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, SplitRefundsRequest, SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData, VaultRequestData, @@ -101,12 +101,12 @@ pub use hyperswitch_domain_models::{ pub use hyperswitch_interfaces::types::{ AcceptDisputeType, ConnectorCustomerType, DefendDisputeType, IncrementalAuthorizationType, MandateRevokeType, PaymentsAuthorizeType, PaymentsBalanceType, PaymentsCaptureType, - PaymentsCompleteAuthorizeType, PaymentsInitType, PaymentsPostProcessingType, - PaymentsPostSessionTokensType, PaymentsPreAuthorizeType, PaymentsPreProcessingType, - PaymentsSessionType, PaymentsSyncType, PaymentsUpdateMetadataType, PaymentsVoidType, - RefreshTokenType, RefundExecuteType, RefundSyncType, Response, RetrieveFileType, - SdkSessionUpdateType, SetupMandateType, SubmitEvidenceType, TokenizationType, UploadFileType, - VerifyWebhookSourceType, + PaymentsCompleteAuthorizeType, PaymentsInitType, PaymentsPostCaptureVoidType, + PaymentsPostProcessingType, PaymentsPostSessionTokensType, PaymentsPreAuthorizeType, + PaymentsPreProcessingType, PaymentsSessionType, PaymentsSyncType, PaymentsUpdateMetadataType, + PaymentsVoidType, RefreshTokenType, RefundExecuteType, RefundSyncType, Response, + RetrieveFileType, SdkSessionUpdateType, SetupMandateType, SubmitEvidenceType, TokenizationType, + UploadFileType, VerifyWebhookSourceType, }; #[cfg(feature = "payouts")] pub use hyperswitch_interfaces::types::{ @@ -164,6 +164,8 @@ pub type PaymentsUpdateMetadataRouterData = RouterData<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>; pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>; +pub type PaymentsCancelPostCaptureRouterData = + RouterData<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>; pub type PaymentsRejectRouterData = RouterData<Reject, PaymentsRejectData, PaymentsResponseData>; pub type PaymentsApproveRouterData = RouterData<Approve, PaymentsApproveData, PaymentsResponseData>; pub type PaymentsSessionRouterData = RouterData<Session, PaymentsSessionData, PaymentsResponseData>; @@ -184,6 +186,8 @@ pub type PaymentsResponseRouterData<R> = ResponseRouterData<Authorize, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsCancelResponseRouterData<R> = ResponseRouterData<Void, R, PaymentsCancelData, PaymentsResponseData>; +pub type PaymentsCancelPostCaptureResponseRouterData<R> = + ResponseRouterData<PostCaptureVoid, R, PaymentsCancelPostCaptureData, PaymentsResponseData>; pub type PaymentsBalanceResponseRouterData<R> = ResponseRouterData<Balance, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsSyncResponseRouterData<R> = @@ -306,6 +310,7 @@ impl Capturable for PaymentsAuthorizeData { | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction @@ -348,6 +353,7 @@ impl Capturable for PaymentsCaptureData { | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Processing | common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction @@ -393,6 +399,7 @@ impl Capturable for CompleteAuthorizeData { | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::PartiallyCaptured + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod @@ -437,6 +444,45 @@ impl Capturable for PaymentsCancelData { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture + | common_enums::IntentStatus::Processing + | common_enums::IntentStatus::PartiallyCaptured + | common_enums::IntentStatus::Conflicted + | common_enums::IntentStatus::Expired => Some(0), + common_enums::IntentStatus::Succeeded + | common_enums::IntentStatus::Failed + | common_enums::IntentStatus::RequiresCustomerAction + | common_enums::IntentStatus::RequiresMerchantAction + | common_enums::IntentStatus::RequiresPaymentMethod + | common_enums::IntentStatus::RequiresConfirmation + | common_enums::IntentStatus::RequiresCapture + | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, + } + } +} +impl Capturable for PaymentsCancelPostCaptureData { + fn get_captured_amount<F>(&self, payment_data: &PaymentData<F>) -> Option<i64> + where + F: Clone, + { + // return previously captured amount + payment_data + .payment_intent + .amount_captured + .map(|amt| amt.get_amount_as_i64()) + } + fn get_amount_capturable<F>( + &self, + _payment_data: &PaymentData<F>, + attempt_status: common_enums::AttemptStatus, + ) -> Option<i64> + where + F: Clone, + { + let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); + match intent_status { + common_enums::IntentStatus::Cancelled + | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index e28ac53ad32..f04dc1a6fd8 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -19,8 +19,8 @@ pub use api_models::{ MandateValidationFields, NextActionType, OpenBankingSessionToken, PayLaterData, PaymentIdType, PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2, PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp, - PaymentsAggregateResponse, PaymentsApproveRequest, PaymentsCancelRequest, - PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, + PaymentsAggregateResponse, PaymentsApproveRequest, PaymentsCancelPostCaptureRequest, + PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse, PaymentsExternalAuthenticationRequest, PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest, PaymentsPostSessionTokensRequest, @@ -37,24 +37,25 @@ use error_stack::ResultExt; pub use hyperswitch_domain_models::router_flow_types::payments::{ Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, IncrementalAuthorization, InitPayment, PSync, - PaymentCreateIntent, PaymentGetIntent, PaymentMethodToken, PaymentUpdateIntent, PostProcessing, - PostSessionTokens, PreProcessing, RecordAttempt, Reject, SdkSessionUpdate, Session, - SetupMandate, UpdateMetadata, Void, + PaymentCreateIntent, PaymentGetIntent, PaymentMethodToken, PaymentUpdateIntent, + PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, RecordAttempt, Reject, + SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }; pub use hyperswitch_interfaces::api::payments::{ ConnectorCustomer, MandateSetup, Payment, PaymentApprove, PaymentAuthorize, PaymentAuthorizeSessionToken, PaymentCapture, PaymentIncrementalAuthorization, - PaymentPostSessionTokens, PaymentReject, PaymentSession, PaymentSessionUpdate, PaymentSync, - PaymentToken, PaymentUpdateMetadata, PaymentVoid, PaymentsCompleteAuthorize, - PaymentsCreateOrder, PaymentsPostProcessing, PaymentsPreProcessing, TaxCalculation, + PaymentPostCaptureVoid, PaymentPostSessionTokens, PaymentReject, PaymentSession, + PaymentSessionUpdate, PaymentSync, PaymentToken, PaymentUpdateMetadata, PaymentVoid, + PaymentsCompleteAuthorize, PaymentsCreateOrder, PaymentsPostProcessing, PaymentsPreProcessing, + TaxCalculation, }; pub use super::payments_v2::{ ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2, PaymentAuthorizeV2, PaymentCaptureV2, PaymentIncrementalAuthorizationV2, - PaymentPostSessionTokensV2, PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, - PaymentSyncV2, PaymentTokenV2, PaymentUpdateMetadataV2, PaymentV2, PaymentVoidV2, - PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, + PaymentPostCaptureVoidV2, PaymentPostSessionTokensV2, PaymentRejectV2, PaymentSessionUpdateV2, + PaymentSessionV2, PaymentSyncV2, PaymentTokenV2, PaymentUpdateMetadataV2, PaymentV2, + PaymentVoidV2, PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, TaxCalculationV2, }; use crate::core::errors; diff --git a/crates/router/src/types/api/payments_v2.rs b/crates/router/src/types/api/payments_v2.rs index 78e3ea7a706..ad0a615a609 100644 --- a/crates/router/src/types/api/payments_v2.rs +++ b/crates/router/src/types/api/payments_v2.rs @@ -1,8 +1,8 @@ pub use hyperswitch_interfaces::api::payments_v2::{ ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2, PaymentAuthorizeV2, PaymentCaptureV2, PaymentIncrementalAuthorizationV2, - PaymentPostSessionTokensV2, PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, - PaymentSyncV2, PaymentTokenV2, PaymentUpdateMetadataV2, PaymentV2, PaymentVoidV2, - PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, + PaymentPostCaptureVoidV2, PaymentPostSessionTokensV2, PaymentRejectV2, PaymentSessionUpdateV2, + PaymentSessionV2, PaymentSyncV2, PaymentTokenV2, PaymentUpdateMetadataV2, PaymentV2, + PaymentVoidV2, PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, TaxCalculationV2, }; diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 02056774729..e7978e1dcdb 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -161,6 +161,7 @@ impl ForeignTryFrom<storage_enums::AttemptStatus> for storage_enums::CaptureStat | storage_enums::AttemptStatus::Authorizing | storage_enums::AttemptStatus::CodInitiated | storage_enums::AttemptStatus::Voided + | storage_enums::AttemptStatus::VoidedPostCharge | storage_enums::AttemptStatus::VoidInitiated | storage_enums::AttemptStatus::VoidFailed | storage_enums::AttemptStatus::AutoRefunded diff --git a/crates/router_derive/src/macros/operation.rs b/crates/router_derive/src/macros/operation.rs index 103f83076bf..2e6dabe0b29 100644 --- a/crates/router_derive/src/macros/operation.rs +++ b/crates/router_derive/src/macros/operation.rs @@ -19,6 +19,8 @@ pub enum Derives { AuthorizeData, SyncData, CancelData, + CancelPostCapture, + CancelPostCaptureData, CaptureData, CompleteAuthorizeData, RejectData, @@ -129,6 +131,12 @@ impl Conversion { Derives::UpdateMetadataData => { syn::Ident::new("PaymentsUpdateMetadataData", Span::call_site()) } + Derives::CancelPostCapture => { + syn::Ident::new("PaymentsCancelPostCaptureRequest", Span::call_site()) + } + Derives::CancelPostCaptureData => { + syn::Ident::new("PaymentsCancelPostCaptureData", Span::call_site()) + } } } @@ -452,6 +460,7 @@ pub fn operation_derive_inner(input: DeriveInput) -> syn::Result<proc_macro::Tok SdkPaymentsSessionUpdateData, PaymentsPostSessionTokensData, PaymentsUpdateMetadataData, + PaymentsCancelPostCaptureData, api::{ PaymentsCaptureRequest, @@ -466,7 +475,8 @@ pub fn operation_derive_inner(input: DeriveInput) -> syn::Result<proc_macro::Tok PaymentsDynamicTaxCalculationRequest, PaymentsIncrementalAuthorizationRequest, PaymentsPostSessionTokensRequest, - PaymentsUpdateMetadataRequest + PaymentsUpdateMetadataRequest, + PaymentsCancelPostCaptureRequest, } }; #trait_derive diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 1fefce2b33b..e798e80e1d2 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -156,6 +156,8 @@ pub enum Flow { PaymentsCapture, /// Payments cancel flow. PaymentsCancel, + /// Payments cancel post capture flow. + PaymentsCancelPostCapture, /// Payments approve flow. PaymentsApprove, /// Payments reject flow. diff --git a/migrations/2025-08-04-143048_add-VoidedPostCharge/down.sql b/migrations/2025-08-04-143048_add-VoidedPostCharge/down.sql new file mode 100644 index 00000000000..2a3866c86d4 --- /dev/null +++ b/migrations/2025-08-04-143048_add-VoidedPostCharge/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +SELECT 1; diff --git a/migrations/2025-08-04-143048_add-VoidedPostCharge/up.sql b/migrations/2025-08-04-143048_add-VoidedPostCharge/up.sql new file mode 100644 index 00000000000..50dde423fdc --- /dev/null +++ b/migrations/2025-08-04-143048_add-VoidedPostCharge/up.sql @@ -0,0 +1,6 @@ +-- Your SQL goes here +ALTER TYPE "IntentStatus" ADD VALUE IF NOT EXISTS 'cancelled_post_capture'; + +ALTER TYPE "AttemptStatus" ADD VALUE IF NOT EXISTS 'voided_post_charge'; + +ALTER TYPE "EventType" ADD VALUE IF NOT EXISTS 'payment_cancelled_post_capture'; \ No newline at end of file
2025-08-05T08:52:03Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Add core flow for Void after Capture - Add PostCaptureVoid Flow in worldpayVantiv 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? Added in Mintlify API reference <img width="1490" height="681" alt="Screenshot 2025-08-05 at 6 38 43β€―PM" src="https://github.com/user-attachments/assets/192a2e9b-beca-46b7-90a2-5b2428bac7f4" /> 1. Create a Vantiv payment ``` { "amount": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "aaaa", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4457000300000007", "card_exp_month": "01", "card_exp_year": "50", // "card_holder_name": "Joseph", "card_cvc": "987" // "card_network":"M" } }, "billing": { "address": { "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "city": "Downtown Core", "state": "Central Indiana America", "zip": "039393", "country": "SG", "first_name": "λ°•μ„±μ€€", "last_name": "λ°•μ„±μ€€" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "city": "Downtown Core", "state": "Central Indiana America", "zip": "039393", "country": "SG", "first_name": "λ°•μ„±μ€€", "last_name": "λ°•μ„±μ€€" }, "phone": { "number": "8056594427", "country_code": "+91" } } } ``` response ``` {"payment_id":"pay_6U7z9JffFphSvaHOa82X","merchant_id":"merchant_1754307959","status":"processing","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":"worldpayvantiv","client_secret":"pay_6U7z9JffFphSvaHOa82X_secret_lrLWdp5mBXe337IX33p6","created":"2025-08-05T09:10:50.360Z","currency":"USD","customer_id":"aaaa","customer":{"id":"aaaa","name":null,"email":null,"phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"0007","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"445700","card_extended_bin":null,"card_exp_month":"01","card_exp_year":"50","card_holder_name":null,"payment_checks":{"avs_result":"00","advanced_a_v_s_result":null,"authentication_result":null,"card_validation_result":"U"},"authentication_data":null},"billing":null},"payment_token":null,"shipping":{"address":{"city":"Downtown Core","country":"SG","line1":"Singapore Changi Airport. 2nd flr","line2":"","line3":"","zip":"039393","state":"Central Indiana America","first_name":"λ°•μ„±μ€€","last_name":"λ°•μ„±μ€€"},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"billing":{"address":{"city":"Downtown Core","country":"SG","line1":"Singapore Changi Airport. 2nd flr","line2":"","line3":"","zip":"039393","state":"Central Indiana America","first_name":"λ°•μ„±μ€€","last_name":"λ°•μ„±μ€€"},"phone":{"number":"8056594427","country_code":"+91"},"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":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"aaaa","created_at":1754385050,"expires":1754388650,"secret":"epk_e68679fd37f84775b725fa5a8058abb9"},"manual_retry_allowed":false,"connector_transaction_id":"83997345492141650","frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":"pay_6U7z9JffFphSvaHOa82X_1","payment_link":null,"profile_id":"pro_39QoIo9WbzDFwm4iqtRI","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_8Skj4ar2yQ9GBKIGCdAZ","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-08-05T09:25:50.360Z","fingerprint":null,"browser_info":null,"payment_channel":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-08-05T09:10:54.164Z","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,"is_iframe_redirection_enabled":null,"whole_connector_response":null} ``` 2. Do psync ``` curl --location 'http://localhost:8080/payments/pay_6U7z9JffFphSvaHOa82X?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_X4UzFm38nxtfI8vV2m1hPnJlW4AKkxYfjr4z9tNRjnxxIbLNok5xyLKKsIBoxaSQ' ``` Response ``` { "payment_id": "pay_6U7z9JffFphSvaHOa82X", "merchant_id": "merchant_1754307959", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "worldpayvantiv", "client_secret": "pay_6U7z9JffFphSvaHOa82X_secret_lrLWdp5mBXe337IX33p6", "created": "2025-08-05T09:10:50.360Z", "currency": "USD", "customer_id": "aaaa", "customer": { "id": "aaaa", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0007", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "445700", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "50", "card_holder_name": null, "payment_checks": { "avs_result": "00", "advanced_a_v_s_result": null, "authentication_result": null, "card_validation_result": "U" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "λ°•μ„±μ€€", "last_name": "λ°•μ„±μ€€" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "λ°•μ„±μ€€", "last_name": "λ°•μ„±μ€€" }, "phone": { "number": "8056594427", "country_code": "+91" }, "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": "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": "83997345492141650", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_6U7z9JffFphSvaHOa82X_1", "payment_link": null, "profile_id": "pro_39QoIo9WbzDFwm4iqtRI", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_8Skj4ar2yQ9GBKIGCdAZ", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-05T09:25:50.360Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-08-05T09:12:15.057Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` 3. We will do cancel_post_capture ``` curl --location 'http://localhost:8080/payments/pay_6U7z9JffFphSvaHOa82X/cancel_post_capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_X4UzFm38nxtfI8vV2m1hPnJlW4AKkxYfjr4z9tNRjnxxIbLNok5xyLKKsIBoxaSQ' \ --data '{ "cancellation_reason": "requested_by_customer" }' ``` Response ``` { "payment_id": "pay_6U7z9JffFphSvaHOa82X", "merchant_id": "merchant_1754307959", "status": "processing", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "worldpayvantiv", "client_secret": "pay_6U7z9JffFphSvaHOa82X_secret_lrLWdp5mBXe337IX33p6", "created": "2025-08-05T09:10:50.360Z", "currency": "USD", "customer_id": null, "customer": null, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0007", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "445700", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "50", "card_holder_name": null, "payment_checks": { "avs_result": "00", "advanced_a_v_s_result": null, "authentication_result": null, "card_validation_result": "U" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "λ°•μ„±μ€€", "last_name": "λ°•μ„±μ€€" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "λ°•μ„±μ€€", "last_name": "λ°•μ„±μ€€" }, "phone": { "number": "8056594427", "country_code": "+91" }, "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": "requested_by_customer", "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": "84085305358301450", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_6U7z9JffFphSvaHOa82X_1", "payment_link": null, "profile_id": "pro_39QoIo9WbzDFwm4iqtRI", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_8Skj4ar2yQ9GBKIGCdAZ", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-05T09:25:50.360Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-08-05T09:13:07.054Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` 4. Do sync to check the status ``` curl --location 'http://localhost:8080/payments/pay_6U7z9JffFphSvaHOa82X?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_X4UzFm38nxtfI8vV2m1hPnJlW4AKkxYfjr4z9tNRjnxxIbLNok5xyLKKsIBoxaSQ' ``` Response - Status will be `cancelled_post_capture` ``` { "payment_id": "pay_6U7z9JffFphSvaHOa82X", "merchant_id": "merchant_1754307959", "status": "cancelled_post_capture", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "worldpayvantiv", "client_secret": "pay_6U7z9JffFphSvaHOa82X_secret_lrLWdp5mBXe337IX33p6", "created": "2025-08-05T09:10:50.360Z", "currency": "USD", "customer_id": "aaaa", "customer": { "id": "aaaa", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0007", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "445700", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "50", "card_holder_name": null, "payment_checks": { "avs_result": "00", "advanced_a_v_s_result": null, "authentication_result": null, "card_validation_result": "U" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "λ°•μ„±μ€€", "last_name": "λ°•μ„±μ€€" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "Downtown Core", "country": "SG", "line1": "Singapore Changi Airport. 2nd flr", "line2": "", "line3": "", "zip": "039393", "state": "Central Indiana America", "first_name": "λ°•μ„±μ€€", "last_name": "λ°•μ„±μ€€" }, "phone": { "number": "8056594427", "country_code": "+91" }, "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": "requested_by_customer", "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": "84085305358301450", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_6U7z9JffFphSvaHOa82X_1", "payment_link": null, "profile_id": "pro_39QoIo9WbzDFwm4iqtRI", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_8Skj4ar2yQ9GBKIGCdAZ", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-05T09:25:50.360Z", "fingerprint": null, "browser_info": null, "payment_channel": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-08-05T09:14:14.704Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` If we hit our \cancel (Void ) after a succeeded status, that will give error ``` { "error": { "type": "invalid_request", "message": "You cannot cancel this payment because it has status succeeded", "code": "IR_16" } } ``` ## 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.115.0
c573f611762ca52eb4ce8f0a0ddf9f87c506c6b3
c573f611762ca52eb4ce8f0a0ddf9f87c506c6b3
juspay/hyperswitch
juspay__hyperswitch-8806
Bug: [BUG] Add additional authentication fields for 3ds external authentication ### Bug Description Cybersource payments via Netcetera are failing for a France based acquirer in prod with Carte Bancaires card, the below fields needs to be added to fix the same. 1. challenge_code 2. challenge_code_reason 3. challenge_cancel 4. message_extension ### Expected Behavior Payments are currently failing in prod a france based acquirer ### Actual Behavior Payments should pass ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/diesel_models/src/authentication.rs b/crates/diesel_models/src/authentication.rs index 915d661bad2..c844df0a699 100644 --- a/crates/diesel_models/src/authentication.rs +++ b/crates/diesel_models/src/authentication.rs @@ -1,4 +1,4 @@ -use common_utils::encryption::Encryption; +use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{self, Deserialize, Serialize}; use serde_json; @@ -61,6 +61,10 @@ pub struct Authentication { pub browser_info: Option<serde_json::Value>, pub email: Option<Encryption>, pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>, + pub challenge_code: Option<String>, + pub challenge_cancel: Option<String>, + pub challenge_code_reason: Option<String>, + pub message_extension: Option<pii::SecretSerdeValue>, } impl Authentication { @@ -121,6 +125,10 @@ pub struct AuthenticationNew { pub browser_info: Option<serde_json::Value>, pub email: Option<Encryption>, pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>, + pub challenge_code: Option<String>, + pub challenge_cancel: Option<String>, + pub challenge_code_reason: Option<String>, + pub message_extension: Option<pii::SecretSerdeValue>, } #[derive(Debug)] @@ -167,11 +175,17 @@ pub enum AuthenticationUpdate { authentication_status: common_enums::AuthenticationStatus, ds_trans_id: Option<String>, eci: Option<String>, + challenge_code: Option<String>, + challenge_cancel: Option<String>, + challenge_code_reason: Option<String>, + message_extension: Option<pii::SecretSerdeValue>, }, PostAuthenticationUpdate { trans_status: common_enums::TransactionStatus, eci: Option<String>, authentication_status: common_enums::AuthenticationStatus, + challenge_cancel: Option<String>, + challenge_code_reason: Option<String>, }, ErrorUpdate { error_message: Option<String>, @@ -227,6 +241,10 @@ pub struct AuthenticationUpdateInternal { pub browser_info: Option<serde_json::Value>, pub email: Option<Encryption>, pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>, + pub challenge_code: Option<String>, + pub challenge_cancel: Option<String>, + pub challenge_code_reason: Option<String>, + pub message_extension: Option<pii::SecretSerdeValue>, } impl Default for AuthenticationUpdateInternal { @@ -267,6 +285,10 @@ impl Default for AuthenticationUpdateInternal { browser_info: Default::default(), email: Default::default(), profile_acquirer_id: Default::default(), + challenge_code: Default::default(), + challenge_cancel: Default::default(), + challenge_code_reason: Default::default(), + message_extension: Default::default(), } } } @@ -309,6 +331,10 @@ impl AuthenticationUpdateInternal { browser_info, email, profile_acquirer_id, + challenge_code, + challenge_cancel, + challenge_code_reason, + message_extension, } = self; Authentication { connector_authentication_id: connector_authentication_id @@ -350,6 +376,10 @@ impl AuthenticationUpdateInternal { browser_info: browser_info.or(source.browser_info), email: email.or(source.email), profile_acquirer_id: profile_acquirer_id.or(source.profile_acquirer_id), + challenge_code: challenge_code.or(source.challenge_code), + challenge_cancel: challenge_cancel.or(source.challenge_cancel), + challenge_code_reason: challenge_code_reason.or(source.challenge_code_reason), + message_extension: message_extension.or(source.message_extension), ..source } } @@ -438,6 +468,10 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal { authentication_status, ds_trans_id, eci, + challenge_code, + challenge_cancel, + challenge_code_reason, + message_extension, } => Self { trans_status: Some(trans_status), authentication_type: Some(authentication_type), @@ -450,16 +484,24 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal { authentication_status: Some(authentication_status), ds_trans_id, eci, + challenge_code, + challenge_cancel, + challenge_code_reason, + message_extension, ..Default::default() }, AuthenticationUpdate::PostAuthenticationUpdate { trans_status, eci, authentication_status, + challenge_cancel, + challenge_code_reason, } => Self { trans_status: Some(trans_status), eci, authentication_status: Some(authentication_status), + challenge_cancel, + challenge_code_reason, ..Default::default() }, AuthenticationUpdate::PreAuthenticationVersionCallUpdate { diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index c141f765536..16eb56df20d 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -137,6 +137,10 @@ diesel::table! { email -> Nullable<Bytea>, #[max_length = 128] profile_acquirer_id -> Nullable<Varchar>, + challenge_code -> Nullable<Varchar>, + challenge_cancel -> Nullable<Varchar>, + challenge_code_reason -> Nullable<Varchar>, + message_extension -> Nullable<Jsonb>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index e434e43b2c6..08fdecfd107 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -137,6 +137,10 @@ diesel::table! { email -> Nullable<Bytea>, #[max_length = 128] profile_acquirer_id -> Nullable<Varchar>, + challenge_code -> Nullable<Varchar>, + challenge_cancel -> Nullable<Varchar>, + challenge_code_reason -> Nullable<Varchar>, + message_extension -> Nullable<Jsonb>, } } diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index 2112989969e..ffef8b20c07 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -34,8 +34,9 @@ use hyperswitch_domain_models::{ SetupMandate, }, router_request_types::{ - CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, - PaymentsPreProcessingData, PaymentsSyncData, ResponseId, SetupMandateRequestData, + authentication::MessageExtensionAttribute, CompleteAuthorizeData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSyncData, + ResponseId, SetupMandateRequestData, }, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, @@ -313,6 +314,7 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest { ))? } }; + let cavv_algorithm = Some("2".to_string()); let processing_information = ProcessingInformation { capture: Some(false), @@ -322,6 +324,7 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest { authorization_options, commerce_indicator: String::from("internet"), payment_solution: solution.map(String::from), + cavv_algorithm, }; Ok(Self { processing_information, @@ -355,6 +358,7 @@ pub struct ProcessingInformation { capture: Option<bool>, capture_options: Option<CaptureOptions>, payment_solution: Option<String>, + cavv_algorithm: Option<String>, } #[derive(Debug, Serialize)] @@ -389,6 +393,7 @@ pub struct CybersourceConsumerAuthInformation { /// Raw electronic commerce indicator (ECI) eci_raw: Option<String>, /// This field is supported only on Asia, Middle East, and Africa Gateway + /// Also needed for Credit Mutuel-CIC in France and Mastercard Identity Check transactions /// This field is only applicable for Mastercard and Visa Transactions pares_status: Option<CybersourceParesStatus>, //This field is used to send the authentication date in yyyyMMDDHHMMSS format @@ -396,6 +401,16 @@ pub struct CybersourceConsumerAuthInformation { /// This field indicates the 3D Secure transaction flow. It is only supported for secure transactions in France. /// The possible values are - CH (Challenge), FD (Frictionless with delegation), FR (Frictionless) effective_authentication_type: Option<EffectiveAuthenticationType>, + /// This field indicates the authentication type or challenge presented to the cardholder at checkout. + challenge_code: Option<String>, + /// This field indicates the reason for payer authentication response status. It is only supported for secure transactions in France. + pares_status_reason: Option<String>, + /// This field indicates the reason why strong authentication was cancelled. It is only supported for secure transactions in France. + challenge_cancel_code: Option<String>, + /// This field indicates the score calculated by the 3D Securing platform. It is only supported for secure transactions in France. + network_score: Option<u32>, + /// This is the transaction ID generated by the access control server. This field is supported only for secure transactions in France. + acs_transaction_id: Option<String>, } #[derive(Debug, Serialize)] @@ -971,6 +986,11 @@ impl .map(|eci| get_commerce_indicator_for_external_authentication(network, eci)) }); + // The 3DS Server might not include the `cavvAlgorithm` field in the challenge response. + // In such cases, we default to "2", which represents the CVV with Authentication Transaction Number (ATN) algorithm. + // This is the most commonly used value for 3DS 2.0 transactions (e.g., Visa, Mastercard). + let cavv_algorithm = Some("2".to_string()); + Ok(Self { capture: Some(matches!( item.router_data.request.capture_method, @@ -983,6 +1003,7 @@ impl capture_options: None, commerce_indicator: commerce_indicator_for_external_authentication .unwrap_or(commerce_indicator), + cavv_algorithm, }) } } @@ -1079,6 +1100,8 @@ impl } else { (None, None, None) }; + let cavv_algorithm = Some("2".to_string()); + Ok(Self { capture: Some(matches!( item.router_data.request.capture_method, @@ -1093,6 +1116,7 @@ impl .indicator .to_owned() .unwrap_or(String::from("internet")), + cavv_algorithm, }) } } @@ -1241,6 +1265,53 @@ fn convert_metadata_to_merchant_defined_info(metadata: Value) -> Vec<MerchantDef vector } +/* +Example Message Extension: + +[ + MessageExtensionAttribute { + name: "CB-SCORE".to_string(), + id: "A000000042_CB-SCORE".to_string(), + criticality_indicator: false, + data: "some value".to_string(), + }, +] + +In this case, the **network score** is `42`, which should be extracted from the `id` field. +The score is encoded in the numeric part of the `id` (after removing the leading 'A' and before the underscore). + +Note: This field represents the score calculated by the 3D Securing platform. +It is only supported for secure transactions in France. +*/ + +fn extract_score_id(message_extensions: &[MessageExtensionAttribute]) -> Option<u32> { + message_extensions.iter().find_map(|attr| { + attr.id + .ends_with("CB-SCORE") + .then(|| { + attr.id + .split('_') + .next() + .and_then(|p| p.strip_prefix('A')) + .and_then(|s| { + s.parse::<u32>().map(Some).unwrap_or_else(|err| { + router_env::logger::error!( + "Failed to parse score_id from '{}': {}", + s, + err + ); + None + }) + }) + .or_else(|| { + router_env::logger::error!("Unexpected prefix format in id: {}", attr.id); + None + }) + }) + .flatten() + }) +} + impl From<common_enums::DecoupledAuthenticationType> for EffectiveAuthenticationType { fn from(auth_type: common_enums::DecoupledAuthenticationType) -> Self { match auth_type { @@ -1289,12 +1360,10 @@ impl None => ccard.get_card_issuer().ok().map(String::from), }; - let pares_status = - if card_type == Some("001".to_string()) || card_type == Some("002".to_string()) { - Some(CybersourceParesStatus::AuthenticationSuccessful) - } else { - None - }; + // For all card payments, we are explicitly setting `pares_status` to `AuthenticationSuccessful` + // to indicate that the Payer Authentication was successful, regardless of actual ACS response. + // This is a default behavior and may be adjusted based on future integration requirements. + let pares_status = Some(CybersourceParesStatus::AuthenticationSuccessful); let security_code = if item .router_data @@ -1349,7 +1418,29 @@ impl ) .ok(); let effective_authentication_type = authn_data.authentication_type.map(Into::into); - + let network_score: Option<u32> = + if ccard.card_network == Some(common_enums::CardNetwork::CartesBancaires) { + match authn_data.message_extension.as_ref() { + Some(secret) => { + let exposed_value = secret.clone().expose(); + match serde_json::from_value::<Vec<MessageExtensionAttribute>>( + exposed_value, + ) { + Ok(exts) => extract_score_id(&exts), + Err(err) => { + router_env::logger::error!( + "Failed to deserialize message_extension: {:?}", + err + ); + None + } + } + } + None => None, + } + } else { + None + }; CybersourceConsumerAuthInformation { pares_status, ucaf_collection_indicator, @@ -1366,6 +1457,11 @@ impl eci_raw: authn_data.eci.clone(), authentication_date, effective_authentication_type, + challenge_code: authn_data.challenge_code.clone(), + pares_status_reason: authn_data.challenge_code_reason.clone(), + challenge_cancel_code: authn_data.challenge_cancel.clone(), + network_score, + acs_transaction_id: authn_data.acs_trans_id.clone(), } }); @@ -1406,12 +1502,10 @@ impl Err(_) => None, }; - let pares_status = - if card_type == Some("001".to_string()) || card_type == Some("002".to_string()) { - Some(CybersourceParesStatus::AuthenticationSuccessful) - } else { - None - }; + // For all card payments, we are explicitly setting `pares_status` to `AuthenticationSuccessful` + // to indicate that the Payer Authentication was successful, regardless of actual ACS response. + // This is a default behavior and may be adjusted based on future integration requirements. + let pares_status = Some(CybersourceParesStatus::AuthenticationSuccessful); let payment_information = PaymentInformation::Cards(Box::new(CardPaymentInformation { card: Card { @@ -1451,6 +1545,29 @@ impl date_time::DateFormat::YYYYMMDDHHmmss, ) .ok(); + let network_score: Option<u32> = + if ccard.card_network == Some(common_enums::CardNetwork::CartesBancaires) { + match authn_data.message_extension.as_ref() { + Some(secret) => { + let exposed_value = secret.clone().expose(); + match serde_json::from_value::<Vec<MessageExtensionAttribute>>( + exposed_value, + ) { + Ok(exts) => extract_score_id(&exts), + Err(err) => { + router_env::logger::error!( + "Failed to deserialize message_extension: {:?}", + err + ); + None + } + } + } + None => None, + } + } else { + None + }; CybersourceConsumerAuthInformation { pares_status, ucaf_collection_indicator, @@ -1467,6 +1584,11 @@ impl eci_raw: authn_data.eci.clone(), authentication_date, effective_authentication_type, + challenge_code: authn_data.challenge_code.clone(), + pares_status_reason: authn_data.challenge_code_reason.clone(), + challenge_cancel_code: authn_data.challenge_cancel.clone(), + network_score, + acs_transaction_id: authn_data.acs_trans_id.clone(), } }); @@ -1510,12 +1632,10 @@ impl Err(_) => None, }; - let pares_status = - if card_type == Some("001".to_string()) || card_type == Some("002".to_string()) { - Some(CybersourceParesStatus::AuthenticationSuccessful) - } else { - None - }; + // For all card payments, we are explicitly setting `pares_status` to `AuthenticationSuccessful` + // to indicate that the Payer Authentication was successful, regardless of actual ACS response. + // This is a default behavior and may be adjusted based on future integration requirements. + let pares_status = Some(CybersourceParesStatus::AuthenticationSuccessful); let payment_information = PaymentInformation::NetworkToken(Box::new(NetworkTokenPaymentInformation { @@ -1556,6 +1676,30 @@ impl date_time::DateFormat::YYYYMMDDHHmmss, ) .ok(); + let network_score: Option<u32> = if token_data.card_network + == Some(common_enums::CardNetwork::CartesBancaires) + { + match authn_data.message_extension.as_ref() { + Some(secret) => { + let exposed_value = secret.clone().expose(); + match serde_json::from_value::<Vec<MessageExtensionAttribute>>( + exposed_value, + ) { + Ok(exts) => extract_score_id(&exts), + Err(err) => { + router_env::logger::error!( + "Failed to deserialize message_extension: {:?}", + err + ); + None + } + } + } + None => None, + } + } else { + None + }; CybersourceConsumerAuthInformation { pares_status, ucaf_collection_indicator, @@ -1572,6 +1716,11 @@ impl eci_raw: authn_data.eci.clone(), authentication_date, effective_authentication_type, + challenge_code: authn_data.challenge_code.clone(), + pares_status_reason: authn_data.challenge_code_reason.clone(), + challenge_cancel_code: authn_data.challenge_cancel.clone(), + network_score, + acs_transaction_id: authn_data.acs_trans_id.clone(), } }); @@ -1707,12 +1856,10 @@ impl None => ccard.get_card_issuer().ok().map(String::from), }; - let pares_status = - if card_type == Some("001".to_string()) || card_type == Some("002".to_string()) { - Some(CybersourceParesStatus::AuthenticationSuccessful) - } else { - None - }; + // For all card payments, we are explicitly setting `pares_status` to `AuthenticationSuccessful` + // to indicate that the Payer Authentication was successful, regardless of actual ACS response. + // This is a default behavior and may be adjusted based on future integration requirements. + let pares_status = Some(CybersourceParesStatus::AuthenticationSuccessful); let payment_information = PaymentInformation::Cards(Box::new(CardPaymentInformation { card: Card { @@ -1757,6 +1904,11 @@ impl eci_raw: None, authentication_date: None, effective_authentication_type: None, + challenge_code: None, + pares_status_reason: None, + challenge_cancel_code: None, + network_score: None, + acs_transaction_id: None, }); let merchant_defined_information = item @@ -1855,6 +2007,11 @@ impl eci_raw: None, authentication_date: None, effective_authentication_type: None, + challenge_code: None, + pares_status_reason: None, + challenge_cancel_code: None, + network_score: None, + acs_transaction_id: None, }), merchant_defined_information, }) @@ -2000,6 +2157,11 @@ impl eci_raw: None, authentication_date: None, effective_authentication_type: None, + challenge_code: None, + pares_status_reason: None, + challenge_cancel_code: None, + network_score: None, + acs_transaction_id: None, }), merchant_defined_information, }) @@ -2202,6 +2364,11 @@ impl TryFrom<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for Cybersour eci_raw: None, authentication_date: None, effective_authentication_type: None, + challenge_code: None, + pares_status_reason: None, + challenge_cancel_code: None, + network_score: None, + acs_transaction_id: None, }, ), }) @@ -2471,6 +2638,7 @@ impl TryFrom<&CybersourceRouterData<&PaymentsCaptureRouterData>> ) .then_some(true); + let cavv_algorithm = Some("2".to_string()); Ok(Self { processing_information: ProcessingInformation { capture_options: Some(CaptureOptions { @@ -2484,6 +2652,7 @@ impl TryFrom<&CybersourceRouterData<&PaymentsCaptureRouterData>> capture: None, commerce_indicator: String::from("internet"), payment_solution: None, + cavv_algorithm, }, order_information: OrderInformationWithBill { amount_details: Amount { @@ -2509,6 +2678,7 @@ impl TryFrom<&CybersourceRouterData<&PaymentsIncrementalAuthorizationRouterData> ) -> Result<Self, Self::Error> { let connector_merchant_config = CybersourceConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?; + let cavv_algorithm = Some("2".to_string()); Ok(Self { processing_information: ProcessingInformation { @@ -2532,6 +2702,7 @@ impl TryFrom<&CybersourceRouterData<&PaymentsIncrementalAuthorizationRouterData> capture: None, capture_options: None, payment_solution: None, + cavv_algorithm, }, order_information: OrderInformationIncrementalAuthorization { amount_details: AdditionalAmount { diff --git a/crates/hyperswitch_connectors/src/connectors/gpayments.rs b/crates/hyperswitch_connectors/src/connectors/gpayments.rs index 946879d8b72..945852cf7a1 100644 --- a/crates/hyperswitch_connectors/src/connectors/gpayments.rs +++ b/crates/hyperswitch_connectors/src/connectors/gpayments.rs @@ -394,6 +394,8 @@ impl trans_status: response.trans_status.into(), authentication_value: response.authentication_value, eci: response.eci, + challenge_cancel: None, + challenge_code_reason: None, }), ..data.clone() }) diff --git a/crates/hyperswitch_connectors/src/connectors/gpayments/transformers.rs b/crates/hyperswitch_connectors/src/connectors/gpayments/transformers.rs index b35679bd998..11f58d278a4 100644 --- a/crates/hyperswitch_connectors/src/connectors/gpayments/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/gpayments/transformers.rs @@ -295,6 +295,10 @@ impl ds_trans_id: Some(response_auth.ds_trans_id), connector_metadata: None, eci: None, + challenge_code: None, + challenge_cancel: None, + challenge_code_reason: None, + message_extension: None, }); Ok(Self { response, diff --git a/crates/hyperswitch_connectors/src/connectors/netcetera.rs b/crates/hyperswitch_connectors/src/connectors/netcetera.rs index 36fa194ca1b..a2745dc4b08 100644 --- a/crates/hyperswitch_connectors/src/connectors/netcetera.rs +++ b/crates/hyperswitch_connectors/src/connectors/netcetera.rs @@ -220,6 +220,8 @@ impl IncomingWebhook for Netcetera { .unwrap_or(common_enums::TransactionStatus::InformationOnly), authentication_value: webhook_body.authentication_value, eci: webhook_body.eci, + challenge_cancel: webhook_body.challenge_cancel, + challenge_code_reason: webhook_body.trans_status_reason, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs b/crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs index 7cd34ec9371..c0691c5ffdf 100644 --- a/crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs +++ b/crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs @@ -1713,15 +1713,6 @@ pub struct SplitSdkType { limited_ind: Option<String>, } -#[derive(Serialize, Deserialize, Debug, Clone)] -#[serde(rename_all = "camelCase")] -pub struct MessageExtensionAttribute { - id: String, - name: String, - criticality_indicator: bool, - data: String, -} - #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ThreeDSReqAuthMethod { /// No 3DS Requestor authentication occurred (i.e. cardholder "logged in" as guest) diff --git a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs index 37238722b72..fc334d68167 100644 --- a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs @@ -5,7 +5,8 @@ use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, ErrorResponse}, router_flow_types::authentication::{Authentication, PreAuthentication}, router_request_types::authentication::{ - AuthNFlowType, ChallengeParams, ConnectorAuthenticationRequestData, PreAuthNRequestData, + AuthNFlowType, ChallengeParams, ConnectorAuthenticationRequestData, + MessageExtensionAttribute, PreAuthNRequestData, }, router_response_types::AuthenticationResponseData, }; @@ -164,6 +165,21 @@ impl connector_metadata: None, ds_trans_id: response.authentication_response.ds_trans_id, eci: response.eci, + challenge_code: response.three_ds_requestor_challenge_ind, + challenge_cancel: response.challenge_cancel, + challenge_code_reason: response.trans_status_reason, + message_extension: response.message_extension.and_then(|v| { + match serde_json::to_value(&v) { + Ok(val) => Some(Secret::new(val)), + Err(e) => { + router_env::logger::error!( + "Failed to serialize message_extension: {:?}", + e + ); + None + } + } + }), }) } NetceteraAuthenticationResponse::Error(error_response) => Err(ErrorResponse { @@ -432,8 +448,8 @@ pub struct NetceteraAuthenticationRequest { pub merchant: Option<netcetera_types::MerchantData>, pub broad_info: Option<String>, pub device_render_options: Option<netcetera_types::DeviceRenderingOptionsSupported>, - pub message_extension: Option<Vec<netcetera_types::MessageExtensionAttribute>>, - pub challenge_message_extension: Option<Vec<netcetera_types::MessageExtensionAttribute>>, + pub message_extension: Option<Vec<MessageExtensionAttribute>>, + pub challenge_message_extension: Option<Vec<MessageExtensionAttribute>>, pub browser_information: Option<netcetera_types::Browser>, #[serde(rename = "threeRIInd")] pub three_ri_ind: Option<String>, @@ -640,6 +656,11 @@ pub struct NetceteraAuthenticationSuccessResponse { pub authentication_response: AuthenticationResponse, #[serde(rename = "base64EncodedChallengeRequest")] pub encoded_challenge_request: Option<String>, + pub challenge_cancel: Option<String>, + pub trans_status_reason: Option<String>, + #[serde(rename = "threeDSRequestorChallengeInd")] + pub three_ds_requestor_challenge_ind: Option<String>, + pub message_extension: Option<Vec<MessageExtensionAttribute>>, } #[derive(Debug, Deserialize, Serialize)] @@ -708,4 +729,6 @@ pub struct ResultsResponseData { /// Optional object containing error details if any errors occurred during the process. pub error_details: Option<NetceteraErrorDetails>, + pub challenge_cancel: Option<String>, + pub trans_status_reason: Option<String>, } diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index b68ecb83f30..31833475db3 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -20,7 +20,8 @@ use hyperswitch_domain_models::{ Authorize, Capture, CompleteAuthorize, PSync, Void, }, router_request_types::{ - BrowserInformation, PaymentsAuthorizeData, PaymentsPreProcessingData, ResponseId, + authentication::MessageExtensionAttribute, BrowserInformation, PaymentsAuthorizeData, + PaymentsPreProcessingData, ResponseId, }, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, @@ -501,26 +502,10 @@ pub struct NuveiACSResponse { pub message_type: String, pub message_version: String, pub trans_status: Option<LiabilityShift>, - pub message_extension: Vec<MessageExtension>, + pub message_extension: Vec<MessageExtensionAttribute>, pub acs_signed_content: Option<serde_json::Value>, } -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct MessageExtension { - pub name: String, - pub id: String, - pub criticality_indicator: bool, - pub data: MessageExtensionData, -} - -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct MessageExtensionData { - pub value_one: String, - pub value_two: String, -} - #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum LiabilityShift { #[serde(rename = "Y", alias = "1")] diff --git a/crates/hyperswitch_connectors/src/connectors/threedsecureio.rs b/crates/hyperswitch_connectors/src/connectors/threedsecureio.rs index 7f98cf9d958..014681b7759 100644 --- a/crates/hyperswitch_connectors/src/connectors/threedsecureio.rs +++ b/crates/hyperswitch_connectors/src/connectors/threedsecureio.rs @@ -486,6 +486,8 @@ impl trans_status: response.trans_status.into(), authentication_value: response.authentication_value, eci: response.eci, + challenge_cancel: None, + challenge_code_reason: None, }), ..data.clone() }) diff --git a/crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs b/crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs index 82387266ed3..de34d423803 100644 --- a/crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs @@ -184,6 +184,10 @@ impl connector_metadata: None, ds_trans_id: Some(response.ds_trans_id), eci: None, + challenge_code: None, + challenge_cancel: None, + challenge_code_reason: None, + message_extension: None, }) } ThreedsecureioAuthenticationResponse::Error(err_response) => match *err_response { diff --git a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs index 3837daae67b..2a795422519 100644 --- a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs @@ -485,6 +485,8 @@ impl<F, T> ds_trans_id: dynamic_data.ds_trans_id, }), trans_status: item.response.authentication_details.trans_status, + challenge_cancel: None, + challenge_code_reason: None, }, }), ..item.data @@ -822,6 +824,10 @@ pub struct ThreeDsAuthDetails { pub acs_signed_content: Option<String>, pub authentication_value: Option<Secret<String>>, pub eci: Option<String>, + pub challenge_code: Option<String>, + pub challenge_cancel: Option<String>, + pub challenge_code_reason: Option<String>, + pub message_extension: Option<common_utils::pii::SecretSerdeValue>, } #[derive(Debug, Serialize, Clone, Copy, Deserialize)] @@ -990,6 +996,10 @@ impl<F, T> connector_metadata: None, ds_trans_id: Some(auth_response.three_ds_auth_response.ds_trans_id), eci: auth_response.three_ds_auth_response.eci, + challenge_code: auth_response.three_ds_auth_response.challenge_code, + challenge_cancel: auth_response.three_ds_auth_response.challenge_cancel, + challenge_code_reason: auth_response.three_ds_auth_response.challenge_code_reason, + message_extension: auth_response.three_ds_auth_response.message_extension, }, }) } diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index 9aca1f867f9..058f3bfce3b 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -712,6 +712,11 @@ pub struct AuthenticationData { pub message_version: Option<common_utils::types::SemanticVersion>, pub ds_trans_id: Option<String>, pub created_at: time::PrimitiveDateTime, + pub challenge_code: Option<String>, + pub challenge_cancel: Option<String>, + pub challenge_code_reason: Option<String>, + pub message_extension: Option<pii::SecretSerdeValue>, + pub acs_trans_id: Option<String>, pub authentication_type: Option<common_enums::DecoupledAuthenticationType>, } diff --git a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs index 31b0e1a46ae..a26d0c7689f 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs @@ -69,6 +69,15 @@ impl AuthNFlowType { } } +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct MessageExtensionAttribute { + pub id: String, + pub name: String, + pub criticality_indicator: bool, + pub data: String, +} + #[derive(Clone, Default, Debug)] pub struct PreAuthNRequestData { // card data diff --git a/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs b/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs index f37af7fa6d3..4edcdb7962f 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs @@ -128,6 +128,10 @@ pub struct AuthenticationDetails { pub connector_metadata: Option<serde_json::Value>, pub ds_trans_id: Option<String>, pub eci: Option<String>, + pub challenge_code: Option<String>, + pub challenge_cancel: Option<String>, + pub challenge_code_reason: Option<String>, + pub message_extension: Option<common_utils::pii::SecretSerdeValue>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] @@ -136,6 +140,8 @@ pub struct PostAuthenticationDetails { pub token_details: Option<TokenDetails>, pub dynamic_data_details: Option<DynamicData>, pub trans_status: Option<common_enums::TransactionStatus>, + pub challenge_cancel: Option<String>, + pub challenge_code_reason: Option<String>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs index dc9d11b0323..b5181dee31e 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types.rs @@ -3,7 +3,7 @@ pub mod fraud_check; pub mod revenue_recovery; use std::collections::HashMap; -use common_utils::{request::Method, types::MinorUnit}; +use common_utils::{pii, request::Method, types::MinorUnit}; pub use disputes::{AcceptDisputeResponse, DefendDisputeResponse, SubmitEvidenceResponse}; use crate::{ @@ -91,7 +91,7 @@ pub struct TaxCalculationResponseData { pub struct MandateReference { pub connector_mandate_id: Option<String>, pub payment_method_id: Option<String>, - pub mandate_metadata: Option<common_utils::pii::SecretSerdeValue>, + pub mandate_metadata: Option<pii::SecretSerdeValue>, pub connector_mandate_request_reference_id: Option<String>, } @@ -546,18 +546,24 @@ pub enum AuthenticationResponseData { connector_metadata: Option<serde_json::Value>, ds_trans_id: Option<String>, eci: Option<String>, + challenge_code: Option<String>, + challenge_cancel: Option<String>, + challenge_code_reason: Option<String>, + message_extension: Option<pii::SecretSerdeValue>, }, PostAuthNResponse { trans_status: common_enums::TransactionStatus, authentication_value: Option<masking::Secret<String>>, eci: Option<String>, + challenge_cancel: Option<String>, + challenge_code_reason: Option<String>, }, } #[derive(Debug, Clone)] pub struct CompleteAuthorizeRedirectResponse { pub params: Option<masking::Secret<String>>, - pub payload: Option<common_utils::pii::SecretSerdeValue>, + pub payload: Option<pii::SecretSerdeValue>, } /// Represents details of a payment method. diff --git a/crates/hyperswitch_interfaces/src/authentication.rs b/crates/hyperswitch_interfaces/src/authentication.rs index 6c2488767b2..cdde955e5ef 100644 --- a/crates/hyperswitch_interfaces/src/authentication.rs +++ b/crates/hyperswitch_interfaces/src/authentication.rs @@ -9,4 +9,8 @@ pub struct ExternalAuthenticationPayload { pub authentication_value: Option<masking::Secret<String>>, /// eci pub eci: Option<String>, + /// Indicates whether the challenge was canceled by the user or system. + pub challenge_cancel: Option<String>, + /// Reason for the challenge code, if applicable. + pub challenge_code_reason: Option<String>, } diff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rs index b6c304168c0..e1f9b02c881 100644 --- a/crates/router/src/core/authentication/utils.rs +++ b/crates/router/src/core/authentication/utils.rs @@ -100,6 +100,10 @@ pub async fn update_trackers<F: Clone, Req>( connector_metadata, ds_trans_id, eci, + challenge_code, + challenge_cancel, + challenge_code_reason, + message_extension, } => { authentication_value .async_map(|auth_val| { @@ -132,12 +136,18 @@ pub async fn update_trackers<F: Clone, Req>( connector_metadata, ds_trans_id, eci, + challenge_code, + challenge_cancel, + challenge_code_reason, + message_extension, } } AuthenticationResponseData::PostAuthNResponse { trans_status, authentication_value, eci, + challenge_cancel, + challenge_code_reason, } => { authentication_value .async_map(|auth_val| { @@ -160,6 +170,8 @@ pub async fn update_trackers<F: Clone, Req>( ), trans_status, eci, + challenge_cancel, + challenge_code_reason, } } AuthenticationResponseData::PreAuthVersionCallResponse { @@ -284,6 +296,10 @@ pub async fn create_new_authentication( browser_info: None, email: None, profile_acquirer_id: None, + challenge_code: None, + challenge_cancel: None, + challenge_code_reason: None, + message_extension: None, }; state .store diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs index 10df4034c92..2abdfdc8ee6 100644 --- a/crates/router/src/core/payments/types.rs +++ b/crates/router/src/core/payments/types.rs @@ -391,6 +391,11 @@ impl message_version, ds_trans_id: authentication.ds_trans_id.clone(), authentication_type: authentication.authentication_type, + challenge_code: authentication.challenge_code.clone(), + challenge_cancel: authentication.challenge_cancel.clone(), + challenge_code_reason: authentication.challenge_code_reason.clone(), + message_extension: authentication.message_extension.clone(), + acs_trans_id: authentication.acs_trans_id.clone(), }) } else { Err(errors::ApiErrorResponse::PaymentAuthenticationFailed { data: None }.into()) diff --git a/crates/router/src/core/unified_authentication_service.rs b/crates/router/src/core/unified_authentication_service.rs index 91d56f4de1c..a7690fc2923 100644 --- a/crates/router/src/core/unified_authentication_service.rs +++ b/crates/router/src/core/unified_authentication_service.rs @@ -609,6 +609,10 @@ pub async fn create_new_authentication( browser_info: None, email: None, profile_acquirer_id, + challenge_code: None, + challenge_cancel: None, + challenge_code_reason: None, + message_extension: None, }; state .store diff --git a/crates/router/src/core/unified_authentication_service/utils.rs b/crates/router/src/core/unified_authentication_service/utils.rs index 954e33f76b5..3f19b82d075 100644 --- a/crates/router/src/core/unified_authentication_service/utils.rs +++ b/crates/router/src/core/unified_authentication_service/utils.rs @@ -235,6 +235,10 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>( connector_metadata: authentication_details.connector_metadata, ds_trans_id: authentication_details.ds_trans_id, eci: authentication_details.eci, + challenge_code: authentication_details.challenge_code, + challenge_cancel: authentication_details.challenge_cancel, + challenge_code_reason: authentication_details.challenge_code_reason, + message_extension: authentication_details.message_extension, }, ) } @@ -271,6 +275,8 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>( ), trans_status, eci: authentication_details.eci, + challenge_cancel: authentication_details.challenge_cancel, + challenge_code_reason: authentication_details.challenge_code_reason, }, ) } diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index cc1dc7bc506..71d13813310 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -1400,6 +1400,8 @@ async fn external_authentication_incoming_webhook_flow( ), trans_status, eci: authentication_details.eci, + challenge_cancel: authentication_details.challenge_cancel, + challenge_code_reason: authentication_details.challenge_code_reason, }; let authentication = if let webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) = diff --git a/crates/router/src/db/authentication.rs b/crates/router/src/db/authentication.rs index cc892cc513a..74600d4284e 100644 --- a/crates/router/src/db/authentication.rs +++ b/crates/router/src/db/authentication.rs @@ -168,6 +168,10 @@ impl AuthenticationInterface for MockDb { browser_info: authentication.browser_info, email: authentication.email, profile_acquirer_id: authentication.profile_acquirer_id, + challenge_code: authentication.challenge_code, + challenge_cancel: authentication.challenge_cancel, + challenge_code_reason: authentication.challenge_code_reason, + message_extension: authentication.message_extension, }; authentications.push(authentication.clone()); Ok(authentication) diff --git a/migrations/2025-07-25-115018_add_authn_fields_challenge_code_cancel_reason_message_extension/down.sql b/migrations/2025-07-25-115018_add_authn_fields_challenge_code_cancel_reason_message_extension/down.sql new file mode 100644 index 00000000000..a0c12177640 --- /dev/null +++ b/migrations/2025-07-25-115018_add_authn_fields_challenge_code_cancel_reason_message_extension/down.sql @@ -0,0 +1,5 @@ +ALTER TABLE authentication + DROP COLUMN IF EXISTS challenge_code, + DROP COLUMN IF EXISTS challenge_cancel, + DROP COLUMN IF EXISTS challenge_code_reason, + DROP COLUMN IF EXISTS message_extension; \ No newline at end of file diff --git a/migrations/2025-07-25-115018_add_authn_fields_challenge_code_cancel_reason_message_extension/up.sql b/migrations/2025-07-25-115018_add_authn_fields_challenge_code_cancel_reason_message_extension/up.sql new file mode 100644 index 00000000000..beed7efa399 --- /dev/null +++ b/migrations/2025-07-25-115018_add_authn_fields_challenge_code_cancel_reason_message_extension/up.sql @@ -0,0 +1,5 @@ +ALTER TABLE authentication + ADD COLUMN challenge_code VARCHAR NULL, + ADD COLUMN challenge_cancel VARCHAR NULL, + ADD COLUMN challenge_code_reason VARCHAR NULL, + ADD COLUMN message_extension JSONB NULL;
2025-07-25T07:36:19Z
## 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 introduces the following changes 1. Added additional authentication fields for 3ds external authentication, the fields are as following - challenge_code - challenge_code_reason - challenge_cancel - message_extension 2. Added additional fields for Cybersource payments request corresponding to the newly added auth fields 3. Added additional request fields for Netcetera, and other 3ds connectors corresponding to the newly added auth fields Context - Cybersource payments via Netcetera are failing for a France based acquirer in prod, the above fields are added to fix the same. ### 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` 6. `crates/router/src/configs` 7. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with 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)? --> ### Card used for testing (mastercard with challenge flow) 5306 8899 4283 3340 ### Successful 3DS challenge completion flow _Tested using local hyperswitch sdk and hyperswitch backend_ [Test video](https://drive.google.com/file/d/1rV5mnly1WdvLk8Ff1_r16vAxBqgGJVUJ/view?usp=sharing) Connector Request for Cybersource: <img width="1720" height="321" alt="Screenshot 2025-07-30 at 8 39 57β€―PM" src="https://github.com/user-attachments/assets/3fa4c555-7d11-4482-b232-baa8713af24c" /> > cavvAlgorithm - "02" > paresStatus - "Y" > challengeCode - Null (Please note - This is not supposed to be null, checking with Netcetera team since it's coming as None from Netcetera) Fix merged in [PR](https://github.com/juspay/hyperswitch/pull/8850) > paresStatusReason - Null (Please note - Null is not expected here,checking this with Netcetera team) Fix raised here [PR](https://github.com/juspay/hyperswitch/pull/8907) > challengeCancelCode - Null (Please note - Null is expected here, as challenge is not cancelled) > networkScore - Null (Please note - Null is expected here, as card is not CartesBancaires and also since it is not production environment - messageExtension field is only available on production) > acsTransactionId - "9187c2cb-54f8-4e70-a63b-537046c2b34d" ### 3DS challenge cancel flow _Tested using local hyperswitch sdk and hyperswitch backend_ [Test video](https://drive.google.com/file/d/1jIAtfLotxhZsroT-xYUEttUXapuRn0Sv/view?usp=sharing) Incoming Webhook from Netcetera on cancelling challenge: <img width="1720" height="198" alt="Screenshot 2025-07-30 at 9 23 53β€―PM" src="https://github.com/user-attachments/assets/93b0eacd-676c-4d88-993b-77ef78e3da90" /> ## 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.115.0
f3c0a9bfb05af5c9c826799f0e16e9c9460870f5
f3c0a9bfb05af5c9c826799f0e16e9c9460870f5
juspay/hyperswitch
juspay__hyperswitch-8816
Bug: add support for apple pay pre-decrypted token in the payments confirm call add support pass the decryted apple pay token directly in the confirm call.
diff --git a/Cargo.lock b/Cargo.lock index 3e1101fdbf4..5a77720c94f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1858,6 +1858,7 @@ dependencies = [ name = "common_types" version = "0.1.0" dependencies = [ + "cards", "common_enums", "common_utils", "diesel", diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index cf48cef794c..8f7a072881a 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -7459,6 +7459,38 @@ "$ref": "#/components/schemas/ApplePayAddressParameters" } }, + "ApplePayCryptogramData": { + "type": "object", + "description": "This struct represents the cryptogram data for Apple Pay transactions", + "required": [ + "online_payment_cryptogram", + "eci_indicator" + ], + "properties": { + "online_payment_cryptogram": { + "type": "string", + "description": "The online payment cryptogram", + "example": "A1B2C3D4E5F6G7H8" + }, + "eci_indicator": { + "type": "string", + "description": "The ECI (Electronic Commerce Indicator) value", + "example": "05" + } + } + }, + "ApplePayPaymentData": { + "oneOf": [ + { + "$ref": "#/components/schemas/ApplePayPredecryptData" + }, + { + "type": "string", + "description": "This variant contains the encrypted Apple Pay payment data as a string." + } + ], + "description": "This enum is used to represent the Apple Pay payment data, which can either be encrypted or decrypted." + }, "ApplePayPaymentRequest": { "type": "object", "required": [ @@ -7529,6 +7561,36 @@ "recurring" ] }, + "ApplePayPredecryptData": { + "type": "object", + "description": "This struct represents the decrypted Apple Pay payment data", + "required": [ + "application_primary_account_number", + "application_expiration_month", + "application_expiration_year", + "payment_data" + ], + "properties": { + "application_primary_account_number": { + "type": "string", + "description": "The primary account number", + "example": "4242424242424242" + }, + "application_expiration_month": { + "type": "string", + "description": "The application expiration date (PAN expiry month)", + "example": "12" + }, + "application_expiration_year": { + "type": "string", + "description": "The application expiration date (PAN expiry year)", + "example": "24" + }, + "payment_data": { + "$ref": "#/components/schemas/ApplePayCryptogramData" + } + } + }, "ApplePayRecurringDetails": { "type": "object", "required": [ @@ -7705,8 +7767,7 @@ ], "properties": { "payment_data": { - "type": "string", - "description": "The payment data of Apple pay" + "$ref": "#/components/schemas/ApplePayPaymentData" }, "payment_method": { "$ref": "#/components/schemas/ApplepayPaymentMethod" diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index dc3578ef61c..7c07f5c2eb5 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -4467,6 +4467,38 @@ "$ref": "#/components/schemas/ApplePayAddressParameters" } }, + "ApplePayCryptogramData": { + "type": "object", + "description": "This struct represents the cryptogram data for Apple Pay transactions", + "required": [ + "online_payment_cryptogram", + "eci_indicator" + ], + "properties": { + "online_payment_cryptogram": { + "type": "string", + "description": "The online payment cryptogram", + "example": "A1B2C3D4E5F6G7H8" + }, + "eci_indicator": { + "type": "string", + "description": "The ECI (Electronic Commerce Indicator) value", + "example": "05" + } + } + }, + "ApplePayPaymentData": { + "oneOf": [ + { + "$ref": "#/components/schemas/ApplePayPredecryptData" + }, + { + "type": "string", + "description": "This variant contains the encrypted Apple Pay payment data as a string." + } + ], + "description": "This enum is used to represent the Apple Pay payment data, which can either be encrypted or decrypted." + }, "ApplePayPaymentRequest": { "type": "object", "required": [ @@ -4537,6 +4569,36 @@ "recurring" ] }, + "ApplePayPredecryptData": { + "type": "object", + "description": "This struct represents the decrypted Apple Pay payment data", + "required": [ + "application_primary_account_number", + "application_expiration_month", + "application_expiration_year", + "payment_data" + ], + "properties": { + "application_primary_account_number": { + "type": "string", + "description": "The primary account number", + "example": "4242424242424242" + }, + "application_expiration_month": { + "type": "string", + "description": "The application expiration date (PAN expiry month)", + "example": "12" + }, + "application_expiration_year": { + "type": "string", + "description": "The application expiration date (PAN expiry year)", + "example": "24" + }, + "payment_data": { + "$ref": "#/components/schemas/ApplePayCryptogramData" + } + } + }, "ApplePayRecurringDetails": { "type": "object", "required": [ @@ -4713,8 +4775,7 @@ ], "properties": { "payment_data": { - "type": "string", - "description": "The payment data of Apple pay" + "$ref": "#/components/schemas/ApplePayPaymentData" }, "payment_method": { "$ref": "#/components/schemas/ApplepayPaymentMethod" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 8dab325c157..50d1ffd2ee4 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -612,6 +612,7 @@ credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,K [pm_filters.worldpayvantiv] debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } +apple_pay = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } [pm_filters.zen] boleto = { country = "BR", currency = "BRL" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index cfbf4d8204d..dbc4cc781ea 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -628,6 +628,7 @@ credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,K [pm_filters.worldpayvantiv] debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } +apple_pay = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } [pm_filters.zen] boleto = { country = "BR", currency = "BRL" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index f4344abb808..507115ba490 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -635,6 +635,7 @@ credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,K [pm_filters.worldpayvantiv] debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } +apple_pay = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } [pm_filters.zen] boleto = { country = "BR", currency = "BRL" } diff --git a/config/development.toml b/config/development.toml index b3aa9fcb9a5..a7f6a518b3d 100644 --- a/config/development.toml +++ b/config/development.toml @@ -820,6 +820,7 @@ credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,K [pm_filters.worldpayvantiv] debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } +apple_pay = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } [pm_filters.bluecode] bluecode = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,IS,LI,NO", currency = "EUR" } diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 0c238d18c2a..57fb0d9f122 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -3986,7 +3986,8 @@ pub struct GpayTokenizationData { #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay - pub payment_data: String, + #[schema(value_type = ApplePayPaymentData)] + pub payment_data: common_types::payments::ApplePayPaymentData, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction diff --git a/crates/common_types/Cargo.toml b/crates/common_types/Cargo.toml index e989426be27..61b3ae128ec 100644 --- a/crates/common_types/Cargo.toml +++ b/crates/common_types/Cargo.toml @@ -22,6 +22,7 @@ error-stack = "0.4.1" common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils"} +cards = { version = "0.1.0", path = "../cards"} euclid = { version = "0.1.0", path = "../euclid" } masking = { version = "0.1.0", path = "../masking" } diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rs index 933106f2bf2..d65492953e8 100644 --- a/crates/common_types/src/payments.rs +++ b/crates/common_types/src/payments.rs @@ -3,7 +3,10 @@ use std::collections::HashMap; use common_enums::enums; -use common_utils::{date_time, errors, events, impl_to_sql_from_sql_json, pii, types::MinorUnit}; +use common_utils::{ + date_time, errors, events, ext_traits::OptionExt, impl_to_sql_from_sql_json, pii, + types::MinorUnit, +}; use diesel::{ sql_types::{Jsonb, Text}, AsExpression, FromSqlRow, @@ -13,7 +16,7 @@ use euclid::frontend::{ ast::Program, dir::{DirKeyKind, EuclidDirFilter}, }; -use masking::{PeekInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; @@ -409,3 +412,116 @@ pub struct XenditMultipleSplitResponse { pub routes: Vec<XenditSplitRoute>, } impl_to_sql_from_sql_json!(XenditMultipleSplitResponse); + +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +#[serde(untagged)] +/// This enum is used to represent the Apple Pay payment data, which can either be encrypted or decrypted. +pub enum ApplePayPaymentData { + /// This variant contains the decrypted Apple Pay payment data as a structured object. + Decrypted(ApplePayPredecryptData), + /// This variant contains the encrypted Apple Pay payment data as a string. + Encrypted(String), +} + +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +/// This struct represents the decrypted Apple Pay payment data +pub struct ApplePayPredecryptData { + /// The primary account number + #[schema(value_type = String, example = "4242424242424242")] + pub application_primary_account_number: cards::CardNumber, + /// The application expiration date (PAN expiry month) + #[schema(value_type = String, example = "12")] + pub application_expiration_month: Secret<String>, + /// The application expiration date (PAN expiry year) + #[schema(value_type = String, example = "24")] + pub application_expiration_year: Secret<String>, + /// The payment data, which contains the cryptogram and ECI indicator + #[schema(value_type = ApplePayCryptogramData)] + pub payment_data: ApplePayCryptogramData, +} + +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +/// This struct represents the cryptogram data for Apple Pay transactions +pub struct ApplePayCryptogramData { + /// The online payment cryptogram + #[schema(value_type = String, example = "A1B2C3D4E5F6G7H8")] + pub online_payment_cryptogram: Secret<String>, + /// The ECI (Electronic Commerce Indicator) value + #[schema(value_type = String, example = "05")] + pub eci_indicator: Option<String>, +} + +impl ApplePayPaymentData { + /// Get the encrypted Apple Pay payment data if it exists + pub fn get_encrypted_apple_pay_payment_data_optional(&self) -> Option<&String> { + match self { + Self::Encrypted(encrypted_data) => Some(encrypted_data), + Self::Decrypted(_) => None, + } + } + + /// Get the decrypted Apple Pay payment data if it exists + pub fn get_decrypted_apple_pay_payment_data_optional(&self) -> Option<&ApplePayPredecryptData> { + match self { + Self::Encrypted(_) => None, + Self::Decrypted(decrypted_data) => Some(decrypted_data), + } + } + + /// Get the encrypted Apple Pay payment data, returning an error if it does not exist + pub fn get_encrypted_apple_pay_payment_data_mandatory( + &self, + ) -> Result<&String, errors::ValidationError> { + self.get_encrypted_apple_pay_payment_data_optional() + .get_required_value("Encrypted Apple Pay payment data") + .attach_printable("Encrypted Apple Pay payment data is mandatory") + } + + /// Get the decrypted Apple Pay payment data, returning an error if it does not exist + pub fn get_decrypted_apple_pay_payment_data_mandatory( + &self, + ) -> Result<&ApplePayPredecryptData, errors::ValidationError> { + self.get_decrypted_apple_pay_payment_data_optional() + .get_required_value("Decrypted Apple Pay payment data") + .attach_printable("Decrypted Apple Pay payment data is mandatory") + } +} + +impl ApplePayPredecryptData { + /// Get the four-digit expiration year from the Apple Pay pre-decrypt data + pub fn get_two_digit_expiry_year(&self) -> Result<Secret<String>, errors::ValidationError> { + let binding = self.application_expiration_year.clone(); + let year = binding.peek(); + Ok(Secret::new( + year.get(year.len() - 2..) + .ok_or(errors::ValidationError::InvalidValue { + message: "Invalid two-digit year".to_string(), + })? + .to_string(), + )) + } + + /// Get the four-digit expiration year from the Apple Pay pre-decrypt data + pub fn get_four_digit_expiry_year(&self) -> Secret<String> { + let mut year = self.application_expiration_year.peek().clone(); + if year.len() == 2 { + year = format!("20{year}"); + } + Secret::new(year) + } + + /// Get the expiration month from the Apple Pay pre-decrypt data + pub fn get_expiry_month(&self) -> Secret<String> { + self.application_expiration_month.clone() + } + + /// Get the expiry date in MMYY format from the Apple Pay pre-decrypt data + pub fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ValidationError> { + let year = self.get_two_digit_expiry_year()?.expose(); + let month = self.application_expiration_month.clone().expose(); + Ok(Secret::new(format!("{month}{year}"))) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index 3d04375b106..53ecbf882e6 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -57,10 +57,9 @@ use crate::{ SubmitEvidenceRouterData, }, utils::{ - self, is_manual_capture, missing_field_err, AddressDetailsData, ApplePayDecrypt, - BrowserInformationData, CardData, ForeignTryFrom, - NetworkTokenData as UtilsNetworkTokenData, PaymentsAuthorizeRequestData, PhoneDetailsData, - RouterData as OtherRouterData, + self, is_manual_capture, missing_field_err, AddressDetailsData, BrowserInformationData, + CardData, ForeignTryFrom, NetworkTokenData as UtilsNetworkTokenData, + PaymentsAuthorizeRequestData, PhoneDetailsData, RouterData as OtherRouterData, }, }; @@ -1264,7 +1263,7 @@ pub struct AdyenPazeData { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenApplePayDecryptData { - number: Secret<String>, + number: CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, brand: String, @@ -2216,8 +2215,8 @@ impl TryFrom<(&WalletData, &PaymentsAuthorizeRouterData)> for AdyenPaymentMethod if let Some(PaymentMethodToken::ApplePayDecrypt(apple_pay_decrypte)) = item.payment_method_token.clone() { - let expiry_year_4_digit = apple_pay_decrypte.get_four_digit_expiry_year()?; - let exp_month = apple_pay_decrypte.get_expiry_month()?; + let expiry_year_4_digit = apple_pay_decrypte.get_four_digit_expiry_year(); + let exp_month = apple_pay_decrypte.get_expiry_month(); let apple_pay_decrypted_data = AdyenApplePayDecryptData { number: apple_pay_decrypte.application_primary_account_number, expiry_month: exp_month, @@ -2229,8 +2228,14 @@ impl TryFrom<(&WalletData, &PaymentsAuthorizeRouterData)> for AdyenPaymentMethod apple_pay_decrypted_data, ))) } else { + let apple_pay_encrypted_data = data + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + })?; let apple_pay_data = AdyenApplePay { - apple_pay_token: Secret::new(data.payment_data.to_string()), + apple_pay_token: Secret::new(apple_pay_encrypted_data.to_string()), }; Ok(AdyenPaymentMethod::ApplePay(Box::new(apple_pay_data))) } diff --git a/crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs b/crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs index 1698c9c4a54..53e7cefc6c8 100644 --- a/crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs @@ -29,8 +29,8 @@ use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, unimplemented_payment_method, utils::{ - self, AddressData, AddressDetailsData, ApplePayDecrypt, CardData, CardIssuer, - PaymentsAuthorizeRequestData, RouterData as _, + self, AddressData, AddressDetailsData, CardData, CardIssuer, PaymentsAuthorizeRequestData, + RouterData as _, }, }; @@ -273,8 +273,12 @@ impl TryFrom<(&WalletData, &Option<PaymentMethodToken>)> for TokenizedCardData { .application_primary_account_number .clone(); - let expiry_year_2_digit = apple_pay_decrypt_data.get_two_digit_expiry_year()?; - let expiry_month = apple_pay_decrypt_data.get_expiry_month()?; + let expiry_year_2_digit = apple_pay_decrypt_data + .get_two_digit_expiry_year() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay expiry year", + })?; + let expiry_month = apple_pay_decrypt_data.get_expiry_month(); Ok(Self { card_data: ArchipelTokenizedCard { @@ -302,7 +306,7 @@ impl TryFrom<(&WalletData, &Option<PaymentMethodToken>)> for TokenizedCardData { #[derive(Debug, Serialize, Eq, PartialEq, Clone)] #[serde(rename_all = "camelCase")] pub struct ArchipelTokenizedCard { - number: Secret<String>, + number: cards::CardNumber, expiry: CardExpiryDate, scheme: ArchipelCardScheme, } diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs index 4f8486d1868..ff2b01cdff6 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs @@ -529,6 +529,12 @@ impl TryFrom<&SetupMandateRouterData> for CreateCustomerProfileRequest { } _ => None, }; + let apple_pay_encrypted_data = applepay_token + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + })?; Ok(Self { create_customer_profile_request: AuthorizedotnetZeroMandateRequest { merchant_authentication, @@ -541,9 +547,7 @@ impl TryFrom<&SetupMandateRouterData> for CreateCustomerProfileRequest { customer_type: CustomerType::Individual, payment: PaymentDetails::OpaqueData(WalletDetails { data_descriptor: WalletMethod::Applepay, - data_value: Secret::new( - applepay_token.payment_data.clone(), - ), + data_value: Secret::new(apple_pay_encrypted_data.clone()), }), }, ship_to_list, @@ -2109,10 +2113,18 @@ fn get_wallet_data( data_descriptor: WalletMethod::Googlepay, data_value: Secret::new(wallet_data.get_encoded_wallet_token()?), })), - WalletData::ApplePay(applepay_token) => Ok(PaymentDetails::OpaqueData(WalletDetails { - data_descriptor: WalletMethod::Applepay, - data_value: Secret::new(applepay_token.payment_data.clone()), - })), + WalletData::ApplePay(applepay_token) => { + let apple_pay_encrypted_data = applepay_token + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + })?; + Ok(PaymentDetails::OpaqueData(WalletDetails { + data_descriptor: WalletMethod::Applepay, + data_value: Secret::new(apple_pay_encrypted_data.clone()), + })) + } WalletData::PaypalRedirect(_) => Ok(PaymentDetails::PayPal(PayPalDetails { success_url: return_url.to_owned(), cancel_url: return_url.to_owned(), diff --git a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs index 5f3bcdf9d37..dccd7b6c6b4 100644 --- a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs @@ -1,5 +1,6 @@ use base64::Engine; use common_enums::{enums, FutureUsage}; +use common_types::payments::ApplePayPredecryptData; use common_utils::{consts, ext_traits::OptionExt, pii}; use hyperswitch_domain_models::{ payment_method_data::{ @@ -7,8 +8,8 @@ use hyperswitch_domain_models::{ WalletData, }, router_data::{ - AdditionalPaymentMethodConnectorResponse, ApplePayPredecryptData, ConnectorAuthType, - ConnectorResponseData, ErrorResponse, PaymentMethodToken, RouterData, + AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, + ErrorResponse, PaymentMethodToken, RouterData, }, router_flow_types::refunds::{Execute, RSync}, router_request_types::{ @@ -31,7 +32,7 @@ use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, unimplemented_payment_method, utils::{ - self, AddressDetailsData, ApplePayDecrypt, CardData, PaymentsAuthorizeRequestData, + self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RecurringMandateData, RouterData as OtherRouterData, }, @@ -247,7 +248,7 @@ pub struct Card { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCard { - number: Secret<String>, + number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, cryptogram: Secret<String>, @@ -1045,7 +1046,7 @@ impl TryFrom<&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>> let client_reference_information = ClientReferenceInformation::from(item); let payment_information = - PaymentInformation::from(&apple_pay_data); + PaymentInformation::try_from(&apple_pay_data)?; let merchant_defined_information = item .router_data .request @@ -2478,7 +2479,7 @@ impl TryFrom<(&SetupMandateRouterData, ApplePayWalletData)> for BankOfAmericaPay "Bank Of America" ))?, }, - None => PaymentInformation::from(&apple_pay_data), + None => PaymentInformation::try_from(&apple_pay_data)?, }; let processing_information = ProcessingInformation::try_from(( Some(PaymentSolution::ApplePay), @@ -2604,8 +2605,8 @@ impl TryFrom<&Box<ApplePayPredecryptData>> for PaymentInformation { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(apple_pay_data: &Box<ApplePayPredecryptData>) -> Result<Self, Self::Error> { - let expiration_month = apple_pay_data.get_expiry_month()?; - let expiration_year = apple_pay_data.get_four_digit_expiry_year()?; + let expiration_month = apple_pay_data.get_expiry_month(); + let expiration_year = apple_pay_data.get_four_digit_expiry_year(); Ok(Self::ApplePay(Box::new(ApplePayPaymentInformation { tokenized_card: TokenizedCard { @@ -2622,17 +2623,28 @@ impl TryFrom<&Box<ApplePayPredecryptData>> for PaymentInformation { } } -impl From<&ApplePayWalletData> for PaymentInformation { - fn from(apple_pay_data: &ApplePayWalletData) -> Self { - Self::ApplePayToken(Box::new(ApplePayTokenPaymentInformation { - fluid_data: FluidData { - value: Secret::from(apple_pay_data.payment_data.clone()), - descriptor: None, - }, - tokenized_card: ApplePayTokenizedCard { - transaction_type: TransactionType::ApplePay, +impl TryFrom<&ApplePayWalletData> for PaymentInformation { + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from(apple_pay_data: &ApplePayWalletData) -> Result<Self, Self::Error> { + let apple_pay_encrypted_data = apple_pay_data + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + })?; + + Ok(Self::ApplePayToken(Box::new( + ApplePayTokenPaymentInformation { + fluid_data: FluidData { + value: Secret::from(apple_pay_encrypted_data.clone()), + descriptor: None, + }, + tokenized_card: ApplePayTokenizedCard { + transaction_type: TransactionType::ApplePay, + }, }, - })) + ))) } } diff --git a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs index ee735f0b878..563eaef3d57 100644 --- a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs @@ -31,7 +31,7 @@ use crate::{ }, unimplemented_payment_method, utils::{ - self, ApplePayDecrypt, PaymentsCaptureRequestData, RouterData as OtherRouterData, + self, PaymentsCaptureRequestData, RouterData as OtherRouterData, WalletData as OtherWalletData, }, }; @@ -215,7 +215,7 @@ pub enum PaymentSource { #[derive(Debug, Serialize)] pub struct ApplePayPredecrypt { - token: Secret<String>, + token: cards::CardNumber, #[serde(rename = "type")] decrypt_type: String, token_type: String, @@ -341,8 +341,8 @@ impl TryFrom<&CheckoutRouterData<&PaymentsAuthorizeRouterData>> for PaymentsRequ })) } PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { - let exp_month = decrypt_data.get_expiry_month()?; - let expiry_year_4_digit = decrypt_data.get_four_digit_expiry_year()?; + let exp_month = decrypt_data.get_expiry_month(); + let expiry_year_4_digit = decrypt_data.get_four_digit_expiry_year(); Ok(PaymentSource::ApplePayPredecrypt(Box::new( ApplePayPredecrypt { token: decrypt_data.application_primary_account_number, diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index 27ac86fe7fc..292bd75b6f1 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -3,6 +3,7 @@ use api_models::payments; use api_models::payouts::PayoutMethodData; use base64::Engine; use common_enums::{enums, FutureUsage}; +use common_types::payments::ApplePayPredecryptData; use common_utils::{ consts, date_time, ext_traits::{OptionExt, ValueExt}, @@ -24,9 +25,8 @@ use hyperswitch_domain_models::{ SamsungPayWalletData, WalletData, }, router_data::{ - AdditionalPaymentMethodConnectorResponse, ApplePayPredecryptData, ConnectorAuthType, - ConnectorResponseData, ErrorResponse, GooglePayDecryptedData, PaymentMethodToken, - RouterData, + AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, + ErrorResponse, GooglePayDecryptedData, PaymentMethodToken, RouterData, }, router_flow_types::{ payments::Authorize, @@ -61,7 +61,7 @@ use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, unimplemented_payment_method, utils::{ - self, AddressDetailsData, ApplePayDecrypt, CardData, CardIssuer, NetworkTokenData as _, + self, AddressDetailsData, CardData, CardIssuer, NetworkTokenData as _, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RecurringMandateData, RouterData as OtherRouterData, @@ -194,8 +194,8 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest { WalletData::ApplePay(apple_pay_data) => match item.payment_method_token.clone() { Some(payment_method_token) => match payment_method_token { PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { - let expiration_month = decrypt_data.get_expiry_month()?; - let expiration_year = decrypt_data.get_four_digit_expiry_year()?; + let expiration_month = decrypt_data.get_expiry_month(); + let expiration_year = decrypt_data.get_four_digit_expiry_year(); ( PaymentInformation::ApplePay(Box::new( ApplePayPaymentInformation { @@ -225,20 +225,28 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest { Err(unimplemented_payment_method!("Google Pay", "Cybersource"))? } }, - None => ( - PaymentInformation::ApplePayToken(Box::new( - ApplePayTokenPaymentInformation { - fluid_data: FluidData { - value: Secret::from(apple_pay_data.payment_data), - descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()), - }, - tokenized_card: ApplePayTokenizedCard { - transaction_type: TransactionType::InApp, + None => { + let apple_pay_encrypted_data = apple_pay_data + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + })?; + ( + PaymentInformation::ApplePayToken(Box::new( + ApplePayTokenPaymentInformation { + fluid_data: FluidData { + value: Secret::from(apple_pay_encrypted_data.clone()), + descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()), + }, + tokenized_card: ApplePayTokenizedCard { + transaction_type: TransactionType::InApp, + }, }, - }, - )), - Some(PaymentSolution::ApplePay), - ), + )), + Some(PaymentSolution::ApplePay), + ) + } }, WalletData::GooglePay(google_pay_data) => ( PaymentInformation::GooglePayToken(Box::new( @@ -492,7 +500,7 @@ pub struct CardPaymentInformation { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCard { - number: Secret<String>, + number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, cryptogram: Option<Secret<String>>, @@ -1811,8 +1819,8 @@ impl Some(apple_pay_wallet_data.payment_method.network.clone()), ))?; let client_reference_information = ClientReferenceInformation::from(item); - let expiration_month = apple_pay_data.get_expiry_month()?; - let expiration_year = apple_pay_data.get_four_digit_expiry_year()?; + let expiration_month = apple_pay_data.get_expiry_month(); + let expiration_year = apple_pay_data.get_four_digit_expiry_year(); let payment_information = PaymentInformation::ApplePay(Box::new(ApplePayPaymentInformation { tokenized_card: TokenizedCard { @@ -1942,12 +1950,7 @@ impl let payment_information = PaymentInformation::GooglePay(Box::new(GooglePayPaymentInformation { tokenized_card: TokenizedCard { - number: Secret::new( - google_pay_decrypted_data - .payment_method_details - .pan - .get_card_no(), - ), + number: google_pay_decrypted_data.payment_method_details.pan, cryptogram: google_pay_decrypted_data.payment_method_details.cryptogram, transaction_type, expiration_year: Secret::new( @@ -2159,10 +2162,21 @@ impl TryFrom<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for Cybersour ))?; let client_reference_information = ClientReferenceInformation::from(item); + + let apple_pay_encrypted_data = apple_pay_data + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context( + errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + }, + )?; let payment_information = PaymentInformation::ApplePayToken( Box::new(ApplePayTokenPaymentInformation { fluid_data: FluidData { - value: Secret::from(apple_pay_data.payment_data), + value: Secret::from( + apple_pay_encrypted_data.clone(), + ), descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()), }, tokenized_card: ApplePayTokenizedCard { diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index 5672740c559..f83f8004d15 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -3,6 +3,7 @@ use std::collections::HashMap; use api_models::payments; use cards::CardNumber; use common_enums::{enums, BankNames, CaptureMethod, Currency}; +use common_types::payments::ApplePayPredecryptData; use common_utils::{ crypto::{self, GenerateDigest}, errors::CustomResult, @@ -17,9 +18,7 @@ use hyperswitch_domain_models::{ BankRedirectData, Card, CardDetailsForNetworkTransactionId, GooglePayWalletData, PaymentMethodData, RealTimePaymentData, WalletData, }, - router_data::{ - ApplePayPredecryptData, ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData, - }, + router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{PaymentsAuthorizeData, ResponseId}, router_response_types::{ @@ -47,10 +46,7 @@ use crate::{ PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData, }, unimplemented_payment_method, - utils::{ - self, ApplePayDecrypt, PaymentsAuthorizeRequestData, QrImage, RefundsRequestData, - RouterData as _, - }, + utils::{self, PaymentsAuthorizeRequestData, QrImage, RefundsRequestData, RouterData as _}, }; pub struct FiuuRouterData<T> { @@ -397,7 +393,7 @@ pub struct FiuuApplePayData { txn_channel: TxnChannel, cc_month: Secret<String>, cc_year: Secret<String>, - cc_token: Secret<String>, + cc_token: CardNumber, eci: Option<String>, token_cryptogram: Secret<String>, token_type: FiuuTokenType, @@ -727,8 +723,8 @@ impl TryFrom<Box<ApplePayPredecryptData>> for FiuuPaymentMethodData { fn try_from(decrypt_data: Box<ApplePayPredecryptData>) -> Result<Self, Self::Error> { Ok(Self::FiuuApplePayData(Box::new(FiuuApplePayData { txn_channel: TxnChannel::Creditan, - cc_month: decrypt_data.get_expiry_month()?, - cc_year: decrypt_data.get_four_digit_expiry_year()?, + cc_month: decrypt_data.get_expiry_month(), + cc_year: decrypt_data.get_four_digit_expiry_year(), cc_token: decrypt_data.application_primary_account_number, eci: decrypt_data.payment_data.eci_indicator, token_cryptogram: decrypt_data.payment_data.online_payment_cryptogram, diff --git a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs index c449ee05122..5390767d6ca 100644 --- a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs @@ -1,6 +1,7 @@ use cards::CardNumber; use common_enums::enums; use common_utils::{pii::Email, request::Method, types::StringMajorUnit}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{BankDebitData, BankRedirectData, PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, PaymentMethodToken, RouterData}, @@ -329,11 +330,19 @@ fn get_payment_method_for_wallet( shipping_address: get_shipping_details(item)?, }, ))), - WalletData::ApplePay(applepay_wallet_data) => Ok(MolliePaymentMethodData::Applepay( - Box::new(ApplePayMethodData { - apple_pay_payment_token: Secret::new(applepay_wallet_data.payment_data.to_owned()), - }), - )), + WalletData::ApplePay(applepay_wallet_data) => { + let apple_pay_encrypted_data = applepay_wallet_data + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + })?; + Ok(MolliePaymentMethodData::Applepay(Box::new( + ApplePayMethodData { + apple_pay_payment_token: Secret::new(apple_pay_encrypted_data.to_owned()), + }, + ))) + } _ => Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()), } } diff --git a/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs index ec5ce3b2e65..b6eda16611d 100644 --- a/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs @@ -541,7 +541,7 @@ impl TryFrom<(&PaymentMethodData, Option<&PaymentsAuthorizeRouterData>)> for Pay }, PaymentMethodData::Wallet(ref wallet_type) => match wallet_type { WalletData::GooglePay(ref googlepay_data) => Ok(Self::from(googlepay_data)), - WalletData::ApplePay(ref applepay_data) => Ok(Self::from(applepay_data)), + WalletData::ApplePay(ref applepay_data) => Ok(Self::try_from(applepay_data)?), WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) @@ -653,12 +653,20 @@ impl From<&GooglePayWalletData> for PaymentMethod { } } -impl From<&ApplePayWalletData> for PaymentMethod { - fn from(wallet_data: &ApplePayWalletData) -> Self { +impl TryFrom<&ApplePayWalletData> for PaymentMethod { + type Error = Error; + fn try_from(apple_pay_wallet_data: &ApplePayWalletData) -> Result<Self, Self::Error> { + let apple_pay_encrypted_data = apple_pay_wallet_data + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context(ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + })?; + let apple_pay_data = ApplePayData { - applepay_payment_data: Secret::new(wallet_data.payment_data.clone()), + applepay_payment_data: Secret::new(apple_pay_encrypted_data.clone()), }; - Self::ApplePay(Box::new(apple_pay_data)) + Ok(Self::ApplePay(Box::new(apple_pay_data))) } } diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index 010109a06ab..3a5205763d4 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -612,21 +612,28 @@ impl TryFrom<GooglePayWalletData> for NuveiPaymentsRequest { }) } } -impl From<ApplePayWalletData> for NuveiPaymentsRequest { - fn from(apple_pay_data: ApplePayWalletData) -> Self { - Self { +impl TryFrom<ApplePayWalletData> for NuveiPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(apple_pay_data: ApplePayWalletData) -> Result<Self, Self::Error> { + let apple_pay_encrypted_data = apple_pay_data + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + })?; + Ok(Self { payment_option: PaymentOption { card: Some(Card { external_token: Some(ExternalToken { external_token_provider: ExternalTokenProvider::ApplePay, - mobile_token: Secret::new(apple_pay_data.payment_data), + mobile_token: Secret::new(apple_pay_encrypted_data.clone()), }), ..Default::default() }), ..Default::default() }, ..Default::default() - } + }) } } @@ -917,7 +924,7 @@ where PaymentMethodData::MandatePayment => Self::try_from(item), PaymentMethodData::Wallet(wallet) => match wallet { WalletData::GooglePay(gpay_data) => Self::try_from(gpay_data), - WalletData::ApplePay(apple_pay_data) => Ok(Self::from(apple_pay_data)), + WalletData::ApplePay(apple_pay_data) => Ok(Self::try_from(apple_pay_data)?), WalletData::PaypalRedirect(_) => Self::foreign_try_from(( AlternativePaymentMethodType::Expresscheckout, None, diff --git a/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs index 45b693ea00e..13014b55482 100644 --- a/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs @@ -121,15 +121,25 @@ impl TryFrom<&PayuRouterData<&types::PaymentsAuthorizeRouterData>> for PayuPayme } }), }), - WalletData::ApplePay(data) => Ok(PayuPaymentMethod { - pay_method: PayuPaymentMethodData::Wallet({ - PayuWallet { - value: PayuWalletCode::Jp, - wallet_type: WALLET_IDENTIFIER.to_string(), - authorization_code: Secret::new(data.payment_data), - } - }), - }), + WalletData::ApplePay(apple_pay_data) => { + let apple_pay_encrypted_data = apple_pay_data + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + })?; + Ok(PayuPaymentMethod { + pay_method: PayuPaymentMethodData::Wallet({ + PayuWallet { + value: PayuWalletCode::Jp, + wallet_type: WALLET_IDENTIFIER.to_string(), + authorization_code: Secret::new( + apple_pay_encrypted_data.to_string(), + ), + } + }), + }) + } _ => Err(errors::ConnectorError::NotImplemented( "Unknown Wallet in Payment Method".to_string(), )), diff --git a/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs b/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs index fb77ffe541c..496dac42f48 100644 --- a/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs @@ -147,10 +147,18 @@ impl TryFrom<&RapydRouterData<&types::PaymentsAuthorizeRouterData>> for RapydPay payment_type: "google_pay".to_string(), token: Some(Secret::new(data.tokenization_data.token.to_owned())), }), - WalletData::ApplePay(data) => Some(RapydWallet { - payment_type: "apple_pay".to_string(), - token: Some(Secret::new(data.payment_data.to_string())), - }), + WalletData::ApplePay(data) => { + let apple_pay_encrypted_data = data + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + })?; + Some(RapydWallet { + payment_type: "apple_pay".to_string(), + token: Some(Secret::new(apple_pay_encrypted_data.to_string())), + }) + } _ => None, }; Some(PaymentMethod { diff --git a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs index 3cd7aa033d7..164f8857afb 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs @@ -45,7 +45,7 @@ use url::Url; use crate::{ constants::headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT, - utils::{convert_uppercase, ApplePay, ApplePayDecrypt, RouterData as OtherRouterData}, + utils::{convert_uppercase, ApplePay, RouterData as OtherRouterData}, }; #[cfg(feature = "payouts")] pub mod connect; @@ -590,7 +590,7 @@ pub enum StripeWallet { #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeApplePayPredecrypt { #[serde(rename = "card[number]")] - number: Secret<String>, + number: cards::CardNumber, #[serde(rename = "card[exp_year]")] exp_year: Secret<String>, #[serde(rename = "card[exp_month]")] @@ -1481,14 +1481,12 @@ impl TryFrom<(&WalletData, Option<PaymentMethodToken>)> for StripePaymentMethodD if let Some(PaymentMethodToken::ApplePayDecrypt(decrypt_data)) = payment_method_token { - let expiry_year_4_digit = decrypt_data.get_four_digit_expiry_year()?; - let exp_month = decrypt_data.get_expiry_month()?; - + let expiry_year_4_digit = decrypt_data.get_four_digit_expiry_year(); Some(Self::Wallet(StripeWallet::ApplePayPredecryptToken( Box::new(StripeApplePayPredecrypt { number: decrypt_data.clone().application_primary_account_number, exp_year: expiry_year_4_digit, - exp_month, + exp_month: decrypt_data.application_expiration_month, eci: decrypt_data.payment_data.eci_indicator, cryptogram: decrypt_data.payment_data.online_payment_cryptogram, tokenization_method: "apple_pay".to_string(), diff --git a/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs b/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs index 413551a9fdf..8e79d668dd2 100644 --- a/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs @@ -1,17 +1,19 @@ use api_models::payments; use base64::Engine; use common_enums::{enums, FutureUsage}; +use common_types::payments::ApplePayPredecryptData; use common_utils::{ consts, pii, types::{SemanticVersion, StringMajorUnit}, }; +use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{ ApplePayWalletData, BankDebitData, GooglePayWalletData, PaymentMethodData, WalletData, }, router_data::{ - AdditionalPaymentMethodConnectorResponse, ApplePayPredecryptData, ConnectorAuthType, - ConnectorResponseData, ErrorResponse, PaymentMethodToken, RouterData, + AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, + ErrorResponse, PaymentMethodToken, RouterData, }, router_flow_types::{ payments::Authorize, @@ -38,7 +40,7 @@ use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, unimplemented_payment_method, utils::{ - self, AddressDetailsData, ApplePayDecrypt, CardData, PaymentsAuthorizeRequestData, + self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RecurringMandateData, RouterData as OtherRouterData, }, @@ -126,8 +128,8 @@ impl TryFrom<&SetupMandateRouterData> for WellsfargoZeroMandateRequest { WalletData::ApplePay(apple_pay_data) => match item.payment_method_token.clone() { Some(payment_method_token) => match payment_method_token { PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { - let expiration_month = decrypt_data.get_expiry_month()?; - let expiration_year = decrypt_data.get_four_digit_expiry_year()?; + let expiration_month = decrypt_data.get_expiry_month(); + let expiration_year = decrypt_data.get_four_digit_expiry_year(); ( PaymentInformation::ApplePay(Box::new( ApplePayPaymentInformation { @@ -157,20 +159,28 @@ impl TryFrom<&SetupMandateRouterData> for WellsfargoZeroMandateRequest { Err(unimplemented_payment_method!("Google Pay", "Wellsfargo"))? } }, - None => ( - PaymentInformation::ApplePayToken(Box::new( - ApplePayTokenPaymentInformation { - fluid_data: FluidData { - value: Secret::from(apple_pay_data.payment_data), - descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()), - }, - tokenized_card: ApplePayTokenizedCard { - transaction_type: TransactionType::ApplePay, + None => { + let apple_pay_encrypted_data = apple_pay_data + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + })?; + ( + PaymentInformation::ApplePayToken(Box::new( + ApplePayTokenPaymentInformation { + fluid_data: FluidData { + value: Secret::from(apple_pay_encrypted_data.clone()), + descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()), + }, + tokenized_card: ApplePayTokenizedCard { + transaction_type: TransactionType::ApplePay, + }, }, - }, - )), - Some(PaymentSolution::ApplePay), - ), + )), + Some(PaymentSolution::ApplePay), + ) + } }, WalletData::GooglePay(google_pay_data) => ( PaymentInformation::GooglePay(Box::new(GooglePayPaymentInformation { @@ -371,7 +381,7 @@ pub struct CardPaymentInformation { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCard { - number: Secret<String>, + number: cards::CardNumber, expiration_month: Secret<String>, expiration_year: Secret<String>, cryptogram: Secret<String>, @@ -991,8 +1001,8 @@ impl Some(apple_pay_wallet_data.payment_method.network.clone()), ))?; let client_reference_information = ClientReferenceInformation::from(item); - let expiration_month = apple_pay_data.get_expiry_month()?; - let expiration_year = apple_pay_data.get_four_digit_expiry_year()?; + let expiration_month = apple_pay_data.get_expiry_month(); + let expiration_year = apple_pay_data.get_four_digit_expiry_year(); let payment_information = PaymentInformation::ApplePay(Box::new(ApplePayPaymentInformation { tokenized_card: TokenizedCard { @@ -1201,10 +1211,21 @@ impl TryFrom<&WellsfargoRouterData<&PaymentsAuthorizeRouterData>> for Wellsfargo ))?; let client_reference_information = ClientReferenceInformation::from(item); + + let apple_pay_encrypted_data = apple_pay_data + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context( + errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + }, + )?; let payment_information = PaymentInformation::ApplePayToken( Box::new(ApplePayTokenPaymentInformation { fluid_data: FluidData { - value: Secret::from(apple_pay_data.payment_data), + value: Secret::from( + apple_pay_encrypted_data.to_string(), + ), descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()), }, tokenized_card: ApplePayTokenizedCard { diff --git a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs index 01736d1f474..a6b7bcd0fa3 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs @@ -786,6 +786,18 @@ static WORLDPAYVANTIV_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethod ), }, ); + + worldpayvantiv_supported_payment_methods.add( + common_enums::PaymentMethod::Wallet, + common_enums::PaymentMethodType::ApplePay, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::Supported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + worldpayvantiv_supported_payment_methods }); diff --git a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs index 3fd7456e2ce..c986eeccfda 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs @@ -204,6 +204,14 @@ pub struct Authorization { pub processing_type: Option<VantivProcessingType>, #[serde(skip_serializing_if = "Option::is_none")] pub original_network_transaction_id: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub cardholder_authentication: Option<CardholderAuthentication>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CardholderAuthentication { + authentication_value: Secret<String>, } #[derive(Debug, Serialize)] @@ -249,6 +257,7 @@ pub struct RefundRequest { #[serde(rename_all = "lowercase")] pub enum OrderSource { Ecommerce, + ApplePay, MailOrder, Telephone, } @@ -297,6 +306,31 @@ pub enum WorldpayvativCardType { UnionPay, } +#[derive(Debug, Clone, Serialize, strum::EnumString)] +pub enum WorldPayVativApplePayNetwork { + Visa, + MasterCard, + AmEx, + Discover, + DinersClub, + JCB, + UnionPay, +} + +impl From<WorldPayVativApplePayNetwork> for WorldpayvativCardType { + fn from(network: WorldPayVativApplePayNetwork) -> Self { + match network { + WorldPayVativApplePayNetwork::Visa => Self::Visa, + WorldPayVativApplePayNetwork::MasterCard => Self::MasterCard, + WorldPayVativApplePayNetwork::AmEx => Self::AmericanExpress, + WorldPayVativApplePayNetwork::Discover => Self::Discover, + WorldPayVativApplePayNetwork::DinersClub => Self::DinersClub, + WorldPayVativApplePayNetwork::JCB => Self::JCB, + WorldPayVativApplePayNetwork::UnionPay => Self::UnionPay, + } + } +} + impl TryFrom<common_enums::CardNetwork> for WorldpayvativCardType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(card_network: common_enums::CardNetwork) -> Result<Self, Self::Error> { @@ -496,7 +530,7 @@ impl TryFrom<&WorldpayvantivRouterData<&PaymentsAuthorizeRouterData>> for CnpOnl })? }; - let card = get_vantiv_card_data(&item.router_data.request.payment_method_data.clone())?; + let (card, cardholder_authentication) = get_vantiv_card_data(item)?; let report_group = item .router_data .request @@ -524,7 +558,7 @@ impl TryFrom<&WorldpayvantivRouterData<&PaymentsAuthorizeRouterData>> for CnpOnl let bill_to_address = get_bill_to_address(item.router_data); let ship_to_address = get_ship_to_address(item.router_data); let processing_info = get_processing_info(&item.router_data.request)?; - let order_source = OrderSource::from(&item.router_data.request.payment_channel); + let order_source = OrderSource::from(item); let (authorization, sale) = if item.router_data.request.is_auto_capture()? && item.amount != MinorUnit::zero() { ( @@ -571,6 +605,7 @@ impl TryFrom<&WorldpayvantivRouterData<&PaymentsAuthorizeRouterData>> for CnpOnl token: processing_info.token, processing_type: processing_info.processing_type, original_network_transaction_id: processing_info.network_transaction_id, + cardholder_authentication, }), None, ) @@ -590,9 +625,16 @@ impl TryFrom<&WorldpayvantivRouterData<&PaymentsAuthorizeRouterData>> for CnpOnl } } -impl From<&Option<common_enums::PaymentChannel>> for OrderSource { - fn from(payment_channel: &Option<common_enums::PaymentChannel>) -> Self { - match payment_channel { +impl From<&WorldpayvantivRouterData<&PaymentsAuthorizeRouterData>> for OrderSource { + fn from(item: &WorldpayvantivRouterData<&PaymentsAuthorizeRouterData>) -> Self { + if let PaymentMethodData::Wallet( + hyperswitch_domain_models::payment_method_data::WalletData::ApplePay(_), + ) = &item.router_data.request.payment_method_data + { + return Self::ApplePay; + } + + match item.router_data.request.payment_channel { Some(common_enums::PaymentChannel::Ecommerce) | Some(common_enums::PaymentChannel::Other(_)) | None => Self::Ecommerce, @@ -2998,8 +3040,15 @@ fn get_refund_status( } fn get_vantiv_card_data( - payment_method_data: &PaymentMethodData, -) -> Result<Option<WorldpayvantivCardData>, error_stack::Report<errors::ConnectorError>> { + item: &WorldpayvantivRouterData<&PaymentsAuthorizeRouterData>, +) -> Result< + ( + Option<WorldpayvantivCardData>, + Option<CardholderAuthentication>, + ), + error_stack::Report<errors::ConnectorError>, +> { + let payment_method_data = item.router_data.request.payment_method_data.clone(); match payment_method_data { PaymentMethodData::Card(card) => { let card_type = match card.card_network.clone() { @@ -3009,12 +3058,15 @@ fn get_vantiv_card_data( let exp_date = card.get_expiry_date_as_mmyy()?; - Ok(Some(WorldpayvantivCardData { - card_type, - number: card.card_number.clone(), - exp_date, - card_validation_num: Some(card.card_cvc.clone()), - })) + Ok(( + Some(WorldpayvantivCardData { + card_type, + number: card.card_number.clone(), + exp_date, + card_validation_num: Some(card.card_cvc.clone()), + }), + None, + )) } PaymentMethodData::CardDetailsForNetworkTransactionId(card_data) => { let card_type = match card_data.card_network.clone() { @@ -3024,14 +3076,73 @@ fn get_vantiv_card_data( let exp_date = card_data.get_expiry_date_as_mmyy()?; - Ok(Some(WorldpayvantivCardData { - card_type, - number: card_data.card_number.clone(), - exp_date, - card_validation_num: None, - })) + Ok(( + Some(WorldpayvantivCardData { + card_type, + number: card_data.card_number.clone(), + exp_date, + card_validation_num: None, + }), + None, + )) } - PaymentMethodData::MandatePayment => Ok(None), + PaymentMethodData::MandatePayment => Ok((None, None)), + PaymentMethodData::Wallet(wallet_data) => match wallet_data { + hyperswitch_domain_models::payment_method_data::WalletData::ApplePay( + apple_pay_data, + ) => match item.router_data.payment_method_token.clone() { + Some( + hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt( + apple_pay_decrypted_data, + ), + ) => { + let number = apple_pay_decrypted_data + .application_primary_account_number + .clone(); + let exp_date = apple_pay_decrypted_data + .get_expiry_date_as_mmyy() + .change_context(errors::ConnectorError::InvalidDataFormat { + field_name: "payment_method_data.card.card_exp_month", + })?; + + let cardholder_authentication = CardholderAuthentication { + authentication_value: apple_pay_decrypted_data + .payment_data + .online_payment_cryptogram + .clone(), + }; + + let apple_pay_network = apple_pay_data + .payment_method + .network + .parse::<WorldPayVativApplePayNetwork>() + .change_context(errors::ConnectorError::ParsingFailed) + .attach_printable_lazy(|| { + format!( + "Failed to parse Apple Pay network: {}", + apple_pay_data.payment_method.network + ) + })?; + + Ok(( + (Some(WorldpayvantivCardData { + card_type: apple_pay_network.into(), + number, + exp_date, + card_validation_num: None, + })), + Some(cardholder_authentication), + )) + } + _ => Err( + errors::ConnectorError::NotImplemented("Payment method type".to_string()) + .into(), + ), + }, + _ => Err( + errors::ConnectorError::NotImplemented("Payment method type".to_string()).into(), + ), + }, _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index d2ee231d144..7222acddc37 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -50,7 +50,7 @@ use hyperswitch_domain_models::{ network_tokenization::NetworkTokenNumber, payment_method_data::{self, Card, CardDetailsForNetworkTransactionId, PaymentMethodData}, router_data::{ - ApplePayPredecryptData, ErrorResponse, PaymentMethodToken, RecurringMandatePaymentData, + ErrorResponse, PaymentMethodToken, RecurringMandatePaymentData, RouterData as ConnectorRouterData, }, router_request_types::{ @@ -1024,40 +1024,6 @@ impl AccessTokenRequestInfo for RefreshTokenRouterData { .ok_or_else(missing_field_err("request.id")) } } -pub trait ApplePayDecrypt { - fn get_expiry_month(&self) -> Result<Secret<String>, Error>; - fn get_two_digit_expiry_year(&self) -> Result<Secret<String>, Error>; - fn get_four_digit_expiry_year(&self) -> Result<Secret<String>, Error>; -} - -impl ApplePayDecrypt for Box<ApplePayPredecryptData> { - fn get_two_digit_expiry_year(&self) -> Result<Secret<String>, Error> { - Ok(Secret::new( - self.application_expiration_date - .get(0..2) - .ok_or(errors::ConnectorError::RequestEncodingFailed)? - .to_string(), - )) - } - - fn get_four_digit_expiry_year(&self) -> Result<Secret<String>, Error> { - Ok(Secret::new(format!( - "20{}", - self.application_expiration_date - .get(0..2) - .ok_or(errors::ConnectorError::RequestEncodingFailed)? - ))) - } - - fn get_expiry_month(&self) -> Result<Secret<String>, Error> { - Ok(Secret::new( - self.application_expiration_date - .get(2..4) - .ok_or(errors::ConnectorError::RequestEncodingFailed)? - .to_owned(), - )) - } -} #[derive(Debug, Copy, Clone, strum::Display, Eq, Hash, PartialEq)] pub enum CardIssuer { @@ -5791,12 +5757,20 @@ pub trait ApplePay { impl ApplePay for payment_method_data::ApplePayWalletData { fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error> { + let apple_pay_encrypted_data = self + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + })?; let token = Secret::new( - String::from_utf8(BASE64_ENGINE.decode(&self.payment_data).change_context( - errors::ConnectorError::InvalidWalletToken { - wallet_name: "Apple Pay".to_string(), - }, - )?) + String::from_utf8( + BASE64_ENGINE + .decode(apple_pay_encrypted_data) + .change_context(errors::ConnectorError::InvalidWalletToken { + wallet_name: "Apple Pay".to_string(), + })?, + ) .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })?, diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index adb4e380782..d4e89a1cf6f 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -474,7 +474,7 @@ pub struct GpayTokenizationData { #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct ApplePayWalletData { /// The payment data of Apple pay - pub payment_data: String, + pub payment_data: common_types::payments::ApplePayPaymentData, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index 8cdcfe7e456..c77f0e3a7bb 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -1,6 +1,6 @@ use std::{collections::HashMap, marker::PhantomData}; -use common_types::primitive_wrappers; +use common_types::{payments as common_payment_types, primitive_wrappers}; use common_utils::{ errors::IntegrityCheckError, ext_traits::{OptionExt, ValueExt}, @@ -244,30 +244,81 @@ pub struct AccessToken { #[derive(Debug, Clone, serde::Deserialize)] pub enum PaymentMethodToken { Token(Secret<String>), - ApplePayDecrypt(Box<ApplePayPredecryptData>), + ApplePayDecrypt(Box<common_payment_types::ApplePayPredecryptData>), GooglePayDecrypt(Box<GooglePayDecryptedData>), PazeDecrypt(Box<PazeDecryptedData>), } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ApplePayPredecryptData { - pub application_primary_account_number: Secret<String>, +pub struct ApplePayPredecryptDataInternal { + pub application_primary_account_number: cards::CardNumber, pub application_expiration_date: String, pub currency_code: String, pub transaction_amount: i64, pub device_manufacturer_identifier: Secret<String>, pub payment_data_type: Secret<String>, - pub payment_data: ApplePayCryptogramData, + pub payment_data: ApplePayCryptogramDataInternal, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ApplePayCryptogramData { +pub struct ApplePayCryptogramDataInternal { pub online_payment_cryptogram: Secret<String>, pub eci_indicator: Option<String>, } +impl TryFrom<ApplePayPredecryptDataInternal> for common_payment_types::ApplePayPredecryptData { + type Error = common_utils::errors::ValidationError; + fn try_from(data: ApplePayPredecryptDataInternal) -> Result<Self, Self::Error> { + let application_expiration_month = data.clone().get_expiry_month()?; + let application_expiration_year = data.clone().get_four_digit_expiry_year()?; + + Ok(Self { + application_primary_account_number: data.application_primary_account_number.clone(), + application_expiration_month, + application_expiration_year, + payment_data: data.payment_data.into(), + }) + } +} + +impl From<ApplePayCryptogramDataInternal> for common_payment_types::ApplePayCryptogramData { + fn from(payment_data: ApplePayCryptogramDataInternal) -> Self { + Self { + online_payment_cryptogram: payment_data.online_payment_cryptogram, + eci_indicator: payment_data.eci_indicator, + } + } +} + +impl ApplePayPredecryptDataInternal { + /// This logic being applied as apple pay provides application_expiration_date in the YYMMDD format + fn get_four_digit_expiry_year( + &self, + ) -> Result<Secret<String>, common_utils::errors::ValidationError> { + Ok(Secret::new(format!( + "20{}", + self.application_expiration_date.get(0..2).ok_or( + common_utils::errors::ValidationError::InvalidValue { + message: "Invalid two-digit year".to_string(), + } + )? + ))) + } + + fn get_expiry_month(&self) -> Result<Secret<String>, common_utils::errors::ValidationError> { + Ok(Secret::new( + self.application_expiration_date + .get(2..4) + .ok_or(common_utils::errors::ValidationError::InvalidValue { + message: "Invalid two-digit month".to_string(), + })? + .to_owned(), + )) + } +} + #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayDecryptedData { diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 58e178f5b9a..344036a198f 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -237,6 +237,9 @@ Never share your secret api keys. Keep them guarded and secure. common_utils::payout_method_utils::PaypalAdditionalData, common_utils::payout_method_utils::VenmoAdditionalData, common_types::payments::SplitPaymentsRequest, + common_types::payments::ApplePayPaymentData, + common_types::payments::ApplePayPredecryptData, + common_types::payments::ApplePayCryptogramData, common_types::payments::StripeSplitPaymentRequest, common_types::domain::AdyenSplitData, common_types::domain::AdyenSplitItem, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 23f0fa2d0d2..a8e44940a0c 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -179,6 +179,10 @@ Never share your secret api keys. Keep them guarded and secure. common_utils::payout_method_utils::PaypalAdditionalData, common_utils::payout_method_utils::VenmoAdditionalData, common_types::payments::SplitPaymentsRequest, + common_types::payments::ApplePayPaymentData, + common_types::payments::ApplePayPredecryptData, + common_types::payments::ApplePayCryptogramData, + common_types::payments::ApplePayPaymentData, common_types::payments::StripeSplitPaymentRequest, common_types::domain::AdyenSplitData, common_types::payments::AcceptanceType, diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 5deeeadb41f..fb6ee799026 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -40,7 +40,7 @@ use crate::{ self, api, domain, storage::enums as storage_enums, transformers::{ForeignFrom, ForeignTryFrom}, - ApplePayPredecryptData, BrowserInformation, PaymentsCancelData, ResponseId, + BrowserInformation, PaymentsCancelData, ResponseId, }, utils::{OptionExt, ValueExt}, }; @@ -1686,10 +1686,16 @@ pub trait ApplePay { impl ApplePay for domain::ApplePayWalletData { fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error> { + let apple_pay_encrypted_data = self + .payment_data + .get_encrypted_apple_pay_payment_data_mandatory() + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "Apple pay encrypted data", + })?; let token = Secret::new( String::from_utf8( consts::BASE64_ENGINE - .decode(&self.payment_data) + .decode(apple_pay_encrypted_data) .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })?, @@ -1702,31 +1708,6 @@ impl ApplePay for domain::ApplePayWalletData { } } -pub trait ApplePayDecrypt { - fn get_expiry_month(&self) -> Result<Secret<String>, Error>; - fn get_four_digit_expiry_year(&self) -> Result<Secret<String>, Error>; -} - -impl ApplePayDecrypt for Box<ApplePayPredecryptData> { - fn get_four_digit_expiry_year(&self) -> Result<Secret<String>, Error> { - Ok(Secret::new(format!( - "20{}", - self.application_expiration_date - .get(0..2) - .ok_or(errors::ConnectorError::RequestEncodingFailed)? - ))) - } - - fn get_expiry_month(&self) -> Result<Secret<String>, Error> { - Ok(Secret::new( - self.application_expiration_date - .get(2..4) - .ok_or(errors::ConnectorError::RequestEncodingFailed)? - .to_owned(), - )) - } -} - pub trait CryptoData { fn get_pay_currency(&self) -> Result<String, Error>; } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index a912dc27b82..3c2a447120f 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3562,6 +3562,13 @@ where _ => return Ok(None), }; + // Check if the wallet has already decrypted the token from the payment data. + // If a pre-decrypted token is available, use it directly to avoid redundant decryption. + if let Some(predecrypted_token) = wallet.check_predecrypted_token(payment_data)? { + logger::debug!("Using predecrypted token for wallet"); + return Ok(Some(predecrypted_token)); + } + let merchant_connector_account = get_merchant_connector_account_for_wallet_decryption_flow::<F, D>( state, @@ -4902,6 +4909,15 @@ where F: Send + Clone, D: OperationSessionGetters<F> + Send + Sync + Clone, { + /// Check if wallet data is already decrypted and return token if so + fn check_predecrypted_token( + &self, + _payment_data: &D, + ) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> { + // Default implementation returns None (no pre-decrypted data) + Ok(None) + } + fn decide_wallet_flow( &self, state: &SessionState, @@ -4990,6 +5006,33 @@ where F: Send + Clone, D: OperationSessionGetters<F> + Send + Sync + Clone, { + fn check_predecrypted_token( + &self, + payment_data: &D, + ) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> { + let apple_pay_wallet_data = payment_data + .get_payment_method_data() + .and_then(|payment_method_data| payment_method_data.get_wallet_data()) + .and_then(|wallet_data| wallet_data.get_apple_pay_wallet_data()) + .get_required_value("Apple Pay wallet token") + .attach_printable( + "Apple Pay wallet data not found in the payment method data during the Apple Pay predecryption flow", + )?; + + match &apple_pay_wallet_data.payment_data { + common_payments_types::ApplePayPaymentData::Encrypted(_) => Ok(None), + common_payments_types::ApplePayPaymentData::Decrypted(apple_pay_predecrypt_data) => { + helpers::validate_card_expiry( + &apple_pay_predecrypt_data.application_expiration_month, + &apple_pay_predecrypt_data.application_expiration_year, + )?; + Ok(Some(PaymentMethodToken::ApplePayDecrypt(Box::new( + apple_pay_predecrypt_data.clone(), + )))) + } + } + } + fn decide_wallet_flow( &self, state: &SessionState, @@ -5028,9 +5071,10 @@ where .get_payment_method_data() .and_then(|payment_method_data| payment_method_data.get_wallet_data()) .and_then(|wallet_data| wallet_data.get_apple_pay_wallet_data()) - .get_required_value("Paze wallet token").attach_printable( + .get_required_value("Apple Pay wallet token").attach_printable( "Apple Pay wallet data not found in the payment method data during the Apple Pay decryption flow", )?; + let apple_pay_data = ApplePayData::token_json(domain::WalletData::ApplePay(apple_pay_wallet_data.clone())) .change_context(errors::ApiErrorResponse::InternalServerError) @@ -5043,15 +5087,22 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to decrypt apple pay token")?; - let apple_pay_predecrypt = apple_pay_data - .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>( - "ApplePayPredecryptData", + let apple_pay_predecrypt_internal = apple_pay_data + .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptDataInternal>( + "ApplePayPredecryptDataInternal", ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "failed to parse decrypted apple pay response to ApplePayPredecryptData", )?; + let apple_pay_predecrypt = + common_types::payments::ApplePayPredecryptData::try_from(apple_pay_predecrypt_internal) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "failed to convert ApplePayPredecryptDataInternal to ApplePayPredecryptData", + )?; + Ok(PaymentMethodToken::ApplePayDecrypt(Box::new( apple_pay_predecrypt, ))) diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 3a51c628b82..c7fe77e46a0 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -47,10 +47,10 @@ use hyperswitch_domain_models::router_flow_types::{ pub use hyperswitch_domain_models::{ payment_address::PaymentAddress, router_data::{ - AccessToken, AdditionalPaymentMethodConnectorResponse, ApplePayCryptogramData, - ApplePayPredecryptData, ConnectorAuthType, ConnectorResponseData, ErrorResponse, - GooglePayDecryptedData, GooglePayPaymentMethodDetails, PaymentMethodBalance, - PaymentMethodToken, RecurringMandatePaymentData, RouterData, + AccessToken, AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, + ConnectorResponseData, ErrorResponse, GooglePayDecryptedData, + GooglePayPaymentMethodDetails, PaymentMethodBalance, PaymentMethodToken, + RecurringMandatePaymentData, RouterData, }, router_data_v2::{ AccessTokenFlowData, DisputesFlowData, ExternalAuthenticationFlowData, FilesFlowData, diff --git a/crates/router/tests/connectors/worldpay.rs b/crates/router/tests/connectors/worldpay.rs index 451aa398eb7..9909a9498f2 100644 --- a/crates/router/tests/connectors/worldpay.rs +++ b/crates/router/tests/connectors/worldpay.rs @@ -100,7 +100,9 @@ async fn should_authorize_applepay_payment() { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Wallet( domain::WalletData::ApplePay(domain::ApplePayWalletData { - payment_data: "someData".to_string(), + payment_data: common_types::payments::ApplePayPaymentData::Encrypted( + "someData".to_string(), + ), transaction_identifier: "someId".to_string(), payment_method: domain::ApplepayPaymentMethod { display_name: "someName".to_string(),
2025-08-01T07:34: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 --> This pull request adds support pass the decryted apple pay token directly in the confirm call. This pull also request introduces significant changes to the handling of Apple Pay payment data across multiple modules, improving the structure, validation, and usage of encrypted and decrypted Apple Pay data. It also refactors related code to enhance type safety and modularity. Below is a summary of the most important changes grouped by themes. ### 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)? --> ### Test apple pay pre decrypt flow -> Enable apple pay for a connector a connector that supports decryption and do not configure any apple pay certificates. -> Make a payment by passing pre decrypted apple pay token in the confirm call ``` { "amount": 7445, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 7445, "customer_id": "cu_{{$timestamp}}", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "setup_future_usage": "on_session", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "billing": { "address": { "line1": "1467", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data": { "application_primary_account_number": "4242424242424242", "application_expiration_month": "09", "application_expiration_year": "30", "payment_data": { "online_payment_cryptogram": "AQAA*******yB5A=", "eci_indicator": "5" } }, "payment_method": { "display_name": "Discover 9319", "network": "Discover", "type": "debit" }, "transaction_identifier": "c635c5b3af900d7bd81fecd7028f1262f9d030754ee65ec7afd988a678194751" } } } } ``` ``` { "payment_id": "pay_rsndpQQg3q5d6MZcC90t", "merchant_id": "merchant_1754031338", "status": "succeeded", "amount": 7445, "net_amount": 7445, "shipping_cost": null, "amount_capturable": 0, "amount_received": 7445, "connector": "cybersource", "client_secret": "pay_rsndpQQg3q5d6MZcC90t_secret_3WokDjcCK7LkjIHKoERT", "created": "2025-08-01T07:55:32.248Z", "currency": "USD", "customer_id": "cu_1754034932", "customer": { "id": "cu_1754034932", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "apple_pay": { "last4": "9319", "card_network": "Discover", "type": "debit" } }, "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": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "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": "apple_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_1754034932", "created_at": 1754034932, "expires": 1754038532, "secret": "epk_6a7deed7c99d4abc955276e5528f0edf" }, "manual_retry_allowed": false, "connector_transaction_id": "7540349324566718504805", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_rsndpQQg3q5d6MZcC90t_1", "payment_link": null, "profile_id": "pro_BdMNcMGamneoVpCbUGjD", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_N7zyBtWcYsXLn1xxwiZL", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-01T08:10:32.248Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-08-01T07:55:32.744Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` logs indicating apple pay pre decrypt flow <img width="2040" height="338" alt="image" src="https://github.com/user-attachments/assets/94af13ac-af0a-4092-8f19-d0bd59b7f2fc" /> logs showing decrypted apple pay token being sent to the connector <img width="2031" height="403" alt="image" src="https://github.com/user-attachments/assets/c0fc463d-5907-48ea-93cb-584396139bad" /> ### Test apple pay hyperswitch decryption flow -> Enable apple pay for a connector by selecting payment_processing_details_at `Hyperswitch` -> Make a apple pay payment ``` { "amount": 1, "currency": "EUR", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 1, "customer_id": "cu_{{$timestamp}}", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "setup_future_usage": "on_session", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "billing": { "address": { "line1": "1467", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "eyJkYXRhIjoiK3N4aGdBODIvSC9hZ1E5ZnJ2WklMNXJmaDl0REtheFd2aFhlZ0ZFeVhuM2ZPVnpDVWRNOXhaOWhXRnNSZ0toUlFRY0JNQndHQ1NxR1NJYjNEUUVKQlRFUEZ3MHlOVEEyTURReE1URTBNekJhTUNnR0NTcUdTSWIzRFFFSk5ERWJNQmt3Q3dZSllJWklBV1VEQkFJQm9Rb0dDQ3FHU000OUJBTUNNQzhHQ1NxR1NJYjNEUUVKQkRFaUJDRGlkOTVsU2gyKy9MZW9wdDlYZ0txOFJTTlJZbWxmSjcvYmtEWGZEeWQrM0RBS0JnZ3Foa2pPUFFRREFnUkhNRVVDSVFEWGxXN3JZREZEODFqb2tTWHBBVjE0aFZtTjBXOFBGUkIrY0IvVXFDUVp5Z0lnWlVGb2FXb21aZVMranJvblVqdTNwNE5FWDFmeGYrc2xhOVRLL1pCb0VSTUFBQUFBQUFBPSIsImhlYWRlciI6eyJwdWJsaWNLZXlIYXNoIjoiMVlTbEwwWUo3cE84ZThHWVVhZFN0dXRWRUdRNU5LS2N2aHJOd2IvRE9nOD0iLCJlcGhlbWVyYWxQdWJsaWNLZXkiOiJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUUxZXFPemRFWTJmTnlwaWovT3NhaEFFZjk2a3h3RjNKbUZrNG5ITXdsVnJ5ZWwyeTdMbHgrdDhTekY0ZVQxRE1FZWlnYkY2Sk9zMlV3Z3QxUnFpK09zQT09IiwidHJhbnNhY3Rpb25JZCI6ImZmODBlNzk4ODhiMTU5MjRhYjY2N2EyMmI3YWNjZTlkYjYzNjQxODI3ZDVkOTQ2MWYwZDBkODU0ZWM1ZTFkNTEifSwidmVyc2lvbiI6IkVDX3YxIn0=", "payment_method": { "display_name": "Discover 9319", "network": "Discover", "type": "debit" }, "transaction_identifier": "c635c5b3af900d7bd81fecd7028f1262f9d030754ee65ec7afd988a678194751" } } } } ``` ``` { "payment_id": "pay_Q8ydSHV3zjSZOutKTRCN", "merchant_id": "merchant_1754035609", "status": "succeeded", "amount": 1, "net_amount": 1, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1, "connector": "cybersource", "client_secret": "pay_Q8ydSHV3zjSZOutKTRCN_secret_aj6St1LLygIZ78PHEaDH", "created": "2025-08-01T08:17:55.511Z", "currency": "EUR", "customer_id": "cu_1754036275", "customer": { "id": "cu_1754036275", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "apple_pay": { "last4": "9319", "card_network": "Discover", "type": "debit" } }, "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": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "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": "apple_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_1754036275", "created_at": 1754036275, "expires": 1754039875, "secret": "epk_3f50b029f83d4d72876d0a9efe3547ea" }, "manual_retry_allowed": false, "connector_transaction_id": "7540362767046209204805", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_Q8ydSHV3zjSZOutKTRCN_1", "payment_link": null, "profile_id": "pro_oPnag2LsACnLlbDFDkgf", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3IV2FB3yWpFmLr0b9Z3N", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-01T08:32:55.511Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-08-01T08:17:57.043Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` Logs indicating decrypt apple pay token <img width="1481" height="441" alt="image" src="https://github.com/user-attachments/assets/aec80973-3b31-4b9f-8f3e-d13310b435d6" /> Logs showing decrypted token in the connector request <img width="2045" height="566" alt="image" src="https://github.com/user-attachments/assets/22a4d603-2280-4690-b3bc-3b92c77976ff" /> ### Test connector decryption flow -> Enabled apple pay with payment processing details at "Connector" ``` { "amount": 6500, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 6500, "customer_id": "cu_{{$timestamp}}", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "setup_future_usage": "off_session", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "apple_pay", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "=", "payment_method": { "display_name": "Visa 0121", "network": "Visa", "type": "credit" }, "transaction_identifier": "c91059b67493677daf9e18ad07d26bc767d931d87b377d7b0062878696509342" } } } } ``` ``` { "payment_id": "pay_KzSYCSHQEDEusanXEBfM", "merchant_id": "merchant_1754045350", "status": "succeeded", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6500, "connector": "adyen", "client_secret": "pay_KzSYCSHQEDEusanXEBfM_secret_y7T1LarPEoR2E9CRnlCP", "created": "2025-08-01T11:00:57.986Z", "currency": "USD", "customer_id": "cu_1754046058", "customer": { "id": "cu_1754046058", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": { "apple_pay": { "last4": "0121", "card_network": "Visa", "type": "credit" } }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "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": "apple_pay", "connector_label": "adyen_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1754046058", "created_at": 1754046057, "expires": 1754049657, "secret": "epk_c04d44072b9f45ccb4b62f50131096f6" }, "manual_retry_allowed": false, "connector_transaction_id": "TSKD2XD2GPXBGZV5", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_KzSYCSHQEDEusanXEBfM_1", "payment_link": null, "profile_id": "pro_deLVMQyHA9B0On0hO1OP", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_NwmhWrK6Lwwkfbn0zjna", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-08-01T11:15:57.986Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_r51tT1dt6mwNbGAfvgz9", "payment_method_status": "active", "updated": "2025-08-01T11:00:59.822Z", "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": "VWM6LZJ2RM6XPST5", "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": 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.115.0
90f3b09a77484a4262608b0a4eeca7d452a4c968
90f3b09a77484a4262608b0a4eeca7d452a4c968
juspay/hyperswitch
juspay__hyperswitch-8811
Bug: [BUG] recurring payouts fail when address is needed ### Bug Description Recurring payouts are failing when billing details are not supplied during payout creation. ### Expected Behavior Billing details should be fetched from DB while making recurring payouts. ### Actual Behavior Billing details are not stored / fetched in payment_methods while making recurring payouts. ### Steps To Reproduce 1. Create a payout using raw details 2. Retrieve the `payout_method_id` 3. Process a payout using `payout_method_id` without billing details Should throw an error saying billing details are mandatory. ```json { "error": { "type": "invalid_request", "message": "Missing required param: billing.address", "code": "IR_04" } } ``` ### Context For The Bug _No response_ ### Environment / - ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index c7784118847..e4ce038b3bd 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -175,7 +175,8 @@ pub fn make_dsl_input_for_payouts( billing_country: payout_data .billing_address .as_ref() - .and_then(|bic| bic.country) + .and_then(|ba| ba.address.as_ref()) + .and_then(|addr| addr.country) .map(api_enums::Country::from_alpha2), business_label: payout_data.payout_attempt.business_label.clone(), setup_future_usage: None, diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 300fca52939..491957045c7 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -29,7 +29,7 @@ use diesel_models::{ use error_stack::{report, ResultExt}; #[cfg(feature = "olap")] use futures::future::join_all; -use hyperswitch_domain_models::payment_methods::PaymentMethod; +use hyperswitch_domain_models::{self as domain_models, payment_methods::PaymentMethod}; use masking::{PeekInterface, Secret}; #[cfg(feature = "payout_retry")] use retry::GsmValidation; @@ -66,7 +66,7 @@ use crate::{ // ********************************************** TYPES ********************************************** #[derive(Clone)] pub struct PayoutData { - pub billing_address: Option<domain::Address>, + pub billing_address: Option<domain_models::address::Address>, pub business_profile: domain::Profile, pub customer_details: Option<domain::Customer>, pub merchant_connector_account: Option<payment_helpers::MerchantConnectorAccountType>, @@ -812,7 +812,7 @@ pub async fn payouts_list_core( }) .ok() .as_ref() - .map(hyperswitch_domain_models::address::Address::from) + .map(domain_models::address::Address::from) .map(payment_enums::Address::from) }); @@ -2537,10 +2537,7 @@ pub async fn response_handler( let billing_address = payout_data.billing_address.to_owned(); let customer_details = payout_data.customer_details.to_owned(); let customer_id = payouts.customer_id; - let billing = billing_address - .as_ref() - .map(hyperswitch_domain_models::address::Address::from) - .map(From::from); + let billing = billing_address.map(From::from); let translated_unified_message = helpers::get_translated_unified_code_and_message( state, @@ -2672,29 +2669,17 @@ pub async fn payout_create_db_entries( _ => None, }; - // We have to do this because the function that is being used to create / get address is from payments - // which expects a payment_id - let payout_id_as_payment_id_type = id_type::PaymentId::try_from(std::borrow::Cow::Owned( - payout_id.get_string_repr().to_string(), - )) - .change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "payout_id contains invalid data".to_string(), - }) - .attach_printable("Error converting payout_id to PaymentId type")?; - - // Get or create address - let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( + // Get or create billing address + let (billing_address, address_id) = helpers::resolve_billing_address_for_payout( state, req.billing.as_ref(), None, - merchant_id, + payment_method.as_ref(), + merchant_context, customer_id.as_ref(), - merchant_context.get_merchant_key_store(), - &payout_id_as_payment_id_type, - merchant_context.get_merchant_account().storage_scheme, + payout_id, ) .await?; - let address_id = billing_address.to_owned().map(|address| address.address_id); // Make payouts entry let currency = req.currency.to_owned().get_required_value("currency")?; @@ -2931,7 +2916,8 @@ pub async fn make_payout_data( &payout_id_as_payment_id_type, merchant_context.get_merchant_account().storage_scheme, ) - .await?; + .await? + .map(|addr| domain_models::address::Address::from(&addr)); let payout_id = &payouts.payout_id; diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 8f104451be5..c80a089e5d4 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -4,7 +4,7 @@ use common_utils::{ crypto::Encryptable, encryption::Encryption, errors::CustomResult, - ext_traits::{AsyncExt, StringExt}, + ext_traits::{AsyncExt, StringExt, ValueExt}, fp_utils, id_type, payout_method_utils as payout_additional, pii, type_name, types::{ keymanager::{Identifier, KeyManagerState}, @@ -605,6 +605,22 @@ pub async fn save_payout_data_to_locker( ) }; + let payment_method_billing_address = payout_data + .billing_address + .clone() + .async_map(|billing_addr| async { + cards::create_encrypted_data( + &key_manager_state, + merchant_context.get_merchant_key_store(), + billing_addr, + ) + .await + }) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt billing address")?; + // Insert new entry in payment_methods table if should_insert_in_pm_table { let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); @@ -625,7 +641,7 @@ pub async fn save_payout_data_to_locker( connector_mandate_details, None, None, - None, + payment_method_billing_address, None, None, None, @@ -1268,37 +1284,19 @@ pub async fn update_payouts_and_payout_attempt( payout_data.payouts.customer_id.clone() }; - // We have to do this because the function that is being used to create / get address is from payments - // which expects a payment_id - let payout_id_as_payment_id_type = id_type::PaymentId::try_from(std::borrow::Cow::Owned( - payout_id.get_string_repr().to_string(), - )) - .change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "payout_id contains invalid data for PaymentId conversion".to_string(), - }) - .attach_printable("Error converting payout_id to PaymentId type")?; - - // Fetch address details from request and create new or else use existing address that was attached - let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( + let (billing_address, address_id) = resolve_billing_address_for_payout( state, req.billing.as_ref(), - None, - merchant_context.get_merchant_account().get_id(), + payout_data.payouts.address_id.as_ref(), + payout_data.payment_method.as_ref(), + merchant_context, customer_id.as_ref(), - merchant_context.get_merchant_key_store(), - &payout_id_as_payment_id_type, - merchant_context.get_merchant_account().storage_scheme, + &payout_id, ) .await?; - let address_id = if billing_address.is_some() { - payout_data.billing_address = billing_address; - payout_data - .billing_address - .as_ref() - .map(|address| address.address_id.clone()) - } else { - payout_data.payouts.address_id.clone() - }; + + // Update payout state with resolved billing address + payout_data.billing_address = billing_address; // Update DB with new data let payouts = payout_data.payouts.to_owned(); @@ -1536,3 +1534,105 @@ pub async fn get_additional_payout_data( } } } + +pub async fn resolve_billing_address_for_payout( + state: &SessionState, + req_billing: Option<&api_models::payments::Address>, + existing_address_id: Option<&String>, + payment_method: Option<&hyperswitch_domain_models::payment_methods::PaymentMethod>, + merchant_context: &domain::MerchantContext, + customer_id: Option<&id_type::CustomerId>, + payout_id: &id_type::PayoutId, +) -> RouterResult<( + Option<hyperswitch_domain_models::address::Address>, + Option<String>, +)> { + let payout_id_as_payment_id = id_type::PaymentId::try_from(std::borrow::Cow::Owned( + payout_id.get_string_repr().to_string(), + )) + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "payout_id contains invalid data for PaymentId conversion".to_string(), + }) + .attach_printable("Error converting payout_id to PaymentId type")?; + + match (req_billing, existing_address_id, payment_method) { + // Address in request + (Some(_), _, _) => { + let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( + state, + req_billing, + None, + merchant_context.get_merchant_account().get_id(), + customer_id, + merchant_context.get_merchant_key_store(), + &payout_id_as_payment_id, + merchant_context.get_merchant_account().storage_scheme, + ) + .await?; + let address_id = billing_address.as_ref().map(|a| a.address_id.clone()); + let hyperswitch_address = billing_address + .map(|addr| hyperswitch_domain_models::address::Address::from(&addr)); + Ok((hyperswitch_address, address_id)) + } + + // Existing address using address_id + (None, Some(address_id), _) => { + let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( + state, + None, + Some(address_id), + merchant_context.get_merchant_account().get_id(), + customer_id, + merchant_context.get_merchant_key_store(), + &payout_id_as_payment_id, + merchant_context.get_merchant_account().storage_scheme, + ) + .await?; + let hyperswitch_address = billing_address + .map(|addr| hyperswitch_domain_models::address::Address::from(&addr)); + Ok((hyperswitch_address, Some(address_id.clone()))) + } + + // Existing address in stored payment method + (None, None, Some(pm)) => { + pm.payment_method_billing_address.as_ref().map_or_else( + || { + logger::info!("No billing address found in payment method"); + Ok((None, None)) + }, + |encrypted_billing_address| { + logger::info!("Found encrypted billing address data in payment method"); + + #[cfg(feature = "v1")] + { + encrypted_billing_address + .clone() + .into_inner() + .expose() + .parse_value::<hyperswitch_domain_models::address::Address>( + "payment_method_billing_address", + ) + .map(|domain_address| { + logger::info!("Successfully parsed as hyperswitch_domain_models::address::Address"); + (Some(domain_address), None) + }) + .map_err(|e| { + logger::error!("Failed to parse billing address into (hyperswitch_domain_models::address::Address): {:?}", e); + errors::ApiErrorResponse::InternalServerError + }) + .attach_printable("Failed to parse stored billing address") + } + + #[cfg(feature = "v2")] + { + // TODO: Implement v2 logic when needed + logger::warn!("v2 billing address resolution not yet implemented"); + Ok((None, None)) + } + }, + ) + } + + (None, None, None) => Ok((None, None)), + } +} diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 4a56078858f..432a148fc41 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -98,30 +98,7 @@ pub async fn construct_payout_router_data<'a, F>( let billing = payout_data.billing_address.to_owned(); - let billing_address = billing.map(|a| { - let phone_details = api_models::payments::PhoneDetails { - number: a.phone_number.clone().map(Encryptable::into_inner), - country_code: a.country_code.to_owned(), - }; - let address_details = api_models::payments::AddressDetails { - city: a.city.to_owned(), - country: a.country.to_owned(), - line1: a.line1.clone().map(Encryptable::into_inner), - line2: a.line2.clone().map(Encryptable::into_inner), - line3: a.line3.clone().map(Encryptable::into_inner), - zip: a.zip.clone().map(Encryptable::into_inner), - first_name: a.first_name.clone().map(Encryptable::into_inner), - last_name: a.last_name.clone().map(Encryptable::into_inner), - state: a.state.map(Encryptable::into_inner), - origin_zip: a.origin_zip.map(Encryptable::into_inner), - }; - - api_models::payments::Address { - phone: Some(phone_details), - address: Some(address_details), - email: a.email.to_owned().map(Email::from), - } - }); + let billing_address = billing.map(api_models::payments::Address::from); let address = PaymentAddress::new(None, billing_address.map(From::from), None, None);
2025-09-04T09:52:17Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR adds capability for payouts to use billing address in payment_methods. 1. During first payout (with recurring: true) - payment_method entry created will store the billing address 2. During recurring payouts - stored billing address will be fetched and used ### 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 This fixes the bug where it required address as a mandatory field for recurring payouts (payout using stored tokens). ## How did you test it? Scenarios to test (for address) 1. Processing CIPT and using that token for processing payout 2. Processing a recurring payout and using that token for processing payout <details> <summary>1. Create payments CIT</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_nCYTBLS606xu5drbUngHWbjGv7PNWKuXbYzppYkoykcCnz4vFyEqbdW1hKW1BBUy' \ --data-raw '{"amount":4500,"currency":"EUR","confirm":true,"profile_id":"pro_XpJkLrIhn3boVv94ixmE","capture_method":"automatic","authentication_type":"three_ds","setup_future_usage":"off_session","customer_id":"cus_MQ79t5dcAGyQnVVXZ5vg","email":"abc@example.com","return_url":"https://google.com","payment_method":"card","payment_method_data":{"card":{"card_number":"4111111111111111","card_exp_month":"03","card_exp_year":"2030","card_cvc":"737"},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","zip":"94122","country":"IT","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"guest@example.com"}},"metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.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"}},"session_expiry":2890}' Response {"payment_id":"pay_DeekxhJrZ9CWyCTQCq4r","merchant_id":"merchant_1756974399","status":"succeeded","amount":4500,"net_amount":4500,"shipping_cost":null,"amount_capturable":0,"amount_received":4500,"connector":"adyen","client_secret":"pay_DeekxhJrZ9CWyCTQCq4r_secret_Ch5L75UesuEC9Err8YZU","created":"2025-09-04T09:36:22.282Z","currency":"EUR","customer_id":"cus_MQ79t5dcAGyQnVVXZ5vg","customer":{"id":"cus_MQ79t5dcAGyQnVVXZ5vg","name":"Albert Klaassen","email":"abc@example.com","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":"card","payment_method_data":{"card":{"last4":"1111","card_type":"CREDIT","card_network":"Visa","card_issuer":"JP Morgan","card_issuing_country":"INDIA","card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"joseph Doe","payment_checks":null,"authentication_data":null},"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":null,"first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"guest@example.com"}},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"abc@example.com","name":"Albert Klaassen","phone":"6168205362","return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_MQ79t5dcAGyQnVVXZ5vg","created_at":1756978582,"expires":1756982182,"secret":"epk_27ed6fdabc164aceb5e0aa888832c373"},"manual_retry_allowed":false,"connector_transaction_id":"WDV92WCPCC5FX875","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":{"redirect_response":null,"search_tags":null,"apple_pay_recurring_details":null,"gateway_system":"direct"},"reference_id":"pay_DeekxhJrZ9CWyCTQCq4r_1","payment_link":null,"profile_id":"pro_XpJkLrIhn3boVv94ixmE","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_Z5SC1uhu0kS6KvrnsxNY","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-09-04T10:24:32.282Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_channel":null,"payment_method_id":"pm_zRVZxGagdzsBMg5LmYct","network_transaction_id":"900345051761757","payment_method_status":"active","updated":"2025-09-04T09:36:23.649Z","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":"GJ7C3STP34XQLV75","card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null,"is_iframe_redirection_enabled":null,"whole_connector_response":null,"enable_partial_authorization":null} </details> <details> <summary>2. Process payout using stored payment_method_id</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_nCYTBLS606xu5drbUngHWbjGv7PNWKuXbYzppYkoykcCnz4vFyEqbdW1hKW1BBUy' \ --data '{"payout_method_id":"pm_zRVZxGagdzsBMg5LmYct","amount":1,"currency":"EUR","customer_id":"cus_MQ79t5dcAGyQnVVXZ5vg","phone_country_code":"+65","description":"Its my first payout request","connector":["adyen"],"entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true,"profile_id":"pro_XpJkLrIhn3boVv94ixmE"}' Response {"payout_id":"payout_uPw0KZVYyb3RnOrChh9Q","merchant_id":"merchant_1756974399","merchant_order_reference_id":null,"amount":1,"currency":"EUR","connector":"adyen","payout_type":"card","payout_method_data":{"card":{"card_issuer":"JP Morgan","card_network":"Visa","card_type":"CREDIT","card_issuing_country":"INDIA","bank_code":"JP_JPM","last4":"1111","card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"joseph Doe"}},"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":null,"first_name":"joseph","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":"guest@example.com"},"auto_fulfill":true,"customer_id":"cus_MQ79t5dcAGyQnVVXZ5vg","customer":{"id":"cus_MQ79t5dcAGyQnVVXZ5vg","name":"Albert Klaassen","email":"abc@example.com","phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_uPw0KZVYyb3RnOrChh9Q_secret_lVBCc5ylHYJonPY9Zhb3","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_5EG2zvgrEvH6Lv8xm3Ni","status":"success","error_message":null,"error_code":null,"profile_id":"pro_XpJkLrIhn3boVv94ixmE","created":"2025-09-04T09:37:16.364Z","connector_transaction_id":"RWZXLHMQMCJXKN75","priority":null,"payout_link":null,"email":"abc@example.com","name":"Albert Klaassen","phone":"6168205362","phone_country_code":"+1","unified_code":null,"unified_message":null,"payout_method_id":"pm_zRVZxGagdzsBMg5LmYct"} </details> <details> <summary>3. Create payout using raw details</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_Iikb8EKUsyOh2DtqlE3HmqD6xdzI47h94XHiKKHTgA5YVT1ng4iyMCqSCBgsUDf8' \ --data-raw '{"amount":100,"currency":"EUR","profile_id":"pro_tQvMhyOhPPzlg5agzwAM","customer":{"id":"cus_Z51PFM8B1iROSJcMzllP","email":"new_cust@example.com","name":"John Doe","phone":"999999999","phone_country_code":"+65"},"connector":["adyen"],"description":"Its my first payout request","payout_type":"card","payout_method_data":{"card":{"card_number":"4111 1111 1111 1111","expiry_month":"03","expiry_year":"2030","card_holder_name":"John Doe"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"US","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"}},"entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true}' Response {"payout_id":"payout_p9MwtbQ0ta4tItSgXqBf","merchant_id":"merchant_1756971567","merchant_order_reference_id":null,"amount":100,"currency":"EUR","connector":"adyen","payout_type":"card","payout_method_data":{"card":{"card_issuer":"JP Morgan","card_network":"Visa","card_type":"CREDIT","card_issuing_country":"INDIA","bank_code":"JP_JPM","last4":"1111","card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe"}},"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"auto_fulfill":true,"customer_id":"cus_Z51PFM8B1iROSJcMzllP","customer":{"id":"cus_Z51PFM8B1iROSJcMzllP","name":"Albert Klaassen","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_p9MwtbQ0ta4tItSgXqBf_secret_HiUN8ag2hf8gWxZj3HuY","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_5fXDmw6DZLP3aod1Zhsn","status":"success","error_message":null,"error_code":null,"profile_id":"pro_tQvMhyOhPPzlg5agzwAM","created":"2025-09-04T07:41:23.654Z","connector_transaction_id":"GB85JNB87RXVS3V5","priority":null,"payout_link":null,"email":null,"name":"Albert Klaassen","phone":"6168205362","phone_country_code":"+1","unified_code":null,"unified_message":null,"payout_method_id":"pm_cNt6gdwVpysyWzbHIDmo"} </details> <details> <summary>4. Process payout using payout_method_id</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_Iikb8EKUsyOh2DtqlE3HmqD6xdzI47h94XHiKKHTgA5YVT1ng4iyMCqSCBgsUDf8' \ --data '{"payout_method_id":"pm_cNt6gdwVpysyWzbHIDmo","amount":1,"currency":"EUR","customer_id":"cus_Z51PFM8B1iROSJcMzllP","phone_country_code":"+65","description":"Its my first payout request","connector":["adyen"],"entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true,"profile_id":"pro_tQvMhyOhPPzlg5agzwAM"}' Response {"payout_id":"payout_NKBml9En5YOW4ZfPKoDI","merchant_id":"merchant_1756971567","merchant_order_reference_id":null,"amount":1,"currency":"EUR","connector":"adyen","payout_type":"card","payout_method_data":{"card":{"card_issuer":"JP Morgan","card_network":"Visa","card_type":"CREDIT","card_issuing_country":"INDIA","bank_code":"JP_JPM","last4":"1111","card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe"}},"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe","origin_zip":null},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"auto_fulfill":true,"customer_id":"cus_Z51PFM8B1iROSJcMzllP","customer":{"id":"cus_Z51PFM8B1iROSJcMzllP","name":"Albert Klaassen","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_NKBml9En5YOW4ZfPKoDI_secret_fhKX0pr2SlIZjRDynimH","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_5fXDmw6DZLP3aod1Zhsn","status":"success","error_message":null,"error_code":null,"profile_id":"pro_tQvMhyOhPPzlg5agzwAM","created":"2025-09-04T07:44:05.254Z","connector_transaction_id":"LV4DQ6NDVV652VT5","priority":null,"payout_link":null,"email":null,"name":"Albert Klaassen","phone":"6168205362","phone_country_code":"+1","unified_code":null,"unified_message":null,"payout_method_id":"pm_cNt6gdwVpysyWzbHIDmo"} </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.116.0
5e1fd0b187b99698936a8a0cb0d839a60b830de2
5e1fd0b187b99698936a8a0cb0d839a60b830de2
juspay/hyperswitch
juspay__hyperswitch-8805
Bug: [CHORE] Add XOF currency to Cybersource cards Add XOF currency to Cybersource cards deployment configs.
diff --git a/config/config.example.toml b/config/config.example.toml index 5967731b9ad..4662e9ea3a5 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -672,8 +672,8 @@ google_pay = { currency = "USD" } samsung_pay = { currency = "USD" } [pm_filters.cybersource] -credit = { currency = "USD,GBP,EUR,PLN,SEK" } -debit = { currency = "USD,GBP,EUR,PLN,SEK" } +credit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } +debit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } apple_pay = { currency = "ARS, CAD, CLP, COP, CNY, EUR, HKD, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, GBP, AED, USD, PLN, SEK" } google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } samsung_pay = { currency = "USD,GBP,EUR,SEK" } @@ -1140,7 +1140,7 @@ billing_connectors_which_requires_invoice_sync_call = "recurly" # List of billin [revenue_recovery] monitoring_threshold_in_seconds = 2592000 # 30*24*60*60 secs , threshold for monitoring the retry system -retry_algorithm_type = "cascading" # type of retry algorithm +retry_algorithm_type = "cascading" # type of retry algorithm [clone_connector_allowlist] merchant_ids = "merchant_ids" # Comma-separated list of allowed merchant IDs @@ -1156,4 +1156,4 @@ allow_connected_merchants = false # Enable or disable connected merchant account [chat] enabled = false # Enable or disable chat features -hyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow host \ No newline at end of file +hyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow host diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 9ef3b802faa..9733244fb68 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -219,17 +219,17 @@ bank_redirect.trustly.connector_list = "adyen" bank_redirect.open_banking_uk.connector_list = "adyen" [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" } +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,xendit,moneris,archipel,worldpayvantiv,payload" 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,xendit,moneris,archipel,worldpayvantiv,payload" -pay_later.klarna.connector_list = "adyen,aci" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet,wellsfargo" +pay_later.klarna.connector_list = "adyen,aci" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet,wellsfargo" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet,wellsfargo" -wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal,authorizedotnet" +wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet,wellsfargo" +wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal,authorizedotnet" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" wallet.go_pay.connector_list = "adyen" @@ -238,9 +238,9 @@ 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,aci" -bank_redirect.sofort.connector_list = "globalpay,aci,multisafepay" -bank_redirect.giropay.connector_list = "globalpay,multisafepay,nexinets,aci" +bank_redirect.ideal.connector_list = "stripe,adyen,globalpay,multisafepay,nexinets,aci" +bank_redirect.sofort.connector_list = "globalpay,aci,multisafepay" +bank_redirect.giropay.connector_list = "globalpay,multisafepay,nexinets,aci" bank_redirect.bancontact_card.connector_list="adyen,stripe" bank_redirect.trustly.connector_list="adyen,aci" bank_redirect.open_banking_uk.connector_list="adyen" @@ -486,8 +486,8 @@ multibanco = { country = "PT", currency = "EUR" } ach = { country = "US", currency = "USD" } [pm_filters.cybersource] -credit = { currency = "USD,GBP,EUR,PLN,SEK" } -debit = { currency = "USD,GBP,EUR,PLN,SEK" } +credit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } +debit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } apple_pay = { currency = "ARS, CAD, CLP, COP, CNY, EUR, HKD, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, GBP, AED, USD, PLN, SEK" } google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } samsung_pay = { currency = "USD,GBP,EUR,SEK" } @@ -799,8 +799,8 @@ billing_connectors_which_requires_invoice_sync_call = "recurly" [revenue_recovery] -monitoring_threshold_in_seconds = 2592000 -retry_algorithm_type = "cascading" +monitoring_threshold_in_seconds = 2592000 +retry_algorithm_type = "cascading" [authentication_providers] -click_to_pay = {connector_list = "adyen, cybersource, trustpay"} \ No newline at end of file +click_to_pay = {connector_list = "adyen, cybersource, trustpay"} diff --git a/config/deployments/production.toml b/config/deployments/production.toml index b95384f66ea..18c608db765 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -219,17 +219,17 @@ bank_redirect.trustly.connector_list = "adyen" bank_redirect.open_banking_uk.connector_list = "adyen" [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" } +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,xendit,moneris,archipel,worldpayvantiv,payload" 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,xendit,moneris,archipel,worldpayvantiv,payload" -pay_later.klarna.connector_list = "adyen,aci" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet,wellsfargo" +pay_later.klarna.connector_list = "adyen,aci" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet,wellsfargo" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet,wellsfargo" -wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal,authorizedotnet" +wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet,wellsfargo" +wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal,authorizedotnet" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" wallet.go_pay.connector_list = "adyen" @@ -238,17 +238,17 @@ 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,aci" -bank_redirect.sofort.connector_list = "globalpay,aci,multisafepay" -bank_redirect.giropay.connector_list = "globalpay,multisafepay,nexinets,aci" +bank_redirect.ideal.connector_list = "stripe,adyen,globalpay,multisafepay,nexinets,aci" +bank_redirect.sofort.connector_list = "globalpay,aci,multisafepay" +bank_redirect.giropay.connector_list = "globalpay,multisafepay,nexinets,aci" bank_redirect.bancontact_card.connector_list="adyen,stripe" bank_redirect.trustly.connector_list="adyen,aci" bank_redirect.open_banking_uk.connector_list="adyen" bank_redirect.eps.connector_list="globalpay,nexinets,aci,multisafepay" [mandates.update_mandate_supported] -card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card -card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card +card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card +card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card [network_transaction_id_supported_connectors] connector_list = "adyen,archipel,stripe,worldpayvantiv" @@ -420,8 +420,8 @@ google_pay = { currency = "USD" } samsung_pay = { currency = "USD" } [pm_filters.cybersource] -credit = { currency = "USD,GBP,EUR,PLN,SEK" } -debit = { currency = "USD,GBP,EUR,PLN,SEK" } +credit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } +debit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } apple_pay = { currency = "ARS, CAD, CLP, COP, CNY, EUR, HKD, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, GBP, AED, USD, PLN, SEK" } google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } samsung_pay = { currency = "USD,GBP,EUR,SEK" } @@ -812,5 +812,5 @@ click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [revenue_recovery] -monitoring_threshold_in_seconds = 2592000 -retry_algorithm_type = "cascading" \ No newline at end of file +monitoring_threshold_in_seconds = 2592000 +retry_algorithm_type = "cascading" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 42b2db3250f..ef373e58aec 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -226,17 +226,17 @@ bank_redirect.trustly.connector_list = "adyen" bank_redirect.open_banking_uk.connector_list = "adyen" [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" } +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,xendit,moneris,archipel,worldpayvantiv,payload" 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,xendit,moneris,archipel,worldpayvantiv,payload" -pay_later.klarna.connector_list = "adyen,aci" -wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet,wellsfargo" +pay_later.klarna.connector_list = "adyen,aci" +wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet,wellsfargo" wallet.samsung_pay.connector_list = "cybersource" -wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet,wellsfargo" -wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal,authorizedotnet" +wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet,wellsfargo" +wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal,authorizedotnet" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" wallet.go_pay.connector_list = "adyen" @@ -245,17 +245,17 @@ 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,aci" -bank_redirect.sofort.connector_list = "globalpay,aci,multisafepay" -bank_redirect.giropay.connector_list = "globalpay,multisafepay,nexinets,aci" +bank_redirect.ideal.connector_list = "stripe,adyen,globalpay,multisafepay,nexinets,aci" +bank_redirect.sofort.connector_list = "globalpay,aci,multisafepay" +bank_redirect.giropay.connector_list = "globalpay,multisafepay,nexinets,aci" bank_redirect.bancontact_card.connector_list="adyen,stripe" bank_redirect.trustly.connector_list="adyen,aci" bank_redirect.open_banking_uk.connector_list="adyen" bank_redirect.eps.connector_list="globalpay,nexinets,aci,multisafepay" [mandates.update_mandate_supported] -card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card -card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card +card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card +card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card [network_transaction_id_supported_connectors] connector_list = "adyen,archipel,cybersource,novalnet,stripe,worldpay,worldpayvantiv" @@ -429,8 +429,8 @@ google_pay = { currency = "USD" } samsung_pay = { currency = "USD" } [pm_filters.cybersource] -credit = { currency = "USD,GBP,EUR,PLN,SEK" } -debit = { currency = "USD,GBP,EUR,PLN,SEK" } +credit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } +debit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } apple_pay = { currency = "ARS, CAD, CLP, COP, CNY, EUR, HKD, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, GBP, AED, USD, PLN, SEK" } google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } samsung_pay = { currency = "USD,GBP,EUR,SEK" } @@ -817,5 +817,5 @@ billing_connectors_which_requires_invoice_sync_call = "recurly" click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [revenue_recovery] -monitoring_threshold_in_seconds = 2592000 -retry_algorithm_type = "cascading" \ No newline at end of file +monitoring_threshold_in_seconds = 2592000 +retry_algorithm_type = "cascading" diff --git a/config/development.toml b/config/development.toml index b3ebb0bcb3a..d83b8b30643 100644 --- a/config/development.toml +++ b/config/development.toml @@ -580,8 +580,8 @@ google_pay = { currency = "USD" } samsung_pay = { currency = "USD" } [pm_filters.cybersource] -credit = { currency = "USD,GBP,EUR,PLN,SEK" } -debit = { currency = "USD,GBP,EUR,PLN,SEK" } +credit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } +debit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } apple_pay = { currency = "ARS, CAD, CLP, COP, CNY, EUR, HKD, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, GBP, AED, USD, PLN, SEK" } google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } samsung_pay = { currency = "USD,GBP,EUR,SEK" } @@ -1249,4 +1249,4 @@ version = "HOSTNAME" [chat] enabled = false -hyperswitch_ai_host = "http://0.0.0.0:8000" \ No newline at end of file +hyperswitch_ai_host = "http://0.0.0.0:8000" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index f22680dd373..dc68c57e739 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -615,8 +615,8 @@ google_pay = { currency = "USD" } samsung_pay = { currency = "USD" } [pm_filters.cybersource] -credit = { currency = "USD,GBP,EUR,PLN,SEK" } -debit = { currency = "USD,GBP,EUR,PLN,SEK" } +credit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } +debit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } apple_pay = { currency = "ARS, CAD, CLP, COP, CNY, EUR, HKD, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, GBP, AED, USD, PLN, SEK" } google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } samsung_pay = { currency = "USD,GBP,EUR,SEK" } @@ -1138,7 +1138,7 @@ click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [revenue_recovery] monitoring_threshold_in_seconds = 2592000 # threshold for monitoring the retry system -retry_algorithm_type = "cascading" # type of retry algorithm +retry_algorithm_type = "cascading" # type of retry algorithm [clone_connector_allowlist] merchant_ids = "merchant_123, merchant_234" # Comma-separated list of allowed merchant IDs @@ -1146,4 +1146,4 @@ connector_names = "stripe, adyen" # Comma-separated list of allowe [infra_values] cluster = "CLUSTER" # value of CLUSTER from deployment -version = "HOSTNAME" # value of HOSTNAME from deployment which tells its version \ No newline at end of file +version = "HOSTNAME" # value of HOSTNAME from deployment which tells its version diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 64ad0ee79c7..eb16ebc37cf 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -331,6 +331,14 @@ credit = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IS,IE,IT,LV,LI,LT,L google_pay = { country = "AL, DZ, AS, AO, AG, AR, AU, AT, AZ, BH, BY, BE, BR, CA, BG, CL, CO, HR, DK, DO, EE, EG, FI, FR, DE, GR, HK, HU, IN, ID, IE, IL, IT, JP, JO, KZ, KE, KW, LV, LB, LT, LU, MY, MX, NL, NZ, NO, OM, PK, PA, PE, PH, PL, PT, QA, RO, SA, SG, SK, ZA, ES, LK, SE, CH, TH, TW, TR, UA, AE, US, UY, VN", currency = "AED, ALL, AOA, AUD, AZN, BGN, BHD, BRL, CAD, CHF, CLP, COP, CZK, DKK, DOP, DZD, EGP, EUR, GBP, HKD, HUF, IDR, ILS, INR, JPY, KES, KWD, KZT, LKR, MXN, MYR, NOK, NZD, OMR, PAB, PEN, PHP, PKR, PLN, QAR, RON, SAR, SEK, SGD, THB, TRY, TWD, UAH, USD, UYU, VND, XCD, ZAR" } apple_pay = { country = "AM, AT, AZ, BY, BE, BG, HR, CY, 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, VA, AU , HK, JP , MY , MN, NZ, SG, TW, VN, EG , MA, ZA, AR, BR, CL, CO, CR, DO, EC, SV, GT, HN, MX, PA, PY, PE, UY, BH, IL, JO, KW, OM,QA, SA, AE, CA", currency = "EGP, MAD, ZAR, AUD, CNY, HKD, JPY, MOP, MYR, MNT, NZD, SGD, KRW, TWD, VND, AMD, EUR, BGN, CZK, DKK, GEL, GBP, HUF, ISK, KZT, CHF, MDL, NOK, PLN, RON, RSD, SEK, UAH, BRL, COP, CRC, DOP, GTQ, HNL, MXN, PAB, PYG, PEN, BSD, UYU, BHD, ILS, JOD, KWD, OMR, QAR, SAR, AED, CAD, USD" } +[pm_filters.cybersource] +credit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } +debit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } +apple_pay = { currency = "ARS, CAD, CLP, COP, CNY, EUR, HKD, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, GBP, AED, USD, PLN, SEK" } +google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } +samsung_pay = { currency = "USD,GBP,EUR,SEK" } +paze = { currency = "USD,SEK" } + [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" } @@ -741,5 +749,5 @@ billing_connectors_which_require_payment_sync = "stripebilling, recurly" billing_connectors_which_requires_invoice_sync_call = "recurly" [chat] -enabled = false -hyperswitch_ai_host = "http://0.0.0.0:8000" \ No newline at end of file +enabled = false +hyperswitch_ai_host = "http://0.0.0.0:8000"
2025-07-30T09:35:02Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [x] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> this pr adds `xof` currency to cybersource 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). --> one of the user asked for it. closes https://github.com/juspay/hyperswitch/issues/8805 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> just a config update. shouldn't break cybersource ci. payment should go through xof currency as shown below: ```sh curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: en' \ --header 'api-key: dev_vfGawKctyn48cifxIDntCEKn12ZbQmsRDtQ5xiNGP67pTt9lAOdqRlQ4XyqORYYJ' \ --data-raw '{ "amount": 1000, "currency": "XOF", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "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_rlOK4wlqDCfWFVxDNjaM", "merchant_id": "postman_merchant_GHAction_1753874384", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "cybersource", "client_secret": "pay_rlOK4wlqDCfWFVxDNjaM_secret_ZEh3kZgU2YmRqH9z7RTJ", "created": "2025-07-30T11:20:12.546Z", "currency": "XOF", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": null }, "authentication_data": null }, "billing": null }, "payment_token": "token_94ft81ede4d6V4WtntFL", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "sundari", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1753874412, "expires": 1753878012, "secret": "epk_7a410167529f41909ed1137a0ad05e97" }, "manual_retry_allowed": false, "connector_transaction_id": "7538744140166402803814", "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_rlOK4wlqDCfWFVxDNjaM_1", "payment_link": null, "profile_id": "pro_eCGWWqBo5rM0do2jB2Xg", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_Wif1Z3hnHhmeO7RYZ1ev", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-30T11:35:12.545Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-07-30T11:20:15.301Z", "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, "is_iframe_redirection_enabled": null, "whole_connector_response": 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 `just clippy && just clippy_v2` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.115.0
794dce168e6b4d280c9c742a6e8a3b3283e09602
794dce168e6b4d280c9c742a6e8a3b3283e09602
juspay/hyperswitch
juspay__hyperswitch-8804
Bug: [FEATURE] Request fields to be populated on top level ### Feature Description Few fields of request to be passed on to top level for certain operations ### Possible Implementation parse the value and then add it to the events ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index d4eb34838d6..4f53a2ef2df 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -547,5 +547,6 @@ pub(crate) async fn fetch_raw_secrets( clone_connector_allowlist: conf.clone_connector_allowlist, merchant_id_auth: conf.merchant_id_auth, infra_values: conf.infra_values, + enhancement: conf.enhancement, } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index ae4c8a3cda0..6e4454063ce 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -162,6 +162,8 @@ pub struct Settings<S: SecretState> { pub merchant_id_auth: MerchantIdAuthSettings, #[serde(default)] pub infra_values: Option<HashMap<String, String>>, + #[serde(default)] + pub enhancement: Option<HashMap<String, String>>, } #[derive(Debug, Deserialize, Clone, Default)] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index cb731c43717..f52b0d44c80 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -132,6 +132,7 @@ pub struct SessionState { pub locale: String, pub crm_client: Arc<dyn CrmInterface>, pub infra_components: Option<serde_json::Value>, + pub enhancement: Option<HashMap<String, String>>, } impl scheduler::SchedulerSessionState for SessionState { fn get_db(&self) -> Box<dyn SchedulerInterface> { @@ -245,6 +246,7 @@ pub struct AppState { pub theme_storage_client: Arc<dyn FileStorageInterface>, pub crm_client: Arc<dyn CrmInterface>, pub infra_components: Option<serde_json::Value>, + pub enhancement: Option<HashMap<String, String>>, } impl scheduler::SchedulerAppState for AppState { fn get_tenants(&self) -> Vec<id_type::TenantId> { @@ -410,6 +412,7 @@ impl AppState { let grpc_client = conf.grpc_client.get_grpc_client_interface().await; let infra_component_values = Self::process_env_mappings(conf.infra_values.clone()); + let enhancement = conf.enhancement.clone(); Self { flow_name: String::from("default"), stores, @@ -431,6 +434,7 @@ impl AppState { theme_storage_client, crm_client, infra_components: infra_component_values, + enhancement, } }) .await @@ -526,6 +530,7 @@ impl AppState { locale: locale.unwrap_or(common_utils::consts::DEFAULT_LOCALE.to_string()), crm_client: self.crm_client.clone(), infra_components: self.infra_components.clone(), + enhancement: self.enhancement.clone(), }) } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 9b6c091a577..792edb71997 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -701,7 +701,11 @@ where } }; - let infra = state.infra_components.clone(); + let infra = extract_mapped_fields( + &serialized_request, + state.enhancement.as_ref(), + state.infra_components.as_ref(), + ); let api_event = ApiEvent::new( tenant_id, @@ -2065,6 +2069,64 @@ pub fn get_payment_link_status( } } +pub fn extract_mapped_fields( + value: &serde_json::Value, + mapping: Option<&HashMap<String, String>>, + existing_enhancement: Option<&serde_json::Value>, +) -> Option<serde_json::Value> { + let mapping = mapping?; + + if mapping.is_empty() { + return existing_enhancement.cloned(); + } + + let mut enhancement = match existing_enhancement { + Some(existing) if existing.is_object() => existing.clone(), + _ => serde_json::json!({}), + }; + + for (dot_path, output_key) in mapping { + if let Some(extracted_value) = extract_field_by_dot_path(value, dot_path) { + if let Some(obj) = enhancement.as_object_mut() { + obj.insert(output_key.clone(), extracted_value); + } + } + } + + if enhancement.as_object().is_some_and(|obj| !obj.is_empty()) { + Some(enhancement) + } else { + None + } +} + +pub fn extract_field_by_dot_path( + value: &serde_json::Value, + path: &str, +) -> Option<serde_json::Value> { + let parts: Vec<&str> = path.split('.').collect(); + let mut current = value; + + for part in parts { + match current { + serde_json::Value::Object(obj) => { + current = obj.get(part)?; + } + serde_json::Value::Array(arr) => { + // Try to parse part as array index + if let Ok(index) = part.parse::<usize>() { + current = arr.get(index)?; + } else { + return None; + } + } + _ => return None, + } + } + + Some(current.clone()) +} + #[cfg(test)] mod tests { #[test]
2025-07-29T06:12:18Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This feature allows based on deployment config , it is able to query Request Body and add as a top level fields in the Kafka events ### 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). --> We wanted a feature where we could add fields from Request Body to top level fields in kafka events irrespective of the flow ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Test 1 In ```development.toml``` ```bash [enhancement] "merchant_reference_id" = "txn_uuid" ``` <img width="540" height="732" alt="Screenshot 2025-07-29 at 11 40 30β€―AM" src="https://github.com/user-attachments/assets/8eb747d8-7bc7-441f-8cb3-e1d992ee1671" /> ```json { "tenant_id": "public", "merchant_id": "cloth_seller_kGLq5ZsmKL6hISw8HI9A", "api_flow": "PaymentsCreateIntent", "created_at_timestamp": 1753767564159, "request_id": "019854b1-52c2-7080-ab7f-114e169fc92b", "latency": 170, "status_code": 200, "api_auth_type": "api_key", "authentication_data": { "merchant_id": "cloth_seller_kGLq5ZsmKL6hISw8HI9A", "key_id": "dev_ekHYWGqV5It7fLj62AOa" }, "request": "{\"amount_details\":{\"order_amount\":{\"Value\":100},\"currency\":\"USD\",\"shipping_cost\":null,\"order_tax_amount\":null,\"skip_external_tax_calculation\":\"skip\",\"skip_surcharge_calculation\":\"skip\",\"surcharge_amount\":null,\"tax_on_surcharge\":null},\"merchant_reference_id\":\"NOPA\",\"routing_algorithm_id\":null,\"capture_method\":\"manual\",\"authentication_type\":\"no_three_ds\",\"billing\":{\"address\":{\"city\":\"test\",\"country\":\"NL\",\"line1\":\"*** alloc::string::String ***\",\"line2\":\"*** alloc::string::String ***\",\"line3\":\"*** alloc::string::String ***\",\"zip\":\"*** alloc::string::String ***\",\"state\":\"*** alloc::string::String ***\",\"first_name\":\"*** alloc::string::String ***\",\"last_name\":\"*** alloc::string::String ***\"},\"phone\":{\"number\":\"*** alloc::string::String ***\",\"country_code\":\"+1\"},\"email\":\"*****@example.com\"},\"shipping\":{\"address\":{\"city\":\"Karwar\",\"country\":\"NL\",\"line1\":null,\"line2\":null,\"line3\":null,\"zip\":\"*** alloc::string::String ***\",\"state\":\"*** alloc::string::String ***\",\"first_name\":\"*** alloc::string::String ***\",\"last_name\":\"*** alloc::string::String ***\"},\"phone\":null,\"email\":\"*******@example.com\"},\"customer_id\":\"12345_cus_019841789b727750b33d014ce2fabf10\",\"customer_present\":null,\"description\":null,\"return_url\":null,\"setup_future_usage\":null,\"apply_mit_exemption\":null,\"statement_descriptor\":null,\"order_details\":null,\"allowed_payment_method_types\":null,\"metadata\":null,\"connector_metadata\":null,\"feature_metadata\":null,\"payment_link_enabled\":null,\"payment_link_config\":null,\"request_incremental_authorization\":null,\"session_expiry\":null,\"frm_metadata\":null,\"request_external_three_ds_authentication\":null,\"force_3ds_challenge\":null,\"merchant_connector_details\":null}", "user_agent": "PostmanRuntime/7.44.1", "ip_addr": "::1", "url_path": "/v2/payments/create-intent", "response": "{\"id\":\"12345_pay_019854b152cf7bc2b538db792c40bcc6\",\"status\":\"requires_payment_method\",\"amount_details\":{\"order_amount\":100,\"currency\":\"USD\",\"shipping_cost\":null,\"order_tax_amount\":null,\"external_tax_calculation\":\"skip\",\"surcharge_calculation\":\"skip\",\"surcharge_amount\":null,\"tax_on_surcharge\":null},\"client_secret\":\"*** alloc::string::String ***\",\"profile_id\":\"pro_uJBgizwyNrvQmKZVxuUo\",\"merchant_reference_id\":\"NOPA\",\"routing_algorithm_id\":null,\"capture_method\":\"manual\",\"authentication_type\":\"no_three_ds\",\"billing\":{\"address\":{\"city\":\"test\",\"country\":\"NL\",\"line1\":\"*** alloc::string::String ***\",\"line2\":\"*** alloc::string::String ***\",\"line3\":\"*** alloc::string::String ***\",\"zip\":\"*** alloc::string::String ***\",\"state\":\"*** alloc::string::String ***\",\"first_name\":\"*** alloc::string::String ***\",\"last_name\":\"*** alloc::string::String ***\"},\"phone\":{\"number\":\"*** alloc::string::String ***\",\"country_code\":\"+1\"},\"email\":\"*****@example.com\"},\"shipping\":{\"address\":{\"city\":\"Karwar\",\"country\":\"NL\",\"line1\":null,\"line2\":null,\"line3\":null,\"zip\":\"*** alloc::string::String ***\",\"state\":\"*** alloc::string::String ***\",\"first_name\":\"*** alloc::string::String ***\",\"last_name\":\"*** alloc::string::String ***\"},\"phone\":null,\"email\":\"*******@example.com\"},\"customer_id\":\"12345_cus_019841789b727750b33d014ce2fabf10\",\"customer_present\":\"present\",\"description\":null,\"return_url\":null,\"setup_future_usage\":\"on_session\",\"apply_mit_exemption\":\"Skip\",\"statement_descriptor\":null,\"order_details\":null,\"allowed_payment_method_types\":null,\"metadata\":null,\"connector_metadata\":null,\"feature_metadata\":null,\"payment_link_enabled\":\"Skip\",\"payment_link_config\":null,\"request_incremental_authorization\":\"default\",\"expires_on\":\"2025-07-29T05:54:24.111Z\",\"frm_metadata\":null,\"request_external_three_ds_authentication\":\"Skip\"}", "error": null, "flow_type": "payment", "payment_id": "12345_pay_019854b152cf7bc2b538db792c40bcc6", "hs_latency": null, "http_method": "POST", "cluster": "my_own_cluster", "txn_uuid": "NOPA" } ``` Test 2 In ```development.toml``` ```bash [enhancement] "merchant_reference_id" = "udf_txn_uuid" "shipping.address.country" = "country" ``` ```json { "tenant_id": "public", "merchant_id": "cloth_seller_PdFuIUDbxVwvu7kZJ3DC", "api_flow": "PaymentsCreateIntent", "created_at_timestamp": 1753795822163, "request_id": "01985660-8135-7422-afa3-9c4aa8c4ff23", "latency": 264, "status_code": 200, "api_auth_type": "api_key", "authentication_data": { "merchant_id": "cloth_seller_PdFuIUDbxVwvu7kZJ3DC", "key_id": "dev_SImQYDU2oDTEQ9RqnY4R" }, "request": "{\"amount_details\":{\"order_amount\":{\"Value\":100},\"currency\":\"USD\",\"shipping_cost\":null,\"order_tax_amount\":null,\"skip_external_tax_calculation\":\"skip\",\"skip_surcharge_calculation\":\"skip\",\"surcharge_amount\":null,\"tax_on_surcharge\":null},\"merchant_reference_id\":\"NOPA\",\"routing_algorithm_id\":null,\"capture_method\":\"manual\",\"authentication_type\":\"no_three_ds\",\"billing\":{\"address\":{\"city\":\"test\",\"country\":\"NL\",\"line1\":\"*** alloc::string::String ***\",\"line2\":\"*** alloc::string::String ***\",\"line3\":\"*** alloc::string::String ***\",\"zip\":\"*** alloc::string::String ***\",\"state\":\"*** alloc::string::String ***\",\"first_name\":\"*** alloc::string::String ***\",\"last_name\":\"*** alloc::string::String ***\"},\"phone\":{\"number\":\"*** alloc::string::String ***\",\"country_code\":\"+1\"},\"email\":\"*****@example.com\"},\"shipping\":{\"address\":{\"city\":\"Karwar\",\"country\":\"NL\",\"line1\":null,\"line2\":null,\"line3\":null,\"zip\":\"*** alloc::string::String ***\",\"state\":\"*** alloc::string::String ***\",\"first_name\":\"*** alloc::string::String ***\",\"last_name\":\"*** alloc::string::String ***\"},\"phone\":null,\"email\":\"*******@example.com\"},\"customer_id\":\"12345_cus_019854ddfc4179a1b56936f3ef50cf48\",\"customer_present\":null,\"description\":null,\"return_url\":null,\"setup_future_usage\":null,\"apply_mit_exemption\":null,\"statement_descriptor\":null,\"order_details\":null,\"allowed_payment_method_types\":null,\"metadata\":\"*** serde_json::value::Value ***\",\"connector_metadata\":null,\"feature_metadata\":null,\"payment_link_enabled\":null,\"payment_link_config\":null,\"request_incremental_authorization\":null,\"session_expiry\":null,\"frm_metadata\":null,\"request_external_three_ds_authentication\":null,\"force_3ds_challenge\":null,\"merchant_connector_details\":null}", "user_agent": "PostmanRuntime/7.44.1", "ip_addr": "::1", "url_path": "/v2/payments/create-intent", "response": "{\"id\":\"12345_pay_0198566081457b12a4925e86e34cbe96\",\"status\":\"requires_payment_method\",\"amount_details\":{\"order_amount\":100,\"currency\":\"USD\",\"shipping_cost\":null,\"order_tax_amount\":null,\"external_tax_calculation\":\"skip\",\"surcharge_calculation\":\"skip\",\"surcharge_amount\":null,\"tax_on_surcharge\":null},\"client_secret\":\"*** alloc::string::String ***\",\"profile_id\":\"pro_LWkFikerdXPyjg0lghL3\",\"merchant_reference_id\":\"NOPA\",\"routing_algorithm_id\":null,\"capture_method\":\"manual\",\"authentication_type\":\"no_three_ds\",\"billing\":{\"address\":{\"city\":\"test\",\"country\":\"NL\",\"line1\":\"*** alloc::string::String ***\",\"line2\":\"*** alloc::string::String ***\",\"line3\":\"*** alloc::string::String ***\",\"zip\":\"*** alloc::string::String ***\",\"state\":\"*** alloc::string::String ***\",\"first_name\":\"*** alloc::string::String ***\",\"last_name\":\"*** alloc::string::String ***\"},\"phone\":{\"number\":\"*** alloc::string::String ***\",\"country_code\":\"+1\"},\"email\":\"*****@example.com\"},\"shipping\":{\"address\":{\"city\":\"Karwar\",\"country\":\"NL\",\"line1\":null,\"line2\":null,\"line3\":null,\"zip\":\"*** alloc::string::String ***\",\"state\":\"*** alloc::string::String ***\",\"first_name\":\"*** alloc::string::String ***\",\"last_name\":\"*** alloc::string::String ***\"},\"phone\":null,\"email\":\"*******@example.com\"},\"customer_id\":\"12345_cus_019854ddfc4179a1b56936f3ef50cf48\",\"customer_present\":\"present\",\"description\":null,\"return_url\":null,\"setup_future_usage\":\"on_session\",\"apply_mit_exemption\":\"Skip\",\"statement_descriptor\":null,\"order_details\":null,\"allowed_payment_method_types\":null,\"metadata\":\"*** serde_json::value::Value ***\",\"connector_metadata\":null,\"feature_metadata\":null,\"payment_link_enabled\":\"Skip\",\"payment_link_config\":null,\"request_incremental_authorization\":\"default\",\"expires_on\":\"2025-07-29T13:45:22.074Z\",\"frm_metadata\":null,\"request_external_three_ds_authentication\":\"Skip\"}", "error": null, "flow_type": "payment", "payment_id": "12345_pay_0198566081457b12a4925e86e34cbe96", "hs_latency": null, "http_method": "POST", "country": "NL", "udf_txn_uuid": "NOPA" } ``` ## 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.115.0
1e6a088c04b40c7fdd5bc65c1973056bf58de764
1e6a088c04b40c7fdd5bc65c1973056bf58de764
juspay/hyperswitch
juspay__hyperswitch-8798
Bug: [FEAT] Set up CI to support mock server for alpha connectors flow should be: - build hyperswitch router - upload it to artifact - download artifact - start the server - run mandatory tests - download artifact - start mock server with node - start server - run optional mock server tests
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 7591fb65fba..9a45e70a749 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -11746,6 +11746,7 @@ "redsys", "santander", "shift4", + "silverflow", "square", "stax", "stripe", @@ -29262,6 +29263,7 @@ "santander", "shift4", "signifyd", + "silverflow", "square", "stax", "stripe", diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 6602d2e2814..b200be3de51 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -8308,6 +8308,7 @@ "redsys", "santander", "shift4", + "silverflow", "square", "stax", "stripe", @@ -23115,6 +23116,7 @@ "santander", "shift4", "signifyd", + "silverflow", "square", "stax", "stripe", diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index c3741e0f5ea..39178d15eb9 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -145,6 +145,7 @@ pub enum RoutableConnectors { Santander, Shift4, Signifyd, + Silverflow, Square, Stax, Stripe, @@ -315,6 +316,7 @@ pub enum Connector { Redsys, Santander, Shift4, + Silverflow, Square, Stax, Stripe, @@ -495,6 +497,7 @@ impl Connector { | Self::Redsys | Self::Santander | Self::Shift4 + | Self::Silverflow | Self::Square | Self::Stax | Self::Stripebilling @@ -668,6 +671,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Santander => Self::Santander, RoutableConnectors::Shift4 => Self::Shift4, RoutableConnectors::Signifyd => Self::Signifyd, + RoutableConnectors::Silverflow => Self::Silverflow, RoutableConnectors::Square => Self::Square, RoutableConnectors::Stax => Self::Stax, RoutableConnectors::Stripe => Self::Stripe, @@ -795,6 +799,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Santander => Ok(Self::Santander), Connector::Shift4 => Ok(Self::Shift4), Connector::Signifyd => Ok(Self::Signifyd), + Connector::Silverflow => Ok(Self::Silverflow), Connector::Square => Ok(Self::Square), Connector::Stax => Ok(Self::Stax), Connector::Stripe => Ok(Self::Stripe), diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 84e7398f61c..4ee90a17469 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -465,6 +465,7 @@ impl ConnectorConfig { Connector::Santander => Ok(connector_data.santander), Connector::Shift4 => Ok(connector_data.shift4), Connector::Signifyd => Ok(connector_data.signifyd), + Connector::Silverflow => Ok(connector_data.silverflow), Connector::Square => Ok(connector_data.square), Connector::Stax => Ok(connector_data.stax), Connector::Stripe => Ok(connector_data.stripe), diff --git a/crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs b/crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs index 87a99417dd6..2d56fa4e61c 100644 --- a/crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs @@ -17,7 +17,7 @@ use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, - utils::CardData, + utils::{self, CardData}, }; //TODO: Fill the struct with respective fields @@ -67,6 +67,7 @@ pub struct SilverflowPaymentsRequest { amount: Amount, #[serde(rename = "type")] payment_type: PaymentType, + clearing_mode: String, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -82,6 +83,17 @@ impl TryFrom<&SilverflowRouterData<&PaymentsAuthorizeRouterData>> for Silverflow fn try_from( item: &SilverflowRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { + // Check if 3DS is being requested - Silverflow doesn't support 3DS + if matches!( + item.router_data.auth_type, + enums::AuthenticationType::ThreeDs + ) { + return Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("silverflow"), + ) + .into()); + } + match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(req_card) => { // Extract merchant acceptor key from connector auth @@ -95,6 +107,21 @@ impl TryFrom<&SilverflowRouterData<&PaymentsAuthorizeRouterData>> for Silverflow holder_name: req_card.get_cardholder_name().ok(), }; + // Determine clearing mode based on capture method + let clearing_mode = match item.router_data.request.capture_method { + Some(enums::CaptureMethod::Manual) => "manual".to_string(), + Some(enums::CaptureMethod::Automatic) | None => "auto".to_string(), + Some(enums::CaptureMethod::ManualMultiple) + | Some(enums::CaptureMethod::Scheduled) + | Some(enums::CaptureMethod::SequentialAutomatic) => { + return Err(errors::ConnectorError::NotSupported { + message: "Capture method not supported by Silverflow".to_string(), + connector: "Silverflow", + } + .into()); + } + }; + Ok(Self { merchant_acceptor_resolver: MerchantAcceptorResolver { merchant_acceptor_key: auth.merchant_acceptor_key.expose(), @@ -109,9 +136,13 @@ impl TryFrom<&SilverflowRouterData<&PaymentsAuthorizeRouterData>> for Silverflow card_entry: "e-commerce".to_string(), order: "checkout".to_string(), }, + clearing_mode, }) } - _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("silverflow"), + ) + .into()), } } } @@ -636,7 +667,10 @@ impl TryFrom<&PaymentsAuthorizeRouterData> for SilverflowTokenizationRequest { card_data, }) } - _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("silverflow"), + ) + .into()), } } } @@ -677,7 +711,10 @@ impl card_data, }) } - _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("silverflow"), + ) + .into()), } } } diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs index 469b27baf8c..70e5fa7c13b 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -1492,6 +1492,7 @@ fn get_cards_required_fields() -> HashMap<Connector, RequiredFieldFinal> { (Connector::Rapyd, fields(vec![], card_with_name(), vec![])), (Connector::Redsys, fields(vec![], card_basic(), vec![])), (Connector::Shift4, fields(vec![], card_basic(), vec![])), + (Connector::Silverflow, fields(vec![], vec![], card_basic())), (Connector::Square, fields(vec![], vec![], card_basic())), (Connector::Stax, fields(vec![], card_with_name(), vec![])), (Connector::Stripe, fields(vec![], vec![], card_basic())), diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rs index 99b873af1dc..8bd9cf6fc9c 100644 --- a/crates/router/src/core/connector_validation.rs +++ b/crates/router/src/core/connector_validation.rs @@ -431,6 +431,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { shift4::transformers::Shift4AuthType::try_from(self.auth_type)?; Ok(()) } + api_enums::Connector::Silverflow => { + silverflow::transformers::SilverflowAuthType::try_from(self.auth_type)?; + Ok(()) + } api_enums::Connector::Square => { square::transformers::SquareAuthType::try_from(self.auth_type)?; Ok(()) diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs index c4a1f187dd9..75ff6bc10ce 100644 --- a/crates/router/src/types/api/connector_mapping.rs +++ b/crates/router/src/types/api/connector_mapping.rs @@ -364,6 +364,9 @@ impl ConnectorData { enums::Connector::Shift4 => { Ok(ConnectorEnum::Old(Box::new(connector::Shift4::new()))) } + enums::Connector::Silverflow => { + Ok(ConnectorEnum::Old(Box::new(connector::Silverflow::new()))) + } enums::Connector::Square => Ok(ConnectorEnum::Old(Box::new(&connector::Square))), enums::Connector::Stax => Ok(ConnectorEnum::Old(Box::new(&connector::Stax))), enums::Connector::Stripe => { diff --git a/crates/router/src/types/connector_transformers.rs b/crates/router/src/types/connector_transformers.rs index 2563f87191c..ea84e3cbd7f 100644 --- a/crates/router/src/types/connector_transformers.rs +++ b/crates/router/src/types/connector_transformers.rs @@ -120,6 +120,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Redsys => Self::Redsys, api_enums::Connector::Santander => Self::Santander, api_enums::Connector::Shift4 => Self::Shift4, + api_enums::Connector::Silverflow => Self::Silverflow, api_enums::Connector::Signifyd => { Err(common_utils::errors::ValidationError::InvalidValue { message: "signifyd is not a routable connector".to_string(),
2025-07-24T07:35:22Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds support for running tests against mock server for alpha connectors. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> The goal is to make sure that the implementation works. closes https://github.com/juspay/hyperswitch/issues/8798 ## 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 / work. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `just clippy && just clippy_v2` - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible
v1.115.0
bc4d29a3e5ee24b14b32262449a7b640e9f6edaf
bc4d29a3e5ee24b14b32262449a7b640e9f6edaf
juspay/hyperswitch
juspay__hyperswitch-8792
Bug: [FEATURE] Add Payments - List endpoint for v2 ### Feature Description This feature adds support for retrieving a filtered list of payments via a GET /v2/payments/list endpoint where multiple values can be provided for a single filter key (e.g. connector, etc.). ### Possible Implementation Add PaymentListFilterConstraints and payments_list_by_filter endpoint for v2 ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 02dbdddf4a3..17a6b572b2e 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -2441,11 +2441,10 @@ "description": "The connector to filter payments list", "required": true, "schema": { - "allOf": [ - { - "$ref": "#/components/schemas/Connector" - } - ], + "type": "array", + "items": { + "$ref": "#/components/schemas/Connector" + }, "nullable": true } }, @@ -2455,11 +2454,10 @@ "description": "The currency to filter payments list", "required": true, "schema": { - "allOf": [ - { - "$ref": "#/components/schemas/Currency" - } - ], + "type": "array", + "items": { + "$ref": "#/components/schemas/Currency" + }, "nullable": true } }, @@ -2469,11 +2467,10 @@ "description": "The payment status to filter payments list", "required": true, "schema": { - "allOf": [ - { - "$ref": "#/components/schemas/IntentStatus" - } - ], + "type": "array", + "items": { + "$ref": "#/components/schemas/IntentStatus" + }, "nullable": true } }, @@ -2483,11 +2480,10 @@ "description": "The payment method type to filter payments list", "required": true, "schema": { - "allOf": [ - { - "$ref": "#/components/schemas/PaymentMethod" - } - ], + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentMethod" + }, "nullable": true } }, @@ -2497,11 +2493,10 @@ "description": "The payment method subtype to filter payments list", "required": true, "schema": { - "allOf": [ - { - "$ref": "#/components/schemas/PaymentMethodType" - } - ], + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentMethodType" + }, "nullable": true } }, @@ -2511,11 +2506,10 @@ "description": "The authentication type to filter payments list", "required": true, "schema": { - "allOf": [ - { - "$ref": "#/components/schemas/AuthenticationType" - } - ], + "type": "array", + "items": { + "$ref": "#/components/schemas/AuthenticationType" + }, "nullable": true } }, @@ -2525,7 +2519,10 @@ "description": "The merchant connector id to filter payments list", "required": true, "schema": { - "type": "string", + "type": "array", + "items": { + "type": "string" + }, "nullable": true } }, @@ -2553,11 +2550,10 @@ "description": "The card networks to filter payments list", "required": true, "schema": { - "allOf": [ - { - "$ref": "#/components/schemas/CardNetwork" - } - ], + "type": "array", + "items": { + "$ref": "#/components/schemas/CardNetwork" + }, "nullable": true } }, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 91886de2390..9090ab2b5e0 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -26,9 +26,39 @@ use common_utils::{ pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; -#[cfg(feature = "v2")] -use deserialize_form_style_query_parameter::option_form_vec_deserialize; use error_stack::ResultExt; + +#[cfg(feature = "v2")] +fn parse_comma_separated<'de, D, T>(v: D) -> Result<Option<Vec<T>>, D::Error> +where + D: serde::Deserializer<'de>, + T: std::str::FromStr, + <T as std::str::FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error, +{ + let opt_str: Option<String> = Option::deserialize(v)?; + match opt_str { + Some(s) if s.is_empty() => Ok(None), + Some(s) => { + // Estimate capacity based on comma count + let capacity = s.matches(',').count() + 1; + let mut result = Vec::with_capacity(capacity); + + for item in s.split(',') { + let trimmed_item = item.trim(); + if !trimmed_item.is_empty() { + let parsed_item = trimmed_item.parse::<T>().map_err(|e| { + <D::Error as serde::de::Error>::custom(format!( + "Invalid value '{trimmed_item}': {e}" + )) + })?; + result.push(parsed_item); + } + } + Ok(Some(result)) + } + None => Ok(None), + } +} use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; #[cfg(feature = "v1")] @@ -6259,26 +6289,33 @@ pub struct PaymentListConstraints { /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list - #[param(value_type = Option<Connector>)] - pub connector: Option<api_enums::Connector>, + #[param(value_type = Option<Vec<Connector>>)] + #[serde(deserialize_with = "parse_comma_separated", default)] + pub connector: Option<Vec<api_enums::Connector>>, /// The currency to filter payments list - #[param(value_type = Option<Currency>)] - pub currency: Option<enums::Currency>, + #[param(value_type = Option<Vec<Currency>>)] + #[serde(deserialize_with = "parse_comma_separated", default)] + pub currency: Option<Vec<enums::Currency>>, /// The payment status to filter payments list - #[param(value_type = Option<IntentStatus>)] - pub status: Option<enums::IntentStatus>, + #[param(value_type = Option<Vec<IntentStatus>>)] + #[serde(deserialize_with = "parse_comma_separated", default)] + pub status: Option<Vec<enums::IntentStatus>>, /// The payment method type to filter payments list - #[param(value_type = Option<PaymentMethod>)] - pub payment_method_type: Option<enums::PaymentMethod>, + #[param(value_type = Option<Vec<PaymentMethod>>)] + #[serde(deserialize_with = "parse_comma_separated", default)] + pub payment_method_type: Option<Vec<enums::PaymentMethod>>, /// The payment method subtype to filter payments list - #[param(value_type = Option<PaymentMethodType>)] - pub payment_method_subtype: Option<enums::PaymentMethodType>, + #[param(value_type = Option<Vec<PaymentMethodType>>)] + #[serde(deserialize_with = "parse_comma_separated", default)] + pub payment_method_subtype: Option<Vec<enums::PaymentMethodType>>, /// The authentication type to filter payments list - #[param(value_type = Option<AuthenticationType>)] - pub authentication_type: Option<enums::AuthenticationType>, + #[param(value_type = Option<Vec<AuthenticationType>>)] + #[serde(deserialize_with = "parse_comma_separated", default)] + pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The merchant connector id to filter payments list - #[param(value_type = Option<String>)] - pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, + #[param(value_type = Option<Vec<String>>)] + #[serde(deserialize_with = "parse_comma_separated", default)] + pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, @@ -6286,8 +6323,9 @@ pub struct PaymentListConstraints { #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list - #[param(value_type = Option<CardNetwork>)] - pub card_network: Option<enums::CardNetwork>, + #[param(value_type = Option<Vec<CardNetwork>>)] + #[serde(deserialize_with = "parse_comma_separated", default)] + pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } @@ -7984,7 +8022,7 @@ pub struct ListMethodsForPaymentsRequest { pub client_secret: Option<String>, /// The two-letter ISO currency code - #[serde(deserialize_with = "option_form_vec_deserialize", default)] + #[serde(deserialize_with = "parse_comma_separated", default)] #[schema(value_type = Option<Vec<CountryAlpha2>>, example = json!(["US", "UK", "IN"]))] pub accepted_countries: Option<Vec<api_enums::CountryAlpha2>>, @@ -7993,7 +8031,7 @@ pub struct ListMethodsForPaymentsRequest { pub amount: Option<MinorUnit>, /// The three-letter ISO currency code - #[serde(deserialize_with = "option_form_vec_deserialize", default)] + #[serde(deserialize_with = "parse_comma_separated", default)] #[schema(value_type = Option<Vec<Currency>>,example = json!(["USD", "EUR"]))] pub accepted_currencies: Option<Vec<api_enums::Currency>>, @@ -8002,7 +8040,7 @@ pub struct ListMethodsForPaymentsRequest { pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for card networks - #[serde(deserialize_with = "option_form_vec_deserialize", default)] + #[serde(deserialize_with = "parse_comma_separated", default)] #[schema(value_type = Option<Vec<CardNetwork>>, example = json!(["visa", "mastercard"]))] pub card_networks: Option<Vec<api_enums::CardNetwork>>, diff --git a/crates/common_utils/src/id_type/merchant_connector_account.rs b/crates/common_utils/src/id_type/merchant_connector_account.rs index f1bdb171b21..df8d1c3b3a4 100644 --- a/crates/common_utils/src/id_type/merchant_connector_account.rs +++ b/crates/common_utils/src/id_type/merchant_connector_account.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use crate::errors::{CustomResult, ValidationError}; crate::id_type!( @@ -21,3 +23,11 @@ impl MerchantConnectorAccountId { Self::try_from(std::borrow::Cow::from(merchant_connector_account_id)) } } + +impl FromStr for MerchantConnectorAccountId { + type Err = std::fmt::Error; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + Self::try_from(std::borrow::Cow::Owned(s.to_string())).map_err(|_| std::fmt::Error) + } +} diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs index a7baf75f069..b1934ae5abc 100644 --- a/crates/diesel_models/src/query/payment_attempt.rs +++ b/crates/diesel_models/src/query/payment_attempt.rs @@ -437,12 +437,12 @@ impl PaymentAttempt { conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], - connector: Option<String>, - payment_method_type: Option<enums::PaymentMethod>, - payment_method_subtype: Option<enums::PaymentMethodType>, - authentication_type: Option<enums::AuthenticationType>, - merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, - card_network: Option<enums::CardNetwork>, + connector: Option<Vec<String>>, + payment_method_type: Option<Vec<enums::PaymentMethod>>, + payment_method_subtype: Option<Vec<enums::PaymentMethodType>>, + authentication_type: Option<Vec<enums::AuthenticationType>>, + merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, + card_network: Option<Vec<enums::CardNetwork>>, ) -> StorageResult<i64> { let mut filter = <Self as HasTable>::table() .count() @@ -450,24 +450,24 @@ impl PaymentAttempt { .filter(dsl::id.eq_any(active_attempt_ids.to_owned())) .into_boxed(); - if let Some(connector) = connector { - filter = filter.filter(dsl::connector.eq(connector)); + if let Some(connectors) = connector { + filter = filter.filter(dsl::connector.eq_any(connectors)); } - if let Some(payment_method_type) = payment_method_type { - filter = filter.filter(dsl::payment_method_type_v2.eq(payment_method_type)); + if let Some(payment_method_types) = payment_method_type { + filter = filter.filter(dsl::payment_method_type_v2.eq_any(payment_method_types)); } - if let Some(payment_method_subtype) = payment_method_subtype { - filter = filter.filter(dsl::payment_method_subtype.eq(payment_method_subtype)); + if let Some(payment_method_subtypes) = payment_method_subtype { + filter = filter.filter(dsl::payment_method_subtype.eq_any(payment_method_subtypes)); } - if let Some(authentication_type) = authentication_type { - filter = filter.filter(dsl::authentication_type.eq(authentication_type)); + if let Some(authentication_types) = authentication_type { + filter = filter.filter(dsl::authentication_type.eq_any(authentication_types)); } - if let Some(merchant_connector_id) = merchant_connector_id { - filter = filter.filter(dsl::merchant_connector_id.eq(merchant_connector_id)) + if let Some(merchant_connector_ids) = merchant_connector_id { + filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_ids)); } - if let Some(card_network) = card_network { - filter = filter.filter(dsl::card_network.eq(card_network)) + if let Some(card_networks) = card_network { + filter = filter.filter(dsl::card_network.eq_any(card_networks)); } router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string()); diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index a1ff44f5331..4449e19e089 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -235,12 +235,12 @@ pub trait PaymentAttemptInterface { &self, merchant_id: &id_type::MerchantId, active_attempt_ids: &[String], - connector: Option<api_models::enums::Connector>, - payment_method_type: Option<storage_enums::PaymentMethod>, - payment_method_subtype: Option<storage_enums::PaymentMethodType>, - authentication_type: Option<storage_enums::AuthenticationType>, - merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, - card_network: Option<storage_enums::CardNetwork>, + connector: Option<Vec<api_models::enums::Connector>>, + payment_method_type: Option<Vec<storage_enums::PaymentMethod>>, + payment_method_subtype: Option<Vec<storage_enums::PaymentMethodType>>, + authentication_type: Option<Vec<storage_enums::AuthenticationType>>, + merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, + card_network: Option<Vec<storage_enums::CardNetwork>>, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<i64, Self::Error>; } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 60158ebdc12..c96209d2b4f 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1340,20 +1340,14 @@ impl PaymentIntentFetchConstraints { #[cfg(feature = "v2")] pub enum PaymentIntentFetchConstraints { - Single { - payment_intent_id: id_type::GlobalPaymentId, - }, List(Box<PaymentIntentListParams>), } #[cfg(feature = "v2")] impl PaymentIntentFetchConstraints { pub fn get_profile_id(&self) -> Option<id_type::ProfileId> { - if let Self::List(pi_list_params) = self { - pi_list_params.profile_id.clone() - } else { - None - } + let Self::List(pi_list_params) = self; + pi_list_params.profile_id.clone() } } @@ -1387,21 +1381,22 @@ pub struct PaymentIntentListParams { pub starting_at: Option<PrimitiveDateTime>, pub ending_at: Option<PrimitiveDateTime>, pub amount_filter: Option<api_models::payments::AmountFilter>, - pub connector: Option<api_models::enums::Connector>, - pub currency: Option<common_enums::Currency>, - pub status: Option<common_enums::IntentStatus>, - pub payment_method_type: Option<common_enums::PaymentMethod>, - pub payment_method_subtype: Option<common_enums::PaymentMethodType>, - pub authentication_type: Option<common_enums::AuthenticationType>, - pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, + pub connector: Option<Vec<api_models::enums::Connector>>, + pub currency: Option<Vec<common_enums::Currency>>, + pub status: Option<Vec<common_enums::IntentStatus>>, + pub payment_method_type: Option<Vec<common_enums::PaymentMethod>>, + pub payment_method_subtype: Option<Vec<common_enums::PaymentMethodType>>, + pub authentication_type: Option<Vec<common_enums::AuthenticationType>>, + pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, pub profile_id: Option<id_type::ProfileId>, pub customer_id: Option<id_type::GlobalCustomerId>, pub starting_after_id: Option<id_type::GlobalPaymentId>, pub ending_before_id: Option<id_type::GlobalPaymentId>, pub limit: Option<u32>, pub order: api_models::payments::Order, - pub card_network: Option<common_enums::CardNetwork>, + pub card_network: Option<Vec<common_enums::CardNetwork>>, pub merchant_order_reference_id: Option<String>, + pub payment_id: Option<id_type::GlobalPaymentId>, } #[cfg(feature = "v1")] @@ -1473,39 +1468,36 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo merchant_order_reference_id, offset, } = value; - if let Some(payment_intent_id) = payment_id { - Self::Single { payment_intent_id } - } else { - Self::List(Box::new(PaymentIntentListParams { - offset: offset.unwrap_or_default(), - starting_at: created_gte.or(created_gt).or(created), - ending_at: created_lte.or(created_lt).or(created), - amount_filter: (start_amount.is_some() || end_amount.is_some()).then_some({ - api_models::payments::AmountFilter { - start_amount, - end_amount, - } - }), - connector, - currency, - status, - payment_method_type, - payment_method_subtype, - authentication_type, - merchant_connector_id, - profile_id, - customer_id, - starting_after_id: starting_after, - ending_before_id: ending_before, - limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V1)), - order: api_models::payments::Order { - on: order_on, - by: order_by, - }, - card_network, - merchant_order_reference_id, - })) - } + Self::List(Box::new(PaymentIntentListParams { + offset: offset.unwrap_or_default(), + starting_at: created_gte.or(created_gt).or(created), + ending_at: created_lte.or(created_lt).or(created), + amount_filter: (start_amount.is_some() || end_amount.is_some()).then_some({ + api_models::payments::AmountFilter { + start_amount, + end_amount, + } + }), + connector, + currency, + status, + payment_method_type, + payment_method_subtype, + authentication_type, + merchant_connector_id, + profile_id, + customer_id, + starting_after_id: starting_after, + ending_before_id: ending_before, + limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V1)), + order: api_models::payments::Order { + on: order_on, + by: order_by, + }, + card_network, + merchant_order_reference_id, + payment_id, + })) } } diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 43be476f68f..9eaef17b9c5 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1827,12 +1827,12 @@ impl PaymentAttemptInterface for KafkaStore { &self, merchant_id: &id_type::MerchantId, active_attempt_ids: &[String], - connector: Option<api_models::enums::Connector>, - payment_method_type: Option<common_enums::PaymentMethod>, - payment_method_subtype: Option<common_enums::PaymentMethodType>, - authentication_type: Option<common_enums::AuthenticationType>, - merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, - card_network: Option<common_enums::CardNetwork>, + connector: Option<Vec<api_models::enums::Connector>>, + payment_method_type: Option<Vec<common_enums::PaymentMethod>>, + payment_method_subtype: Option<Vec<common_enums::PaymentMethodType>>, + authentication_type: Option<Vec<common_enums::AuthenticationType>>, + merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, + card_network: Option<Vec<common_enums::CardNetwork>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index ec27f9bed65..0268bc93ac9 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -65,12 +65,12 @@ impl PaymentAttemptInterface for MockDb { &self, _merchant_id: &id_type::MerchantId, _active_attempt_ids: &[String], - _connector: Option<api_models::enums::Connector>, - _payment_method_type: Option<common_enums::PaymentMethod>, - _payment_method_subtype: Option<common_enums::PaymentMethodType>, - _authentication_type: Option<common_enums::AuthenticationType>, - _merchanat_connector_id: Option<id_type::MerchantConnectorAccountId>, - _card_network: Option<storage_enums::CardNetwork>, + _connector: Option<Vec<api_models::enums::Connector>>, + _payment_method_type: Option<Vec<common_enums::PaymentMethod>>, + _payment_method_subtype: Option<Vec<common_enums::PaymentMethodType>>, + _authentication_type: Option<Vec<common_enums::AuthenticationType>>, + _merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, + _card_network: Option<Vec<storage_enums::CardNetwork>>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<i64, StorageError> { Err(StorageError::MockDbError)? diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 5ddf5d50182..5424ad964e3 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -546,12 +546,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { &self, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], - connector: Option<api_models::enums::Connector>, - payment_method_type: Option<common_enums::PaymentMethod>, - payment_method_subtype: Option<common_enums::PaymentMethodType>, - authentication_type: Option<common_enums::AuthenticationType>, - merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, - card_network: Option<common_enums::CardNetwork>, + connector: Option<Vec<api_models::enums::Connector>>, + payment_method_type: Option<Vec<common_enums::PaymentMethod>>, + payment_method_subtype: Option<Vec<common_enums::PaymentMethodType>>, + authentication_type: Option<Vec<common_enums::AuthenticationType>>, + merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, + card_network: Option<Vec<common_enums::CardNetwork>>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = self @@ -565,7 +565,9 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { &conn, merchant_id, active_attempt_ids, - connector.map(|val| val.to_string()), + connector + .as_ref() + .map(|vals| vals.iter().map(|v| v.to_string()).collect()), payment_method_type, payment_method_subtype, authentication_type, @@ -1713,12 +1715,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { &self, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], - connector: Option<api_models::enums::Connector>, - payment_method_type: Option<common_enums::PaymentMethod>, - payment_method_subtype: Option<common_enums::PaymentMethodType>, - authentication_type: Option<common_enums::AuthenticationType>, - merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, - card_network: Option<common_enums::CardNetwork>, + connector: Option<Vec<api_models::enums::Connector>>, + payment_method_type: Option<Vec<common_enums::PaymentMethod>>, + payment_method_subtype: Option<Vec<common_enums::PaymentMethodType>>, + authentication_type: Option<Vec<common_enums::AuthenticationType>>, + merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, + card_network: Option<Vec<common_enums::CardNetwork>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { self.router_store diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index d054a4b1650..4eb3fad60a8 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -1361,9 +1361,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .into_boxed(); query = match constraints { - PaymentIntentFetchConstraints::Single { payment_intent_id } => { - query.filter(pi_dsl::id.eq(payment_intent_id.to_owned())) - } PaymentIntentFetchConstraints::List(params) => { query = match params.order { Order { @@ -1457,50 +1454,54 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { }; query = match &params.currency { - Some(currency) => query.filter(pi_dsl::currency.eq(*currency)), + Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())), None => query, }; query = match &params.connector { - Some(connector) => query.filter(pa_dsl::connector.eq(*connector)), + Some(connector) => query.filter(pa_dsl::connector.eq_any(connector.clone())), None => query, }; query = match &params.status { - Some(status) => query.filter(pi_dsl::status.eq(*status)), + Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())), None => query, }; query = match &params.payment_method_type { - Some(payment_method_type) => { - query.filter(pa_dsl::payment_method_type_v2.eq(*payment_method_type)) - } + Some(payment_method_type) => query + .filter(pa_dsl::payment_method_type_v2.eq_any(payment_method_type.clone())), None => query, }; query = match &params.payment_method_subtype { - Some(payment_method_subtype) => { - query.filter(pa_dsl::payment_method_subtype.eq(*payment_method_subtype)) - } + Some(payment_method_subtype) => query.filter( + pa_dsl::payment_method_subtype.eq_any(payment_method_subtype.clone()), + ), None => query, }; query = match &params.authentication_type { - Some(authentication_type) => { - query.filter(pa_dsl::authentication_type.eq(*authentication_type)) - } + Some(authentication_type) => query + .filter(pa_dsl::authentication_type.eq_any(authentication_type.clone())), None => query, }; query = match &params.merchant_connector_id { - Some(merchant_connector_id) => query - .filter(pa_dsl::merchant_connector_id.eq(merchant_connector_id.clone())), + Some(merchant_connector_id) => query.filter( + pa_dsl::merchant_connector_id.eq_any(merchant_connector_id.clone()), + ), None => query, }; if let Some(card_network) = &params.card_network { - query = query.filter(pa_dsl::card_network.eq(card_network.clone())); + query = query.filter(pa_dsl::card_network.eq_any(card_network.clone())); } + + if let Some(payment_id) = &params.payment_id { + query = query.filter(pi_dsl::id.eq(payment_id.clone())); + } + query } }; @@ -1561,9 +1562,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .into_boxed(); query = match constraints { - PaymentIntentFetchConstraints::Single { payment_intent_id } => { - query.filter(pi_dsl::id.eq(payment_intent_id.to_owned())) - } PaymentIntentFetchConstraints::List(params) => { if let Some(customer_id) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); @@ -1604,15 +1602,19 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { }; query = match &params.currency { - Some(currency) => query.filter(pi_dsl::currency.eq(*currency)), + Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())), None => query, }; query = match &params.status { - Some(status) => query.filter(pi_dsl::status.eq(*status)), + Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())), None => query, }; + if let Some(payment_id) = &params.payment_id { + query = query.filter(pi_dsl::id.eq(payment_id.clone())); + } + query } };
2025-07-29T14:30:17Z
## 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 --> **Enhanced Payment Listing API with Multi-Value Filtering** This feature adds support for retrieving a filtered list of payments via a `GET /v2/payments/list` endpoint where multiple values can be provided for a single filter key (e.g. `status`, `currency`, `connector`, etc.). ### Additional Changes - [X] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> GetRequest: ``` curl --location 'http://localhost:8080/v2/payments/list' \ --header 'api-key: dev_tP1IAK95c65hjO7NvF3dRliuiMuSIFhIeFjXBb1du3NZ1Ui6Av0XKyL3ONtB7tpy' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_G9buhoAY3Mpu9cFIeWoZ' \ --header 'Authorization: api-key=dev_tP1IAK95c65hjO7NvF3dRliuiMuSIFhIeFjXBb1du3NZ1Ui6Av0XKyL3ONtB7tpy' \ --data '' ``` GetResponse: ``` { "count": 4, "total_count": 4, "data": [ { "id": "12345_pay_01987e212eac7b23986ab9afee1d4f3f", "merchant_id": "cloth_seller_qNqGZXs31yvrAlmFG1Jj", "profile_id": "pro_G9buhoAY3Mpu9cFIeWoZ", "customer_id": null, "payment_method_id": null, "status": "requires_payment_method", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "created": "2025-08-06T06:46:00.627Z", "payment_method_type": null, "payment_method_subtype": null, "connector": null, "merchant_connector_id": null, "customer": null, "merchant_reference_id": null, "connector_payment_id": null, "connector_response_reference_id": null, "metadata": null, "description": null, "authentication_type": "no_three_ds", "capture_method": "manual", "setup_future_usage": "on_session", "attempt_count": 0, "error": null, "cancellation_reason": null, "order_details": null, "return_url": null, "statement_descriptor": null, "allowed_payment_method_types": null, "authorization_count": 0, "modified_at": null }, { "id": "12345_pay_01987e212d6f7af18f54d484b9afad2f", "merchant_id": "cloth_seller_qNqGZXs31yvrAlmFG1Jj", "profile_id": "pro_G9buhoAY3Mpu9cFIeWoZ", "customer_id": null, "payment_method_id": null, "status": "requires_payment_method", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "created": "2025-08-06T06:46:00.316Z", "payment_method_type": null, "payment_method_subtype": null, "connector": null, "merchant_connector_id": null, "customer": null, "merchant_reference_id": null, "connector_payment_id": null, "connector_response_reference_id": null, "metadata": null, "description": null, "authentication_type": "no_three_ds", "capture_method": "manual", "setup_future_usage": "on_session", "attempt_count": 0, "error": null, "cancellation_reason": null, "order_details": null, "return_url": null, "statement_descriptor": null, "allowed_payment_method_types": null, "authorization_count": 0, "modified_at": null }, { "id": "12345_pay_01987e212b497a7394a404b857f156bf", "merchant_id": "cloth_seller_qNqGZXs31yvrAlmFG1Jj", "profile_id": "pro_G9buhoAY3Mpu9cFIeWoZ", "customer_id": null, "payment_method_id": null, "status": "requires_payment_method", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "created": "2025-08-06T06:45:59.767Z", "payment_method_type": null, "payment_method_subtype": null, "connector": null, "merchant_connector_id": null, "customer": null, "merchant_reference_id": null, "connector_payment_id": null, "connector_response_reference_id": null, "metadata": null, "description": null, "authentication_type": "no_three_ds", "capture_method": "manual", "setup_future_usage": "on_session", "attempt_count": 0, "error": null, "cancellation_reason": null, "order_details": null, "return_url": null, "statement_descriptor": null, "allowed_payment_method_types": null, "authorization_count": 0, "modified_at": null }, { "id": "12345_pay_01987e1fa70c7bb18fea2a1667c32e5e", "merchant_id": "cloth_seller_qNqGZXs31yvrAlmFG1Jj", "profile_id": "pro_G9buhoAY3Mpu9cFIeWoZ", "customer_id": null, "payment_method_id": null, "status": "requires_payment_method", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "created": "2025-08-06T06:44:20.386Z", "payment_method_type": null, "payment_method_subtype": null, "connector": null, "merchant_connector_id": null, "customer": null, "merchant_reference_id": null, "connector_payment_id": null, "connector_response_reference_id": null, "metadata": null, "description": null, "authentication_type": "no_three_ds", "capture_method": "manual", "setup_future_usage": "on_session", "attempt_count": 0, "error": null, "cancellation_reason": null, "order_details": null, "return_url": null, "statement_descriptor": null, "allowed_payment_method_types": null, "authorization_count": 0, "modified_at": null } ] } ``` GETRequestWithMultipleFilters: ``` curl --location 'http://localhost:8080/v2/payments/list?status=requires_payment_method%2Crequires_capture%2Csucceeded&currency=USD' \ --header 'api-key: dev_0M1HsoPENAKVcLprxBkqXvtLLA8myjdVHFUDvvknNykT1jlEdww31C8VNcj3emYL' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_qBIx1HzjxmvyeDgJmZLd' \ --header 'Authorization: api-key=dev_0M1HsoPENAKVcLprxBkqXvtLLA8myjdVHFUDvvknNykT1jlEdww31C8VNcj3emYL' \ --data '' ``` PostResponse: ``` { "count": 6, "total_count": 6, "data": [ { "id": "12345_pay_019897db488f74b2ace8d4f34a1afd2e", "merchant_id": "cloth_seller_EWd2xVEKmKewu5gHgXMY", "profile_id": "pro_qBIx1HzjxmvyeDgJmZLd", "customer_id": null, "payment_method_id": null, "status": "succeeded", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": 100 }, "created": "2025-08-11T06:39:47.356Z", "payment_method_type": "card", "payment_method_subtype": "credit", "connector": "authorizedotnet", "merchant_connector_id": "mca_t6Qa8RtV3MHmRAHlu1Zi", "customer": null, "merchant_reference_id": null, "connector_payment_id": "80043331424", "connector_response_reference_id": "80043331424", "metadata": null, "description": null, "authentication_type": "no_three_ds", "capture_method": "automatic", "setup_future_usage": "on_session", "attempt_count": 0, "error": null, "cancellation_reason": null, "order_details": null, "return_url": null, "statement_descriptor": null, "allowed_payment_method_types": null, "authorization_count": 0, "modified_at": "2025-08-11T06:39:50.721Z" }, { "id": "12345_pay_019897db458a7650b52dc95d1d2cedc5", "merchant_id": "cloth_seller_EWd2xVEKmKewu5gHgXMY", "profile_id": "pro_qBIx1HzjxmvyeDgJmZLd", "customer_id": null, "payment_method_id": null, "status": "requires_payment_method", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "created": "2025-08-11T06:39:46.589Z", "payment_method_type": null, "payment_method_subtype": null, "connector": null, "merchant_connector_id": null, "customer": null, "merchant_reference_id": null, "connector_payment_id": null, "connector_response_reference_id": null, "metadata": null, "description": null, "authentication_type": "no_three_ds", "capture_method": "automatic", "setup_future_usage": "on_session", "attempt_count": 0, "error": null, "cancellation_reason": null, "order_details": null, "return_url": null, "statement_descriptor": null, "allowed_payment_method_types": null, "authorization_count": 0, "modified_at": null }, { "id": "12345_pay_019897db02ff7e10b129a3df71b09aaf", "merchant_id": "cloth_seller_EWd2xVEKmKewu5gHgXMY", "profile_id": "pro_qBIx1HzjxmvyeDgJmZLd", "customer_id": null, "payment_method_id": null, "status": "requires_payment_method", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "created": "2025-08-11T06:39:29.562Z", "payment_method_type": null, "payment_method_subtype": null, "connector": null, "merchant_connector_id": null, "customer": null, "merchant_reference_id": null, "connector_payment_id": null, "connector_response_reference_id": null, "metadata": null, "description": null, "authentication_type": "no_three_ds", "capture_method": "automatic", "setup_future_usage": "on_session", "attempt_count": 0, "error": null, "cancellation_reason": null, "order_details": null, "return_url": null, "statement_descriptor": null, "allowed_payment_method_types": null, "authorization_count": 0, "modified_at": null }, { "id": "12345_pay_019897db003876b1b5f57f8d4c27072d", "merchant_id": "cloth_seller_EWd2xVEKmKewu5gHgXMY", "profile_id": "pro_qBIx1HzjxmvyeDgJmZLd", "customer_id": null, "payment_method_id": null, "status": "requires_payment_method", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "created": "2025-08-11T06:39:28.839Z", "payment_method_type": null, "payment_method_subtype": null, "connector": null, "merchant_connector_id": null, "customer": null, "merchant_reference_id": null, "connector_payment_id": null, "connector_response_reference_id": null, "metadata": null, "description": null, "authentication_type": "no_three_ds", "capture_method": "automatic", "setup_future_usage": "on_session", "attempt_count": 0, "error": null, "cancellation_reason": null, "order_details": null, "return_url": null, "statement_descriptor": null, "allowed_payment_method_types": null, "authorization_count": 0, "modified_at": null }, { "id": "12345_pay_019897dafd2070c1956d1af439088873", "merchant_id": "cloth_seller_EWd2xVEKmKewu5gHgXMY", "profile_id": "pro_qBIx1HzjxmvyeDgJmZLd", "customer_id": null, "payment_method_id": null, "status": "requires_payment_method", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "created": "2025-08-11T06:39:28.045Z", "payment_method_type": null, "payment_method_subtype": null, "connector": null, "merchant_connector_id": null, "customer": null, "merchant_reference_id": null, "connector_payment_id": null, "connector_response_reference_id": null, "metadata": null, "description": null, "authentication_type": "no_three_ds", "capture_method": "automatic", "setup_future_usage": "on_session", "attempt_count": 0, "error": null, "cancellation_reason": null, "order_details": null, "return_url": null, "statement_descriptor": null, "allowed_payment_method_types": null, "authorization_count": 0, "modified_at": null }, { "id": "12345_pay_019897dae26871f2be542d43fc570b13", "merchant_id": "cloth_seller_EWd2xVEKmKewu5gHgXMY", "profile_id": "pro_qBIx1HzjxmvyeDgJmZLd", "customer_id": null, "payment_method_id": null, "status": "succeeded", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": 100 }, "created": "2025-08-11T06:39:21.215Z", "payment_method_type": "card", "payment_method_subtype": "credit", "connector": "authorizedotnet", "merchant_connector_id": "mca_t6Qa8RtV3MHmRAHlu1Zi", "customer": null, "merchant_reference_id": null, "connector_payment_id": "80043331420", "connector_response_reference_id": "80043331420", "metadata": null, "description": null, "authentication_type": "no_three_ds", "capture_method": "automatic", "setup_future_usage": "on_session", "attempt_count": 0, "error": null, "cancellation_reason": null, "order_details": null, "return_url": null, "statement_descriptor": null, "allowed_payment_method_types": null, "authorization_count": 0, "modified_at": "2025-08-11T06:39:26.628Z" } ] } ``` GetRequestWithTimeDuration: ``` curl --location 'http://localhost:8080/v2/payments/list?status=requires_payment_method%2Crequires_capture%2Csucceeded&currency=USD&created.gte=2025-08-01T00%3A00%3A00Z&created.lte=2025-08-09T23%3A59%3A59Z' \ --header 'api-key: dev_SfzD1JfNBMBwIxi6S55ku8kCXpt665huoFrJv1hnIFERGXNIUWldBQaOMJiHE0de' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_E7U8C0vjFGXvuaVEGH4M' \ --header 'Authorization: api-key=dev_SfzD1JfNBMBwIxi6S55ku8kCXpt665huoFrJv1hnIFERGXNIUWldBQaOMJiHE0de' \ --data '' ``` Response: ``` { "count": 0, "total_count": 0, "data": [] } ``` GetRequestWithTimeDuration: ``` curl --location 'http://localhost:8080/v2/payments/list?status=failed&currency=USD&created.gte=2025-08-01T00%3A00%3A00Z&created.lte=2025-08-31T23%3A59%3A59Z' \ --header 'api-key: dev_SfzD1JfNBMBwIxi6S55ku8kCXpt665huoFrJv1hnIFERGXNIUWldBQaOMJiHE0de' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_E7U8C0vjFGXvuaVEGH4M' \ --header 'Authorization: api-key=dev_SfzD1JfNBMBwIxi6S55ku8kCXpt665huoFrJv1hnIFERGXNIUWldBQaOMJiHE0de' \ --data '' ``` Response: ``` { "count": 1, "total_count": 1, "data": [ { "id": "12345_pay_01989e70b0fc7e219eb6352105ccd06f", "merchant_id": "cloth_seller_bdCHKB6LXsvpWlKKcios", "profile_id": "pro_E7U8C0vjFGXvuaVEGH4M", "customer_id": "12345_cus_01989e7025b471c0ace0c31e46b83360", "payment_method_id": null, "status": "failed", "amount": { "order_amount": 10000, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 10000, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "created": "2025-08-12T13:20:42.244Z", "payment_method_type": "card", "payment_method_subtype": "credit", "connector": "trustpay", "merchant_connector_id": "mca_Z9a58zhABpHduskbCsf9", "customer": null, "merchant_reference_id": null, "connector_payment_id": null, "connector_response_reference_id": null, "metadata": null, "description": null, "authentication_type": "no_three_ds", "capture_method": "automatic", "setup_future_usage": "on_session", "attempt_count": 0, "error": { "code": "4", "message": "4", "unified_code": null, "unified_message": null, "network_advice_code": null, "network_decline_code": null, "network_error_message": null }, "cancellation_reason": null, "order_details": null, "return_url": null, "statement_descriptor": null, "allowed_payment_method_types": null, "authorization_count": 0, "modified_at": "2025-08-12T13:20:47.624Z" } ] } ``` Closes #8792 ## 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.116.0
446590690e7980e1bef6b846683d391b43cb3f0e
446590690e7980e1bef6b846683d391b43cb3f0e
juspay/hyperswitch
juspay__hyperswitch-8796
Bug: [FEATURE] (connector): [ARCHIPEL,BANKOFAMERICA,BOKU,CHARGEBEE,CRYPTOPAY,CYBERSOURCE,DATATRANS,NMI,NOON,PAYEEZY,PAYME,PAYPAL,PLAID,STRIPEBILLING,TRUSTPAY] add in feature matrix api ### Feature Description [ARCHIPEL,BANKOFAMERICA,BOKU,CHARGEBEE,CRYPTOPAY,CYBERSOURCE,DATATRANS,NMI,NOON,PAYEEZY,PAYME,PAYPAL,PLAID,STRIPEBILLING,TRUSTPAY] add in feature matrix api ### Possible Implementation [ARCHIPEL,BANKOFAMERICA,BOKU,CHARGEBEE,CRYPTOPAY,CYBERSOURCE,DATATRANS,NMI,NOON,PAYEEZY,PAYME,PAYPAL,PLAID,STRIPEBILLING,TRUSTPAY] add in feature matrix api ### 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/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 2182ecbef46..5f8bfdf3959 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -16673,7 +16673,8 @@ "payout_processor", "authentication_provider", "fraud_and_risk_management_provider", - "tax_calculation_provider" + "tax_calculation_provider", + "revenue_growth_management_platform" ] }, "IfStatement": { diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 2d9164f8cb5..d7a0b6e5393 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -12819,7 +12819,8 @@ "payout_processor", "authentication_provider", "fraud_and_risk_management_provider", - "tax_calculation_provider" + "tax_calculation_provider", + "revenue_growth_management_platform" ] }, "HyperswitchVaultSessionDetails": { diff --git a/config/config.example.toml b/config/config.example.toml index 5fe3dbd05fa..a6bc906cd67 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -536,7 +536,7 @@ bank_redirect.ideal = { connector_list = "stripe,adyen,globalpay" } bank_redirect.sofort = { connector_list = "stripe,globalpay" } wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon,bankofamerica,authorizedotnet" } wallet.samsung_pay = { connector_list = "cybersource" } -wallet.google_pay = { connector_list = "bankofamerica,authorizedotnet" } +wallet.google_pay = { connector_list = "bankofamerica,authorizedotnet,cybersource" } bank_redirect.giropay = { connector_list = "globalpay" } [mandates.supported_payment_methods] @@ -685,11 +685,11 @@ red_pagos = { country = "UY", currency = "UYU" } local_bank_transfer = { country = "CN", currency = "CNY" } [pm_filters.bankofamerica] -credit = { currency = "USD" } -debit = { currency = "USD" } -apple_pay = { currency = "USD" } -google_pay = { currency = "USD" } -samsung_pay = { currency = "USD" } +credit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" } +debit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" } +apple_pay = { country = "AU,AT,BH,BE,BR,BG,CA,CL,CN,CO,CR,HR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,MC,ME,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" } +google_pay = { country = "AU,AT,BE,BR,CA,CL,CO,CR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" } +samsung_pay = { country = "AU,BH,BR,CA,CN,DK,FI,FR,DE,HK,IN,IT,JP,KZ,KR,KW,MY,NZ,NO,OM,QA,SA,SG,ZA,ES,SE,CH,TW,AE,GB,US", currency = "USD" } [pm_filters.cybersource] credit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } @@ -908,6 +908,37 @@ bluecode = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT [pm_filters.dwolla] ach = { country = "US", currency = "USD" } +[pm_filters.boku] +dana = { country = "ID", currency = "IDR" } +gcash = { country = "PH", currency = "PHP" } +go_pay = { country = "ID", currency = "IDR" } +kakao_pay = { country = "KR", currency = "KRW" } +momo = { country = "VN", currency = "VND" } + +[pm_filters.nmi] +credit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +debit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +apple_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +google_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } + +[pm_filters.paypal] +credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +paypal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +eps = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +giropay = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +ideal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } + +[pm_filters.datatrans] +credit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } +debit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } + +[pm_filters.payme] +credit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +debit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } + [connector_customer] connector_list = "authorizedotnet,dwolla,facilitapay,gocardless,hyperswitch_vault,stax,stripe" payout_connector_list = "nomupay,stripe,wise" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 21ac732394f..aef655bf250 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -415,11 +415,11 @@ credit = { country = "US,CA", currency = "USD" } debit = { country = "US,CA", currency = "USD" } [pm_filters.bankofamerica] -credit = { currency = "USD" } -debit = { currency = "USD" } -apple_pay = { currency = "USD" } -google_pay = { currency = "USD" } -samsung_pay = { currency = "USD" } +credit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" } +debit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" } +apple_pay = { country = "AU,AT,BH,BE,BR,BG,CA,CL,CN,CO,CR,HR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,MC,ME,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" } +google_pay = { country = "AU,AT,BE,BR,CA,CL,CO,CR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" } +samsung_pay = { country = "AU,BH,BR,CA,CN,DK,FI,FR,DE,HK,IN,IT,JP,KZ,KR,KW,MY,NZ,NO,OM,QA,SA,SG,ZA,ES,SE,CH,TW,AE,GB,US", currency = "USD" } [pm_filters.braintree] credit = { country = "AD,AT,AU,BE,BG,CA,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GG,GI,GR,HK,HR,HU,IE,IM,IT,JE,LI,LT,LU,LV,MT,MC,MY,NL,NO,NZ,PL,PT,RO,SE,SG,SI,SK,SM,US", currency = "AED,AMD,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BIF,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,ISK,JMD,JPY,KES,KGS,KHR,KMF,KRW,KYD,KZT,LAK,LBP,LKR,LRD,LSL,MAD,MDL,MKD,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLL,SOS,SRD,STD,SVC,SYP,SZL,THB,TJS,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL"} @@ -789,6 +789,37 @@ pix = { country = "BR", currency = "BRL" } [pm_filters.bluecode] bluecode = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,IS,LI,NO", currency = "EUR" } +[pm_filters.boku] +dana = { country = "ID", currency = "IDR" } +gcash = { country = "PH", currency = "PHP" } +go_pay = { country = "ID", currency = "IDR" } +kakao_pay = { country = "KR", currency = "KRW" } +momo = { country = "VN", currency = "VND" } + +[pm_filters.nmi] +credit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +debit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +apple_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +google_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } + +[pm_filters.paypal] +credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +paypal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +eps = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +giropay = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +ideal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } + +[pm_filters.datatrans] +credit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } +debit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } + +[pm_filters.payme] +credit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +debit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } + [temp_locker_enable_config] bluesnap.payment_method = "card" nuvei.payment_method = "card" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 853ec279f66..8cff6885a5c 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -426,11 +426,11 @@ credit = { country = "US,CA", currency = "USD" } debit = { country = "US,CA", currency = "USD" } [pm_filters.bankofamerica] -credit = { currency = "USD" } -debit = { currency = "USD" } -apple_pay = { currency = "USD" } -google_pay = { currency = "USD" } -samsung_pay = { currency = "USD" } +credit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" } +debit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" } +apple_pay = { country = "AU,AT,BH,BE,BR,BG,CA,CL,CN,CO,CR,HR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,MC,ME,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" } +google_pay = { country = "AU,AT,BE,BR,CA,CL,CO,CR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" } +samsung_pay = { country = "AU,BH,BR,CA,CN,DK,FI,FR,DE,HK,IN,IT,JP,KZ,KR,KW,MY,NZ,NO,OM,QA,SA,SG,ZA,ES,SE,CH,TW,AE,GB,US", currency = "USD" } [pm_filters.cybersource] credit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } @@ -790,6 +790,37 @@ pix = { country = "BR", currency = "BRL" } [pm_filters.bluecode] bluecode = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,IS,LI,NO", currency = "EUR" } +[pm_filters.boku] +dana = { country = "ID", currency = "IDR" } +gcash = { country = "PH", currency = "PHP" } +go_pay = { country = "ID", currency = "IDR" } +kakao_pay = { country = "KR", currency = "KRW" } +momo = { country = "VN", currency = "VND" } + +[pm_filters.nmi] +credit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +debit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +apple_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +google_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } + +[pm_filters.paypal] +credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +paypal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +eps = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +giropay = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +ideal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } + +[pm_filters.datatrans] +credit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } +debit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } + +[pm_filters.payme] +credit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +debit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } + [payout_method_filters.adyenplatform] sepa = { country = "AT,BE,CH,CZ,DE,EE,ES,FI,FR,GB,HU,IE,IT,LT,LV,NL,NO,PL,PT,SE,SK", currency = "EUR,CZK,DKK,HUF,NOK,PLN,SEK,GBP,CHF" } credit = { country = "AT,BE,BG,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GR,HR,HU,IE,IS,IT,LI,LT,LU,LV,MT,NL,NO,PL,PT,RO,SE,SI,SK,US", currency = "EUR,USD,GBP" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index dbd5e87e520..8a996c33d21 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -435,11 +435,11 @@ credit = { country = "US,CA", currency = "USD" } debit = { country = "US,CA", currency = "USD" } [pm_filters.bankofamerica] -credit = { currency = "USD" } -debit = { currency = "USD" } -apple_pay = { currency = "USD" } -google_pay = { currency = "USD" } -samsung_pay = { currency = "USD" } +credit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" } +debit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" } +apple_pay = { country = "AU,AT,BH,BE,BR,BG,CA,CL,CN,CO,CR,HR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,MC,ME,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" } +google_pay = { country = "AU,AT,BE,BR,CA,CL,CO,CR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" } +samsung_pay = { country = "AU,BH,BR,CA,CN,DK,FI,FR,DE,HK,IN,IT,JP,KZ,KR,KW,MY,NZ,NO,OM,QA,SA,SG,ZA,ES,SE,CH,TW,AE,GB,US", currency = "USD" } [pm_filters.checkbook] ach = { country = "US", currency = "USD" } @@ -802,6 +802,37 @@ pix = { country = "BR", currency = "BRL" } [pm_filters.bluecode] bluecode = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,IS,LI,NO", currency = "EUR" } +[pm_filters.boku] +dana = { country = "ID", currency = "IDR" } +gcash = { country = "PH", currency = "PHP" } +go_pay = { country = "ID", currency = "IDR" } +kakao_pay = { country = "KR", currency = "KRW" } +momo = { country = "VN", currency = "VND" } + +[pm_filters.nmi] +credit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +debit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +apple_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +google_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } + +[pm_filters.paypal] +credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +paypal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +eps = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +giropay = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +ideal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } + +[pm_filters.datatrans] +credit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } +debit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } + +[pm_filters.payme] +credit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +debit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } + [payout_method_filters.stripe] ach = { country = "US", currency = "USD" } diff --git a/config/development.toml b/config/development.toml index 1215c323628..933f8fda01c 100644 --- a/config/development.toml +++ b/config/development.toml @@ -604,11 +604,11 @@ credit = { country = "US,CA", currency = "USD" } debit = { country = "US,CA", currency = "USD" } [pm_filters.bankofamerica] -credit = { currency = "USD" } -debit = { currency = "USD" } -apple_pay = { currency = "USD" } -google_pay = { currency = "USD" } -samsung_pay = { currency = "USD" } +credit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" } +debit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" } +apple_pay = { country = "AU,AT,BH,BE,BR,BG,CA,CL,CN,CO,CR,HR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,MC,ME,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" } +google_pay = { country = "AU,AT,BE,BR,CA,CL,CO,CR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" } +samsung_pay = { country = "AU,BH,BR,CA,CN,DK,FI,FR,DE,HK,IN,IT,JP,KZ,KR,KW,MY,NZ,NO,OM,QA,SA,SG,ZA,ES,SE,CH,TW,AE,GB,US", currency = "USD" } [pm_filters.cybersource] credit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } @@ -950,6 +950,37 @@ eft = { country = "NG, ZA, GH, KE, CI", currency = "NGN, GHS, ZAR, KES, USD" } [pm_filters.santander] pix = { country = "BR", currency = "BRL" } +[pm_filters.boku] +dana = { country = "ID", currency = "IDR" } +gcash = { country = "PH", currency = "PHP" } +go_pay = { country = "ID", currency = "IDR" } +kakao_pay = { country = "KR", currency = "KRW" } +momo = { country = "VN", currency = "VND" } + +[pm_filters.nmi] +credit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +debit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +apple_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +google_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } + +[pm_filters.paypal] +credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +paypal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +eps = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +giropay = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +ideal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } + +[pm_filters.datatrans] +credit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } +debit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } + +[pm_filters.payme] +credit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +debit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } + [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" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 75305234278..750d9f05f57 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -652,11 +652,11 @@ ali_pay = {country = "CN", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,MYR,NZD,SGD,U card_redirect = { country = "US", currency = "USD" } [pm_filters.bankofamerica] -credit = { currency = "USD" } -debit = { currency = "USD" } -apple_pay = { currency = "USD" } -google_pay = { currency = "USD" } -samsung_pay = { currency = "USD" } +credit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" } +debit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" } +apple_pay = { country = "AU,AT,BH,BE,BR,BG,CA,CL,CN,CO,CR,HR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,MC,ME,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" } +google_pay = { country = "AU,AT,BE,BR,CA,CL,CO,CR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" } +samsung_pay = { country = "AU,BH,BR,CA,CN,DK,FI,FR,DE,HK,IN,IT,JP,KZ,KR,KW,MY,NZ,NO,OM,QA,SA,SG,ZA,ES,SE,CH,TW,AE,GB,US", currency = "USD" } [pm_filters.cybersource] credit = { currency = "USD,GBP,EUR,PLN,SEK,XOF" } @@ -934,6 +934,37 @@ pix = { country = "BR", currency = "BRL" } [pm_filters.bluecode] bluecode = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,IS,LI,NO", currency = "EUR" } +[pm_filters.boku] +dana = { country = "ID", currency = "IDR" } +gcash = { country = "PH", currency = "PHP" } +go_pay = { country = "ID", currency = "IDR" } +kakao_pay = { country = "KR", currency = "KRW" } +momo = { country = "VN", currency = "VND" } + +[pm_filters.nmi] +credit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +debit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +apple_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +google_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } + +[pm_filters.paypal] +credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +paypal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +eps = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +giropay = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +ideal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } + +[pm_filters.datatrans] +credit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } +debit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } + +[pm_filters.payme] +credit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +debit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } + [bank_config.online_banking_fpx] adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" fiuu.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_of_china,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" @@ -970,7 +1001,7 @@ bank_redirect.open_banking_uk.connector_list = "adyen" [mandates.supported_payment_methods] pay_later.klarna = { connector_list = "adyen,aci" } -wallet.google_pay = { connector_list = "stripe,adyen,bankofamerica,authorizedotnet,novalnet,multisafepay,wellsfargo" } +wallet.google_pay = { connector_list = "stripe,cybersource,adyen,bankofamerica,authorizedotnet,noon,novalnet,multisafepay,wellsfargo" } wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon,bankofamerica,authorizedotnet,novalnet,multisafepay,wellsfargo" } wallet.samsung_pay = { connector_list = "cybersource" } wallet.paypal = { connector_list = "adyen,novalnet,authorizedotnet" } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 07916214269..70945ba44cc 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -8489,6 +8489,7 @@ pub enum HyperswitchConnectorCategory { AuthenticationProvider, FraudAndRiskManagementProvider, TaxCalculationProvider, + RevenueGrowthManagementPlatform, } /// Connector Integration Status diff --git a/crates/hyperswitch_connectors/src/connectors/archipel.rs b/crates/hyperswitch_connectors/src/connectors/archipel.rs index 997cbbb9a1c..ef5bccee25a 100644 --- a/crates/hyperswitch_connectors/src/connectors/archipel.rs +++ b/crates/hyperswitch_connectors/src/connectors/archipel.rs @@ -1,3 +1,5 @@ +use std::sync::LazyLock; + use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use common_enums::enums; use common_utils::{ @@ -21,7 +23,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsIncrementalAuthorizationRouterData, PaymentsSyncRouterData, RefundSyncRouterData, @@ -29,7 +34,10 @@ use hyperswitch_domain_models::{ }, }; use hyperswitch_interfaces::{ - api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + api::{ + self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, + ConnectorValidation, + }, configs::Connectors, consts::NO_ERROR_MESSAGE, errors, @@ -45,7 +53,6 @@ use transformers::{ }; use crate::{ - capture_method_not_supported, constants::headers, types::ResponseRouterData, utils::{is_mandate_supported, PaymentMethodDataType, PaymentsAuthorizeRequestData}, @@ -79,7 +86,6 @@ impl api::RefundExecute for Archipel {} impl api::RefundSync for Archipel {} impl api::Payment for Archipel {} impl api::PaymentIncrementalAuthorization for Archipel {} -impl api::ConnectorSpecifications for Archipel {} fn build_env_specific_endpoint( base_url: &str, @@ -180,34 +186,6 @@ impl ConnectorCommon for Archipel { } impl ConnectorValidation for Archipel { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<common_enums::CaptureMethod>, - _payment_method: common_enums::PaymentMethod, - pmt: Option<common_enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - - match capture_method { - enums::CaptureMethod::Automatic - | enums::CaptureMethod::SequentialAutomatic - | enums::CaptureMethod::Manual => Ok(()), - enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => { - let connector = self.id(); - match pmt { - Some(payment_method_type) => { - capture_method_not_supported!( - connector, - capture_method, - payment_method_type - ) - } - None => capture_method_not_supported!(connector, capture_method), - } - } - } - } - fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, @@ -1084,3 +1062,97 @@ impl IncomingWebhook for Archipel { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } + +static ARCHIPEL_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::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::CartesBancaires, + ]; + + let mut archipel_supported_payment_methods = SupportedPaymentMethods::new(); + + archipel_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + archipel_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network, + } + }), + ), + }, + ); + + archipel_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::ApplePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: None, + }, + ); + + archipel_supported_payment_methods + }); + +static ARCHIPEL_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Archipel", + description: "Full-service processor offering secure payment solutions and innovative banking technologies for businesses of all sizes.", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Live, +}; + +static ARCHIPEL_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Archipel { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&ARCHIPEL_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*ARCHIPEL_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&ARCHIPEL_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/bamboraapac.rs b/crates/hyperswitch_connectors/src/connectors/bamboraapac.rs index 5cdbcf883fc..23752321b55 100644 --- a/crates/hyperswitch_connectors/src/connectors/bamboraapac.rs +++ b/crates/hyperswitch_connectors/src/connectors/bamboraapac.rs @@ -1,4 +1,5 @@ pub mod transformers; +use std::sync::LazyLock; use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use common_enums::enums; @@ -43,7 +44,6 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; -use lazy_static::lazy_static; use transformers as bamboraapac; use crate::{ @@ -738,8 +738,8 @@ fn html_to_xml_string_conversion(res: String) -> String { res.replace("&lt;", "<").replace("&gt;", ">") } -lazy_static! { - static ref BAMBORAAPAC_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { +static BAMBORAAPAC_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { let default_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, @@ -750,6 +750,12 @@ lazy_static! { common_enums::CardNetwork::Visa, common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, ]; let mut bamboraapac_supported_payment_methods = SupportedPaymentMethods::new(); @@ -793,21 +799,20 @@ lazy_static! { ); bamboraapac_supported_payment_methods - }; + }); - static ref BAMBORAAPAC_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { - display_name: "Bambora Asia-Pacific", - description: "Bambora Asia-Pacific, provides comprehensive payment solutions, offering merchants smart and smooth payment processing capabilities.", - connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, - integration_status: enums::ConnectorIntegrationStatus::Sandbox, - }; +static BAMBORAAPAC_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Bambora Asia-Pacific", + description: "Bambora Asia-Pacific, provides comprehensive payment solutions, offering merchants smart and smooth payment processing capabilities.", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Sandbox, +}; - static ref BAMBORAAPAC_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); -} +static BAMBORAAPAC_SUPPORTED_WEBHOOK_FLOWS: [common_enums::EventClass; 0] = []; impl ConnectorSpecifications for Bamboraapac { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { - Some(&*BAMBORAAPAC_CONNECTOR_INFO) + Some(&BAMBORAAPAC_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { @@ -815,6 +820,6 @@ impl ConnectorSpecifications for Bamboraapac { } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { - Some(&*BAMBORAAPAC_SUPPORTED_WEBHOOK_FLOWS) + Some(&BAMBORAAPAC_SUPPORTED_WEBHOOK_FLOWS) } } diff --git a/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs index 090cd6dd0c0..d4e7d39ad12 100644 --- a/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs +++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs @@ -1,5 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; + use base64::Engine; use common_enums::enums; use common_utils::{ @@ -23,7 +25,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, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData, @@ -311,23 +316,6 @@ impl ConnectorCommon for Bankofamerica { } impl ConnectorValidation for Bankofamerica { - 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>, @@ -1095,4 +1083,123 @@ impl webhooks::IncomingWebhook for Bankofamerica { } } -impl ConnectorSpecifications for Bankofamerica {} +static BANKOFAMERICA_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::Visa, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + common_enums::CardNetwork::Maestro, + common_enums::CardNetwork::Interac, + ]; + + let mut bankofamerica_supported_payment_methods = SupportedPaymentMethods::new(); + + bankofamerica_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::GooglePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + bankofamerica_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::ApplePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + bankofamerica_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::SamsungPay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + bankofamerica_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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(), + } + }), + ), + }, + ); + + bankofamerica_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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(), + } + }), + ), + }, + ); + + bankofamerica_supported_payment_methods + }); + +static BANKOFAMERICA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Bank Of America", + description: + "It is the second-largest banking institution in the United States and the second-largest bank in the world by market capitalization ", + connector_type: enums::HyperswitchConnectorCategory::BankAcquirer, + integration_status: enums::ConnectorIntegrationStatus::Live, + }; + +static BANKOFAMERICA_SUPPORTED_WEBHOOK_FLOWS: [common_enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Bankofamerica { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&BANKOFAMERICA_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*BANKOFAMERICA_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&BANKOFAMERICA_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/boku.rs b/crates/hyperswitch_connectors/src/connectors/boku.rs index 2eda599e661..75a8c20324a 100644 --- a/crates/hyperswitch_connectors/src/connectors/boku.rs +++ b/crates/hyperswitch_connectors/src/connectors/boku.rs @@ -1,4 +1,5 @@ pub mod transformers; +use std::sync::LazyLock; use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use common_enums::enums; @@ -21,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, RefundSyncRouterData, RefundsRouterData, @@ -49,7 +53,7 @@ use crate::{ constants::{headers, UNSUPPORTED_ERROR_MESSAGE}, metrics, types::ResponseRouterData, - utils::{construct_not_supported_error_report, convert_amount}, + utils::convert_amount, }; #[derive(Clone)] @@ -174,24 +178,7 @@ impl ConnectorCommon for Boku { } } -impl ConnectorValidation for Boku { - 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( - construct_not_supported_error_report(capture_method, self.id()), - ), - } - } -} +impl ConnectorValidation for Boku {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Boku { //TODO: implement sessions flow @@ -718,4 +705,92 @@ fn get_xml_deserialized( } } -impl ConnectorSpecifications for Boku {} +static BOKU_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let mut boku_supported_payment_methods = SupportedPaymentMethods::new(); + + boku_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::Dana, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + boku_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::Gcash, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + boku_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::GoPay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + boku_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::KakaoPay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + boku_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::Momo, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: None, + }, + ); + + boku_supported_payment_methods +}); + +static BOKU_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Boku", + description: "Boku, Inc. is a mobile payments company that allows businesses to collect online payments through both carrier billing and mobile wallets.", + connector_type: enums::HyperswitchConnectorCategory::AlternativePaymentMethod, + integration_status: enums::ConnectorIntegrationStatus::Alpha, +}; + +static BOKU_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Boku { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&BOKU_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*BOKU_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&BOKU_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee.rs b/crates/hyperswitch_connectors/src/connectors/chargebee.rs index f6f38d20c04..19ec99fc1d0 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee.rs @@ -1,6 +1,7 @@ pub mod transformers; use base64::Engine; +use common_enums::enums; use common_utils::{ consts::BASE64_ENGINE, errors::CustomResult, @@ -30,7 +31,7 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ConnectorInfo, PaymentsResponseData, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, @@ -783,4 +784,21 @@ impl webhooks::IncomingWebhook for Chargebee { } } -impl ConnectorSpecifications for Chargebee {} +static CHARGEBEE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Chargebee", + description: "Chargebee is a Revenue Growth Management (RGM) platform that helps subscription businesses manage subscriptions, billing, revenue recognition, collections, and customer retention, essentially streamlining the entire subscription lifecycle.", + connector_type: enums::HyperswitchConnectorCategory::RevenueGrowthManagementPlatform, + integration_status: enums::ConnectorIntegrationStatus::Alpha, +}; + +static CHARGEBEE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments]; + +impl ConnectorSpecifications for Chargebee { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&CHARGEBEE_CONNECTOR_INFO) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&CHARGEBEE_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/cryptopay.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs index 723e662b400..ece0eaa6b48 100644 --- a/crates/hyperswitch_connectors/src/connectors/cryptopay.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs @@ -1,6 +1,8 @@ pub mod transformers; +use std::sync::LazyLock; use base64::Engine; +use common_enums::enums; use common_utils::{ crypto::{self, GenerateDigest, SignMessage}, date_time, @@ -23,7 +25,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, PaymentsSyncRouterData}, }; use hyperswitch_interfaces::{ @@ -315,7 +320,7 @@ impl ConnectorValidation for Cryptopay { &self, _data: &PaymentsSyncData, _is_three_ds: bool, - _status: common_enums::enums::AttemptStatus, + _status: enums::AttemptStatus, _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { // since we can make psync call with our reference_id, having connector_transaction_id is not an mandatory criteria @@ -501,4 +506,48 @@ impl webhooks::IncomingWebhook for Cryptopay { } } -impl ConnectorSpecifications for Cryptopay {} +static CRYPTOPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let mut cryptopay_supported_payment_methods = SupportedPaymentMethods::new(); + + cryptopay_supported_payment_methods.add( + enums::PaymentMethod::Crypto, + enums::PaymentMethodType::CryptoCurrency, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::NotSupported, + supported_capture_methods, + specific_features: None, + }, + ); + + cryptopay_supported_payment_methods + }); + +static CRYPTOPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Cryptopay", + description: "Simple and secure solution to buy and manage crypto. Make quick international transfers, spend your BTC, ETH and other crypto assets.", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Live, +}; + +static CRYPTOPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments]; + +impl ConnectorSpecifications for Cryptopay { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&CRYPTOPAY_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*CRYPTOPAY_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&CRYPTOPAY_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource.rs b/crates/hyperswitch_connectors/src/connectors/cybersource.rs index 0a1061e2c15..b4f1cbe10b1 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource.rs @@ -1,4 +1,5 @@ pub mod transformers; +use std::sync::LazyLock; use base64::Engine; use common_enums::enums; @@ -29,7 +30,10 @@ use hyperswitch_domain_models::{ PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, PaymentsResponseData, + RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, @@ -299,22 +303,6 @@ impl ConnectorCommon for Cybersource { } impl ConnectorValidation for Cybersource { - 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>, @@ -1751,4 +1739,133 @@ impl webhooks::IncomingWebhook for Cybersource { } } -impl ConnectorSpecifications for Cybersource {} +static CYBERSOURCE_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::Visa, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + common_enums::CardNetwork::Maestro, + ]; + + let mut cybersource_supported_payment_methods = SupportedPaymentMethods::new(); + + cybersource_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + cybersource_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + cybersource_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::ApplePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + cybersource_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::GooglePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + cybersource_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::Paze, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + cybersource_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::SamsungPay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + cybersource_supported_payment_methods + }); + +static CYBERSOURCE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Cybersource", + description: "Cybersource provides payments, fraud protection, integrations, and support to help businesses grow with a digital-first approach.", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Live, +}; + +static CYBERSOURCE_SUPPORTED_WEBHOOK_FLOWS: [common_enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Cybersource { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&CYBERSOURCE_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*CYBERSOURCE_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&CYBERSOURCE_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/datatrans.rs b/crates/hyperswitch_connectors/src/connectors/datatrans.rs index d6bde3068c8..0bbd6c82165 100644 --- a/crates/hyperswitch_connectors/src/connectors/datatrans.rs +++ b/crates/hyperswitch_connectors/src/connectors/datatrans.rs @@ -1,4 +1,5 @@ pub mod transformers; +use std::sync::LazyLock; use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use base64::Engine; @@ -24,7 +25,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, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData, @@ -182,28 +186,6 @@ impl ConnectorCommon for Datatrans { } impl ConnectorValidation for Datatrans { - //TODO: implement functions when support enabled - fn validate_connector_against_payment_request( - &self, - capture_method: Option<CaptureMethod>, - _payment_method: PaymentMethod, - _pmt: Option<PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - CaptureMethod::Automatic - | CaptureMethod::Manual - | CaptureMethod::SequentialAutomatic => Ok(()), - CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => { - Err(errors::ConnectorError::NotSupported { - message: capture_method.to_string(), - connector: self.id(), - } - .into()) - } - } - } - fn validate_mandate_payment( &self, _pm_type: Option<PaymentMethodType>, @@ -812,4 +794,90 @@ impl IncomingWebhook for Datatrans { } } -impl ConnectorSpecifications for Datatrans {} +static DATATRANS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { + let supported_capture_methods = vec![ + CaptureMethod::Automatic, + CaptureMethod::Manual, + CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::UnionPay, + common_enums::CardNetwork::Maestro, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::CartesBancaires, + ]; + + let mut datatrans_supported_payment_methods = SupportedPaymentMethods::new(); + + datatrans_supported_payment_methods.add( + PaymentMethod::Card, + PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: common_enums::enums::FeatureStatus::Supported, + refunds: common_enums::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(), + } + }), + ), + }, + ); + + datatrans_supported_payment_methods.add( + PaymentMethod::Card, + PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: common_enums::enums::FeatureStatus::Supported, + refunds: common_enums::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.clone(), + } + }), + ), + }, + ); + + datatrans_supported_payment_methods + }); + +static DATATRANS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Datatrans", + description: + "Datatrans is a payment gateway that facilitates the processing of payments, including hosting smart payment forms and correctly routing payment information.", + connector_type: common_enums::enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: common_enums::enums::ConnectorIntegrationStatus::Live, +}; + +static DATATRANS_SUPPORTED_WEBHOOK_FLOWS: [common_enums::enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Datatrans { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&DATATRANS_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*DATATRANS_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> { + Some(&DATATRANS_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/gocardless.rs b/crates/hyperswitch_connectors/src/connectors/gocardless.rs index 2ded0f53f19..b94ba5b2787 100644 --- a/crates/hyperswitch_connectors/src/connectors/gocardless.rs +++ b/crates/hyperswitch_connectors/src/connectors/gocardless.rs @@ -1,5 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; + use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use common_enums::enums; use common_utils::{ @@ -44,7 +46,6 @@ use hyperswitch_interfaces::{ types::{self, PaymentsSyncType, Response}, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; -use lazy_static::lazy_static; use masking::{Mask, PeekInterface}; use transformers as gocardless; @@ -876,8 +877,8 @@ impl IncomingWebhook for Gocardless { } } -lazy_static! { - static ref GOCARDLESS_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { +static GOCARDLESS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::SequentialAutomatic, @@ -919,19 +920,24 @@ lazy_static! { ); gocardless_supported_payment_methods - }; - static ref GOCARDLESS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { - display_name: "GoCardless", - description: "GoCardless is a fintech company that specialises in bank payments including recurring payments.", - connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, - integration_status: enums::ConnectorIntegrationStatus::Sandbox, - }; - static ref GOCARDLESS_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = vec![enums::EventClass::Payments, enums::EventClass::Refunds, enums::EventClass::Mandates]; -} + }); + +static GOCARDLESS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "GoCardless", + description: "GoCardless is a fintech company that specialises in bank payments including recurring payments.", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Sandbox, +}; + +static GOCARDLESS_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [ + enums::EventClass::Payments, + enums::EventClass::Refunds, + enums::EventClass::Mandates, +]; impl ConnectorSpecifications for Gocardless { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { - Some(&*GOCARDLESS_CONNECTOR_INFO) + Some(&GOCARDLESS_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { @@ -939,6 +945,6 @@ impl ConnectorSpecifications for Gocardless { } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { - Some(&*GOCARDLESS_SUPPORTED_WEBHOOK_FLOWS) + Some(&GOCARDLESS_SUPPORTED_WEBHOOK_FLOWS) } } diff --git a/crates/hyperswitch_connectors/src/connectors/nmi.rs b/crates/hyperswitch_connectors/src/connectors/nmi.rs index 8243fa3f0e7..cf948d21247 100644 --- a/crates/hyperswitch_connectors/src/connectors/nmi.rs +++ b/crates/hyperswitch_connectors/src/connectors/nmi.rs @@ -1,4 +1,6 @@ pub mod transformers; +use std::sync::LazyLock; + use api_models::webhooks::IncomingWebhookEvent; use common_enums::{enums, CallConnectorAction, PaymentAction}; use common_utils::{ @@ -21,7 +23,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, @@ -49,7 +54,7 @@ use transformers as nmi; use crate::{ types::ResponseRouterData, - utils::{self, construct_not_supported_error_report, convert_amount, get_header_key_value}, + utils::{self, convert_amount, get_header_key_value}, }; #[derive(Clone)] @@ -136,23 +141,6 @@ impl ConnectorCommon for Nmi { } impl ConnectorValidation for Nmi { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), 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( - construct_not_supported_error_report(capture_method, self.id()), - ), - } - } - fn validate_psync_reference_id( &self, _data: &PaymentsSyncData, @@ -1014,4 +1002,111 @@ impl ConnectorRedirectResponse for Nmi { } } -impl ConnectorSpecifications for Nmi {} +static NMI_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::Interac, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + common_enums::CardNetwork::Maestro, + ]; + + let mut nmi_supported_payment_methods = SupportedPaymentMethods::new(); + + nmi_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + nmi_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network, + } + }), + ), + }, + ); + + nmi_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::GooglePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + nmi_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::ApplePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: None, + }, + ); + + nmi_supported_payment_methods +}); + +static NMI_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "NMI", + description: "NMI is a global leader in embedded payments, powering more than $200 billion in payment volumes every year.", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Live, +}; + +static NMI_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] = + [enums::EventClass::Payments, enums::EventClass::Refunds]; + +impl ConnectorSpecifications for Nmi { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&NMI_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*NMI_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&NMI_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/noon.rs b/crates/hyperswitch_connectors/src/connectors/noon.rs index 1db28cd20bf..5d3a1be0640 100644 --- a/crates/hyperswitch_connectors/src/connectors/noon.rs +++ b/crates/hyperswitch_connectors/src/connectors/noon.rs @@ -1,4 +1,5 @@ pub mod transformers; +use std::sync::LazyLock; use api_models::webhooks::{ConnectorWebhookSecrets, IncomingWebhookEvent, ObjectReferenceId}; use base64::Engine; @@ -25,7 +26,10 @@ use hyperswitch_domain_models::{ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, PaymentsResponseData, + RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, @@ -910,4 +914,115 @@ impl webhooks::IncomingWebhook for Noon { } } -impl ConnectorSpecifications for Noon {} +static NOON_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::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + ]; + + let mut noon_supported_payment_methods = SupportedPaymentMethods::new(); + + noon_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + noon_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + noon_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::ApplePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + noon_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::GooglePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + noon_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::Paypal, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + noon_supported_payment_methods +}); + +static NOON_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Noon", + description: "Noon is a payment gateway and PSP enabling secure online transactions", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Live, +}; + +static NOON_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments]; + +impl ConnectorSpecifications for Noon { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&NOON_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*NOON_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&NOON_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/payeezy.rs b/crates/hyperswitch_connectors/src/connectors/payeezy.rs index 0f7c56817b2..569f765feb6 100644 --- a/crates/hyperswitch_connectors/src/connectors/payeezy.rs +++ b/crates/hyperswitch_connectors/src/connectors/payeezy.rs @@ -1,8 +1,9 @@ pub mod transformers; +use std::sync::LazyLock; use api_models::webhooks::IncomingWebhookEvent; use base64::Engine; -use common_enums::{CaptureMethod, PaymentMethod, PaymentMethodType}; +use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::ByteSliceExt, @@ -21,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, PaymentsCancelRouterData, PaymentsCaptureRouterData, RefundsRouterData, @@ -45,9 +49,7 @@ use rand::distributions::DistString; use ring::hmac; use transformers as payeezy; -use crate::{ - constants::headers, types::ResponseRouterData, utils::construct_not_implemented_error_report, -}; +use crate::{constants::headers, types::ResponseRouterData}; #[derive(Debug, Clone)] pub struct Payeezy; @@ -154,24 +156,7 @@ impl ConnectorCommon for Payeezy { } } -impl ConnectorValidation for Payeezy { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<CaptureMethod>, - _payment_method: PaymentMethod, - _pmt: Option<PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - CaptureMethod::Automatic - | CaptureMethod::Manual - | CaptureMethod::SequentialAutomatic => Ok(()), - CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => Err( - construct_not_implemented_error_report(capture_method, self.id()), - ), - } - } -} +impl ConnectorValidation for Payeezy {} impl api::Payment for Payeezy {} @@ -596,4 +581,63 @@ impl IncomingWebhook for Payeezy { } } -impl ConnectorSpecifications for Payeezy {} +static PAYEEZY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_networks = vec![ + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::Discover, + ]; + + let mut payeezy_supported_payment_methods = SupportedPaymentMethods::new(); + + payeezy_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: 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, + } + }), + ), + }, + ); + + payeezy_supported_payment_methods +}); + +static PAYEEZY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Payeezy", + description: "Payeezy is a payment gateway platform that facilitates online and mobile payment processing for businesses. It provides a range of features, including support for various payment methods, security features like PCI-DSS compliance and tokenization, and tools for managing transactions and customer interactions.", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Alpha, +}; + +static PAYEEZY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Payeezy { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&PAYEEZY_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*PAYEEZY_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&PAYEEZY_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/payme.rs b/crates/hyperswitch_connectors/src/connectors/payme.rs index a5dbe2f6322..a7e7a50c47b 100644 --- a/crates/hyperswitch_connectors/src/connectors/payme.rs +++ b/crates/hyperswitch_connectors/src/connectors/payme.rs @@ -1,4 +1,5 @@ pub mod transformers; +use std::sync::LazyLock; use api_models::enums::AuthenticationType; use common_enums::enums; @@ -27,7 +28,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, RefundsRouterData, @@ -1263,4 +1267,99 @@ impl webhooks::IncomingWebhook for Payme { } } -impl ConnectorSpecifications for Payme {} +static PAYME_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::AmericanExpress, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + ]; + + let mut payme_supported_payment_methods = SupportedPaymentMethods::new(); + + payme_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + payme_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + payme_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::ApplePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + payme_supported_payment_methods +}); + +static PAYME_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Payme", + description: "Payme is a payment gateway enabling secure online transactions", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Live, +}; + +static PAYME_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [ + enums::EventClass::Payments, + enums::EventClass::Refunds, + enums::EventClass::Disputes, +]; + +impl ConnectorSpecifications for Payme { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&PAYME_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*PAYME_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&PAYME_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/paypal.rs b/crates/hyperswitch_connectors/src/connectors/paypal.rs index 8831f49900c..b92c53c327b 100644 --- a/crates/hyperswitch_connectors/src/connectors/paypal.rs +++ b/crates/hyperswitch_connectors/src/connectors/paypal.rs @@ -1,5 +1,5 @@ pub mod transformers; -use std::fmt::Write; +use std::{fmt::Write, sync::LazyLock}; use base64::Engine; use common_enums::{enums, CallConnectorAction, PaymentAction}; @@ -34,7 +34,8 @@ use hyperswitch_domain_models::{ SdkPaymentsSessionUpdateData, SetupMandateRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ - PaymentsResponseData, RefundsResponseData, VerifyWebhookSourceResponseData, + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, VerifyWebhookSourceResponseData, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, @@ -369,22 +370,6 @@ impl ConnectorCommon for Paypal { } impl ConnectorValidation for Paypal { - 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( - connector_utils::construct_not_implemented_error_report(capture_method, self.id()), - ), - } - } fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, @@ -2348,4 +2333,151 @@ impl ConnectorErrorTypeMapping for Paypal { } } -impl ConnectorSpecifications for Paypal {} +static PAYPAL_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_capture_methods_bank_redirect = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + ]; + + let mut paypal_supported_payment_methods = SupportedPaymentMethods::new(); + + paypal_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + paypal_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + 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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network, + } + }), + ), + }, + ); + + paypal_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::Paypal, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + paypal_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Eps, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods_bank_redirect.clone(), + specific_features: None, + }, + ); + + paypal_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Giropay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods_bank_redirect.clone(), + specific_features: None, + }, + ); + + paypal_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Ideal, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods_bank_redirect.clone(), + specific_features: None, + }, + ); + + paypal_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Sofort, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods_bank_redirect.clone(), + specific_features: None, + }, + ); + + paypal_supported_payment_methods +}); + +static PAYPAL_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Paypal", + description: "PayPal is a global online payment system that enables individuals and businesses to send and receive money electronically.", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Live, +}; + +static PAYPAL_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [ + enums::EventClass::Payments, + enums::EventClass::Refunds, + enums::EventClass::Disputes, +]; + +impl ConnectorSpecifications for Paypal { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&PAYPAL_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*PAYPAL_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&PAYPAL_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/plaid.rs b/crates/hyperswitch_connectors/src/connectors/plaid.rs index f1da95fe7f5..501587e4822 100644 --- a/crates/hyperswitch_connectors/src/connectors/plaid.rs +++ b/crates/hyperswitch_connectors/src/connectors/plaid.rs @@ -1,6 +1,8 @@ pub mod transformers; +use std::sync::LazyLock; use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; +use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, @@ -19,7 +21,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsPostProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData}, }; use hyperswitch_interfaces::{ @@ -443,4 +448,47 @@ impl IncomingWebhook for Plaid { } } -impl ConnectorSpecifications for Plaid {} +static PLAID_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let mut plaid_supported_payment_methods = SupportedPaymentMethods::new(); + + plaid_supported_payment_methods.add( + enums::PaymentMethod::OpenBanking, + enums::PaymentMethodType::OpenBankingPIS, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::NotSupported, + supported_capture_methods, + specific_features: None, + }, + ); + + plaid_supported_payment_methods +}); + +static PLAID_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Plaid", + description: "Plaid is a data network that helps millions connect their financial accounts to apps like Venmo, SoFi, and Betterment. It powers tools used by Fortune 500 companies, major banks, and leading fintechs to enable easier, smarter financial lives.", + connector_type: enums::HyperswitchConnectorCategory::AuthenticationProvider, + integration_status: enums::ConnectorIntegrationStatus::Beta, +}; + +static PLAID_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Plaid { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&PLAID_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*PLAID_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&PLAID_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/powertranz.rs b/crates/hyperswitch_connectors/src/connectors/powertranz.rs index b393bc836c5..b4f6654e9c2 100644 --- a/crates/hyperswitch_connectors/src/connectors/powertranz.rs +++ b/crates/hyperswitch_connectors/src/connectors/powertranz.rs @@ -1,6 +1,6 @@ pub mod transformers; -use std::fmt::Debug; +use std::{fmt::Debug, sync::LazyLock}; use api_models::enums::AuthenticationType; use common_enums::enums; @@ -46,7 +46,6 @@ use hyperswitch_interfaces::{ }, webhooks, }; -use lazy_static::lazy_static; use masking::{ExposeInterface, Mask}; use transformers as powertranz; @@ -609,8 +608,8 @@ impl webhooks::IncomingWebhook for Powertranz { } } -lazy_static! { - static ref POWERTRANZ_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { +static POWERTRANZ_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, @@ -620,6 +619,7 @@ lazy_static! { let supported_card_network = vec![ common_enums::CardNetwork::Visa, common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::AmericanExpress, ]; let mut powertranz_supported_payment_methods = SupportedPaymentMethods::new(); @@ -627,7 +627,7 @@ lazy_static! { powertranz_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(), @@ -640,13 +640,13 @@ lazy_static! { } }), ), - } + }, ); powertranz_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(), @@ -659,27 +659,24 @@ lazy_static! { } }), ), - } + }, ); powertranz_supported_payment_methods - }; + }); - static ref POWERTRANZ_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { - display_name: "Powertranz", - description: - "Powertranz is a leading payment gateway serving the Caribbean and parts of Central America ", - connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, - integration_status: enums::ConnectorIntegrationStatus::Alpha, - }; - - static ref POWERTRANZ_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); +static POWERTRANZ_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Powertranz", + description: "Powertranz is a leading payment gateway serving the Caribbean and parts of Central America ", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Alpha, +}; -} +static POWERTRANZ_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Powertranz { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { - Some(&*POWERTRANZ_CONNECTOR_INFO) + Some(&POWERTRANZ_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { @@ -687,6 +684,6 @@ impl ConnectorSpecifications for Powertranz { } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { - Some(&*POWERTRANZ_SUPPORTED_WEBHOOK_FLOWS) + Some(&POWERTRANZ_SUPPORTED_WEBHOOK_FLOWS) } } diff --git a/crates/hyperswitch_connectors/src/connectors/rapyd.rs b/crates/hyperswitch_connectors/src/connectors/rapyd.rs index 8f0474c5e58..d639860fd5d 100644 --- a/crates/hyperswitch_connectors/src/connectors/rapyd.rs +++ b/crates/hyperswitch_connectors/src/connectors/rapyd.rs @@ -1,4 +1,5 @@ pub mod transformers; +use std::sync::LazyLock; use api_models::webhooks::IncomingWebhookEvent; use base64::Engine; @@ -47,7 +48,6 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; -use lazy_static::lazy_static; use masking::{ExposeInterface, Mask, PeekInterface, Secret}; use rand::distributions::{Alphanumeric, DistString}; use ring::hmac; @@ -950,104 +950,104 @@ impl IncomingWebhook for Rapyd { } } -lazy_static! { - static ref RAPYD_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::AmericanExpress, - common_enums::CardNetwork::Visa, - common_enums::CardNetwork::JCB, - common_enums::CardNetwork::DinersClub, - common_enums::CardNetwork::UnionPay, - common_enums::CardNetwork::Mastercard, - common_enums::CardNetwork::Discover, - ]; - - let mut rapyd_supported_payment_methods = SupportedPaymentMethods::new(); - - rapyd_supported_payment_methods.add( - enums::PaymentMethod::Wallet, - enums::PaymentMethodType::ApplePay, - PaymentMethodDetails{ - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods.clone(), - specific_features: None, - } - ); - - rapyd_supported_payment_methods.add( - enums::PaymentMethod::Wallet, - enums::PaymentMethodType::GooglePay, - PaymentMethodDetails{ - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods.clone(), - specific_features: None, - } - ); - - rapyd_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::Supported, - no_three_ds: common_enums::FeatureStatus::Supported, - supported_card_networks: supported_card_network.clone(), - } - }), - ), - } - ); - - rapyd_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::Supported, - no_three_ds: common_enums::FeatureStatus::Supported, - supported_card_networks: supported_card_network.clone(), - } - }), - ), - } - ); - - rapyd_supported_payment_methods - }; - - static ref RAPYD_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { - display_name: "Rapyd", - description: - "Rapyd is a fintech company that enables businesses to collect payments in local currencies across the globe ", - connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, - integration_status: enums::ConnectorIntegrationStatus::Sandbox, - }; - - static ref RAPYD_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = vec![enums::EventClass::Payments, enums::EventClass::Refunds, enums::EventClass::Disputes]; +static RAPYD_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::AmericanExpress, + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::UnionPay, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Discover, + ]; + + let mut rapyd_supported_payment_methods = SupportedPaymentMethods::new(); + + rapyd_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::ApplePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + rapyd_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::GooglePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + rapyd_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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + rapyd_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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + rapyd_supported_payment_methods +}); + +static RAPYD_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Rapyd", + description: "Rapyd is a fintech company that enables businesses to collect payments in local currencies across the globe ", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Sandbox, +}; -} +static RAPYD_SUPPORTED_WEBHOOK_FLOWS: [common_enums::EventClass; 3] = [ + enums::EventClass::Payments, + enums::EventClass::Refunds, + enums::EventClass::Disputes, +]; impl ConnectorSpecifications for Rapyd { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { - Some(&*RAPYD_CONNECTOR_INFO) + Some(&RAPYD_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { @@ -1055,6 +1055,6 @@ impl ConnectorSpecifications for Rapyd { } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { - Some(&*RAPYD_SUPPORTED_WEBHOOK_FLOWS) + Some(&RAPYD_SUPPORTED_WEBHOOK_FLOWS) } } diff --git a/crates/hyperswitch_connectors/src/connectors/shift4.rs b/crates/hyperswitch_connectors/src/connectors/shift4.rs index 0503a55195d..3af15de507f 100644 --- a/crates/hyperswitch_connectors/src/connectors/shift4.rs +++ b/crates/hyperswitch_connectors/src/connectors/shift4.rs @@ -1,4 +1,5 @@ pub mod transformers; +use std::sync::LazyLock; use api_models::webhooks::IncomingWebhookEvent; use common_enums::enums; @@ -45,7 +46,6 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; -use lazy_static::lazy_static; use masking::Mask; use transformers::{self as shift4, Shift4PaymentsRequest, Shift4RefundRequest}; @@ -847,224 +847,118 @@ impl IncomingWebhook for Shift4 { } } -lazy_static! { - static ref SHIFT4_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { - let supported_capture_methods = vec![ - enums::CaptureMethod::Automatic, - enums::CaptureMethod::Manual, - enums::CaptureMethod::SequentialAutomatic, - ]; - - let supported_capture_methods2 = vec![ - enums::CaptureMethod::Automatic, - ]; +static SHIFT4_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::Visa, + common_enums::CardNetwork::Mastercard, + ]; + + let mut shift4_supported_payment_methods = SupportedPaymentMethods::new(); + + shift4_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Eps, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + shift4_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Giropay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + shift4_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Ideal, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + shift4_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Sofort, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + shift4_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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + shift4_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::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); - let supported_card_network = vec![ - common_enums::CardNetwork::Visa, - common_enums::CardNetwork::Mastercard, - ]; + shift4_supported_payment_methods +}); - let mut shift4_supported_payment_methods = SupportedPaymentMethods::new(); - - shift4_supported_payment_methods.add( - enums::PaymentMethod::BankRedirect, - enums::PaymentMethodType::Eps, - PaymentMethodDetails{ - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods.clone(), - specific_features: None - } - ); - - shift4_supported_payment_methods.add( - enums::PaymentMethod::BankRedirect, - enums::PaymentMethodType::Giropay, - PaymentMethodDetails{ - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods.clone(), - specific_features: None - } - ); - - shift4_supported_payment_methods.add( - enums::PaymentMethod::BankRedirect, - enums::PaymentMethodType::Ideal, - PaymentMethodDetails{ - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods.clone(), - specific_features: None - } - ); - - shift4_supported_payment_methods.add( - enums::PaymentMethod::BankRedirect, - enums::PaymentMethodType::Trustly, - PaymentMethodDetails { - mandates: enums::FeatureStatus::Supported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods2.clone(), - specific_features: None, - }, - ); - - shift4_supported_payment_methods.add( - enums::PaymentMethod::BankRedirect, - enums::PaymentMethodType::Sofort, - PaymentMethodDetails{ - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods.clone(), - specific_features: None - } - ); - - shift4_supported_payment_methods.add( - enums::PaymentMethod::BankRedirect, - enums::PaymentMethodType::Blik, - PaymentMethodDetails{ - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods2.clone(), - specific_features: None - } - ); - - shift4_supported_payment_methods.add( - enums::PaymentMethod::Voucher, - enums::PaymentMethodType::Boleto, - PaymentMethodDetails{ - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods2.clone(), - specific_features: None - } - ); - - shift4_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::Supported, - no_three_ds: common_enums::FeatureStatus::Supported, - supported_card_networks: supported_card_network.clone(), - } - }), - ), - } - ); - - shift4_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::Supported, - no_three_ds: common_enums::FeatureStatus::Supported, - supported_card_networks: supported_card_network.clone(), - } - }), - ), - } - ); - - shift4_supported_payment_methods.add( - enums::PaymentMethod::Wallet, - enums::PaymentMethodType::AliPay, - PaymentMethodDetails { - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods2.clone(), - specific_features: None, - }, - ); - - shift4_supported_payment_methods.add( - enums::PaymentMethod::Wallet, - enums::PaymentMethodType::WeChatPay, - PaymentMethodDetails { - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods2.clone(), - specific_features: None, - }, - ); - - shift4_supported_payment_methods.add( - enums::PaymentMethod::Wallet, - enums::PaymentMethodType::Paysera, - PaymentMethodDetails { - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods2.clone(), - specific_features: None, - }, - ); - - shift4_supported_payment_methods.add( - enums::PaymentMethod::Wallet, - enums::PaymentMethodType::Skrill, - PaymentMethodDetails { - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods2.clone(), - specific_features: None, - }, - ); - - shift4_supported_payment_methods.add( - enums::PaymentMethod::PayLater, - enums::PaymentMethodType::Klarna, - PaymentMethodDetails { - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods2.clone(), - specific_features: None, - }, - ); - - shift4_supported_payment_methods.add( - enums::PaymentMethod::Crypto, - enums::PaymentMethodType::CryptoCurrency, - PaymentMethodDetails { - mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods2.clone(), - specific_features: None, - }, - ); - - shift4_supported_payment_methods - }; - - static ref SHIFT4_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { - display_name: "Shift4", - description: - "Shift4 Payments, Inc. is an American payment processing company based in Allentown, Pennsylvania. ", - connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, - integration_status: enums::ConnectorIntegrationStatus::Live, - }; - - static ref SHIFT4_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = vec![enums::EventClass::Payments, enums::EventClass::Refunds]; +static SHIFT4_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Shift4", + description: "Shift4 Payments, Inc. is an American payment processing company based in Allentown, Pennsylvania. ", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Live, +}; -} +static SHIFT4_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] = + [enums::EventClass::Payments, enums::EventClass::Refunds]; impl ConnectorSpecifications for Shift4 { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { - Some(&*SHIFT4_CONNECTOR_INFO) + Some(&SHIFT4_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { @@ -1072,6 +966,6 @@ impl ConnectorSpecifications for Shift4 { } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { - Some(&*SHIFT4_SUPPORTED_WEBHOOK_FLOWS) + Some(&SHIFT4_SUPPORTED_WEBHOOK_FLOWS) } } diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs index a933d62355f..79f0bcc88d8 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs @@ -2,6 +2,7 @@ pub mod transformers; use std::collections::HashMap; +use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, @@ -23,7 +24,7 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ConnectorInfo, PaymentsResponseData, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, @@ -911,4 +912,22 @@ fn get_signature_elements_from_header( Ok(header_hashmap) } -impl ConnectorSpecifications for Stripebilling {} +static STRIPEBILLING_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Stripebilling", + description: "Stripe Billing manages subscriptions, recurring payments, and invoicing. It supports trials, usage-based billing, coupons, and automated retries.", + connector_type: enums::HyperswitchConnectorCategory::RevenueGrowthManagementPlatform, + integration_status: enums::ConnectorIntegrationStatus::Beta, +}; + +static STRIPEBILLING_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = + [enums::EventClass::Payments]; + +impl ConnectorSpecifications for Stripebilling { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&STRIPEBILLING_CONNECTOR_INFO) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&STRIPEBILLING_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay.rs b/crates/hyperswitch_connectors/src/connectors/trustpay.rs index cceb5d73411..d3a6a2cdf71 100644 --- a/crates/hyperswitch_connectors/src/connectors/trustpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/trustpay.rs @@ -1,4 +1,6 @@ pub mod transformers; +use std::sync::LazyLock; + use base64::Engine; use common_enums::{enums, PaymentAction}; use common_utils::{ @@ -25,7 +27,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData, @@ -1151,4 +1156,212 @@ impl utils::ConnectorErrorTypeMapping for Trustpay { } } -impl ConnectorSpecifications for Trustpay {} +static TRUSTPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + ]; + + let mut trustpay_supported_payment_methods = SupportedPaymentMethods::new(); + + trustpay_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(), + } + }), + ), + }, + ); + + trustpay_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, + } + }), + ), + }, + ); + + trustpay_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::GooglePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + trustpay_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::ApplePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Eps, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Giropay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Ideal, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Sofort, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Blik, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankTransfer, + enums::PaymentMethodType::SepaBankTransfer, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankTransfer, + enums::PaymentMethodType::InstantBankTransfer, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankTransfer, + enums::PaymentMethodType::InstantBankTransferFinland, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankTransfer, + enums::PaymentMethodType::InstantBankTransferPoland, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: None, + }, + ); + + trustpay_supported_payment_methods + }); + +static TRUSTPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Trustpay", + description: "TrustPay offers cross-border payment solutions for online businesses, including global card processing, local payment methods, business accounts, and reconciliation toolsβ€”all under one roof.", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Live, +}; + +static TRUSTPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [ + enums::EventClass::Payments, + enums::EventClass::Refunds, + enums::EventClass::Disputes, +]; + +impl ConnectorSpecifications for Trustpay { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&TRUSTPAY_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*TRUSTPAY_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&TRUSTPAY_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/worldline.rs b/crates/hyperswitch_connectors/src/connectors/worldline.rs index 6012782ed63..3e86ce3682f 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldline.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldline.rs @@ -1,6 +1,6 @@ pub mod transformers; -use std::fmt::Debug; +use std::{fmt::Debug, sync::LazyLock}; use base64::Engine; use common_enums::enums; @@ -46,7 +46,6 @@ use hyperswitch_interfaces::{ }, webhooks::{self, IncomingWebhookFlowError}, }; -use lazy_static::lazy_static; use masking::{ExposeInterface, Mask, PeekInterface}; use ring::hmac; use router_env::logger; @@ -826,8 +825,8 @@ impl webhooks::IncomingWebhook for Worldline { } } -lazy_static! { - static ref WORLDLINE_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { +static WORLDLINE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, @@ -890,7 +889,7 @@ lazy_static! { PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, - supported_capture_methods: supported_capture_methods.clone(), + supported_capture_methods, specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { @@ -904,20 +903,20 @@ lazy_static! { ); worldline_supported_payment_methods - }; - static ref WORLDLINE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { - display_name: "Worldline", - description: "Worldline, Europe's leading payment service provider", - connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, - integration_status: enums::ConnectorIntegrationStatus::Sandbox, - }; - static ref WORLDLINE_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = - vec![enums::EventClass::Payments]; -} + }); + +static WORLDLINE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Worldline", + description: "Worldpay is an industry leading payments technology and solutions company with unique capabilities to power omni-commerce across the globe.r", + connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, + integration_status: enums::ConnectorIntegrationStatus::Sandbox, +}; + +static WORLDLINE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments]; impl ConnectorSpecifications for Worldline { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { - Some(&*WORLDLINE_CONNECTOR_INFO) + Some(&WORLDLINE_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { @@ -925,6 +924,6 @@ impl ConnectorSpecifications for Worldline { } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { - Some(&*WORLDLINE_SUPPORTED_WEBHOOK_FLOWS) + Some(&WORLDLINE_SUPPORTED_WEBHOOK_FLOWS) } } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 374119bebbc..6ca40c66104 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -636,6 +636,44 @@ trustly = {currency="DKK, EUR, GBP, NOK, PLN, SEK" } blik = { country="PL" , currency = "PLN" } atome = { country = "SG, MY" , currency = "SGD, MYR" } +[pm_filters.boku] +dana = { country = "ID", currency = "IDR" } +gcash = { country = "PH", currency = "PHP" } +go_pay = { country = "ID", currency = "IDR" } +kakao_pay = { country = "KR", currency = "KRW" } +momo = { country = "VN", currency = "VND" } + +[pm_filters.nmi] +credit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +debit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +apple_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } +google_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "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,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } + +[pm_filters.paypal] +credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +paypal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +eps = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +giropay = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +ideal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } +sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" } + +[pm_filters.datatrans] +credit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } +debit = { country = "AL,AD,AM,AT,AZ,BY,BE,BA,BG,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GE,GR,HR,HU,IE,IS,IT,KZ,LI,LT,LU,LV,MC,MD,ME,MK,MT,NL,NO,PL,PT,RO,RU,SE,SI,SK,SM,TR,UA,VA", currency = "BHD,BIF,CHF,DJF,EUR,GBP,GNF,IQD,ISK,JPY,JOD,KMF,KRW,KWD,LYD,OMR,PYG,RWF,TND,UGX,USD,VND,VUV,XAF,XOF,XPF" } + +[pm_filters.bankofamerica] +credit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" } +debit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" } +apple_pay = { country = "AU,AT,BH,BE,BR,BG,CA,CL,CN,CO,CR,HR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,MC,ME,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" } +google_pay = { country = "AU,AT,BE,BR,CA,CL,CO,CR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" } +samsung_pay = { country = "AU,BH,BR,CA,CN,DK,FI,FR,DE,HK,IN,IT,JP,KZ,KR,KW,MY,NZ,NO,OM,QA,SA,SG,ZA,ES,SE,CH,TW,AE,GB,US", currency = "USD" } + +[pm_filters.payme] +credit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +debit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } +apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" } + #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } }
2025-07-30T07:03:19Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/8796) ## Description <!-- Describe your changes in detail --> Added connector specifications for Archipel, Bankofamerica, Boku, Chargebee, Cryptopay, Cybersource, Datatrans, Nmi, Noon, Payeezy, Payme, Paypal, Plaid, Stripebilling, Trustpay. ### 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 Matrix API: Request: ``` curl --location 'http://localhost:8080/feature_matrix' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_3ShwqeYwf04wnKtu5Ovbs9k0gkKeatSRsG4Gqha9ECBNLFM4G4qdlRDxydpa7IMh' ``` Response: ``` { "connector_count": 109, "connectors": [ { "name": "ARCHIPEL", "display_name": "Archipel", "description": "Full-service processor offering secure payment solutions and innovative banking technologies for businesses of all sizes.", "category": "payment_gateway", "integration_status": "live", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "payment_method_type_display_name": "Credit Card", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "DinersClub", "Discover", "CartesBancaires" ], "supported_countries": null, "supported_currencies": null }, { "payment_method": "card", "payment_method_type": "debit", "payment_method_type_display_name": "Debit Card", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "DinersClub", "Discover", "CartesBancaires" ], "supported_countries": null, "supported_currencies": null }, { "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_type_display_name": "Apple Pay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": null, "supported_currencies": null } ], "supported_webhook_flows": [] }, { "name": "BOKU", "display_name": "Boku", "description": "Boku, Inc. is a mobile payments company that allows businesses to collect online payments through both carrier billing and mobile wallets.", "category": "alternative_payment_method", "integration_status": "alpha", "supported_payment_methods": [ { "payment_method": "wallet", "payment_method_type": "dana", "payment_method_type_display_name": "DANA", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "IDN" ], "supported_currencies": [ "IDR" ] }, { "payment_method": "wallet", "payment_method_type": "go_pay", "payment_method_type_display_name": "GoPay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "IDN" ], "supported_currencies": [ "IDR" ] }, { "payment_method": "wallet", "payment_method_type": "kakao_pay", "payment_method_type_display_name": "KakaoPay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "KOR" ], "supported_currencies": [ "KRW" ] }, { "payment_method": "wallet", "payment_method_type": "momo", "payment_method_type_display_name": "MoMo", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "VNM" ], "supported_currencies": [ "VND" ] }, { "payment_method": "wallet", "payment_method_type": "gcash", "payment_method_type_display_name": "GCash", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "PHL" ], "supported_currencies": [ "PHP" ] } ], "supported_webhook_flows": [] }, { "name": "CHARGEBEE", "display_name": "Chargebee", "description": "Chargebee is a Revenue Growth Management (RGM) platform that helps subscription businesses manage subscriptions, billing, revenue recognition, collections, and customer retention, essentially streamlining the entire subscription lifecycle.", "category": "revenue_growth_management_platform", "integration_status": "alpha", "supported_payment_methods": null, "supported_webhook_flows": [ "payments" ] }, { "name": "CRYPTOPAY", "display_name": "Cryptopay", "description": "Simple and secure solution to buy and manage crypto. Make quick international transfers, spend your BTC, ETH and other crypto assets.", "category": "payment_gateway", "integration_status": "live", "supported_payment_methods": [ { "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_method_type_display_name": "Crypto", "mandates": "not_supported", "refunds": "not_supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": null, "supported_currencies": null } ], "supported_webhook_flows": [ "payments" ] }, { "name": "DATATRANS", "display_name": "Datatrans", "description": "Datatrans is a payment gateway that facilitates the processing of payments, including hosting smart payment forms and correctly routing payment information.", "category": "payment_gateway", "integration_status": "live", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "debit", "payment_method_type_display_name": "Debit Card", "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", "DinersClub", "Discover", "UnionPay", "Maestro", "Interac", "CartesBancaires" ], "supported_countries": [ "LIE", "TUR", "HRV", "KAZ", "GRC", "GBR", "DNK", "BEL", "GEO", "CHE", "MLT", "AUT", "LTU", "FRA", "AND", "CZE", "NLD", "VAT", "ALB", "MCO", "ISL", "SVN", "LVA", "BGR", "BLR", "SMR", "HUN", "IRL", "ITA", "DEU", "FIN", "SVK", "MKD", "RUS", "MDA", "UKR", "EST", "LUX", "MNE", "BIH", "SWE", "AZE", "CYP", "POL", "PRT", "ROU", "ESP", "NOR", "ARM" ], "supported_currencies": [ "KRW", "ISK", "KMF", "VND", "OMR", "JOD", "VUV", "XOF", "XPF", "DJF", "KWD", "EUR", "TND", "USD", "PYG", "IQD", "LYD", "GBP", "BIF", "RWF", "BHD", "JPY", "UGX", "GNF", "CHF", "XAF" ] }, { "payment_method": "card", "payment_method_type": "credit", "payment_method_type_display_name": "Credit Card", "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", "DinersClub", "Discover", "UnionPay", "Maestro", "Interac", "CartesBancaires" ], "supported_countries": [ "ROU", "BGR", "BEL", "BLR", "ALB", "GBR", "RUS", "MNE", "ESP", "DNK", "GEO", "LVA", "MCO", "MLT", "HRV", "FIN", "MDA", "KAZ", "BIH", "EST", "GRC", "ISL", "TUR", "POL", "VAT", "AND", "ITA", "SWE", "IRL", "NLD", "AUT", "SMR", "MKD", "UKR", "CZE", "LUX", "NOR", "SVK", "FRA", "HUN", "PRT", "CHE", "LIE", "LTU", "DEU", "ARM", "CYP", "SVN", "AZE" ], "supported_currencies": [ "XPF", "VND", "BHD", "BIF", "ISK", "TND", "UGX", "CHF", "EUR", "USD", "VUV", "IQD", "KMF", "GNF", "JOD", "JPY", "KRW", "GBP", "LYD", "OMR", "PYG", "RWF", "KWD", "XAF", "XOF", "DJF" ] } ], "supported_webhook_flows": [] }, { "name": "PLAID", "display_name": "Plaid", "description": "Plaid is a data network that helps millions connect their financial accounts to apps like Venmo, SoFi, and Betterment. It powers tools used by Fortune 500 companies, major banks, and leading fintechs to enable easier, smarter financial lives.", "category": "authentication_provider", "integration_status": "beta", "supported_payment_methods": [ { "payment_method": "open_banking", "payment_method_type": "open_banking_pis", "payment_method_type_display_name": "Open Banking PIS", "mandates": "not_supported", "refunds": "not_supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": null, "supported_currencies": [ "GBP", "EUR" ] } ], "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.116.0
30925ca5dd51be93e33ac4492b85c2322263b3fc
30925ca5dd51be93e33ac4492b85c2322263b3fc
juspay/hyperswitch
juspay__hyperswitch-8791
Bug: [BUG] Add changes for field CybersourceConsumerAuthInformation ### Bug Description Cybersource payments via Netcetera are failing for a France based acquirer in prod, the PR provides fix for the same by introducing field effective_authentication_type, and making sure semantic_version is sent. ### Expected Behavior Payments should pass ### Actual Behavior Payments are currently failing in prod a france based acquirer ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index da1237f3f4f..2112989969e 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -377,7 +377,7 @@ pub struct CybersourceConsumerAuthInformation { ucaf_authentication_data: Option<Secret<String>>, xid: Option<String>, directory_server_transaction_id: Option<Secret<String>>, - specification_version: Option<String>, + specification_version: Option<SemanticVersion>, /// This field specifies the 3ds version pa_specification_version: Option<SemanticVersion>, /// Verification response enrollment status. @@ -393,6 +393,15 @@ pub struct CybersourceConsumerAuthInformation { pares_status: Option<CybersourceParesStatus>, //This field is used to send the authentication date in yyyyMMDDHHMMSS format authentication_date: Option<String>, + /// This field indicates the 3D Secure transaction flow. It is only supported for secure transactions in France. + /// The possible values are - CH (Challenge), FD (Frictionless with delegation), FR (Frictionless) + effective_authentication_type: Option<EffectiveAuthenticationType>, +} + +#[derive(Debug, Serialize)] +pub enum EffectiveAuthenticationType { + CH, + FR, } #[derive(Debug, Serialize)] @@ -1232,6 +1241,15 @@ fn convert_metadata_to_merchant_defined_info(metadata: Value) -> Vec<MerchantDef vector } +impl From<common_enums::DecoupledAuthenticationType> for EffectiveAuthenticationType { + fn from(auth_type: common_enums::DecoupledAuthenticationType) -> Self { + match auth_type { + common_enums::DecoupledAuthenticationType::Challenge => Self::CH, + common_enums::DecoupledAuthenticationType::Frictionless => Self::FR, + } + } +} + impl TryFrom<( &CybersourceRouterData<&PaymentsAuthorizeRouterData>, @@ -1330,6 +1348,8 @@ impl date_time::DateFormat::YYYYMMDDHHmmss, ) .ok(); + let effective_authentication_type = authn_data.authentication_type.map(Into::into); + CybersourceConsumerAuthInformation { pares_status, ucaf_collection_indicator, @@ -1340,11 +1360,12 @@ impl .ds_trans_id .clone() .map(Secret::new), - specification_version: None, + specification_version: authn_data.message_version.clone(), pa_specification_version: authn_data.message_version.clone(), veres_enrolled: Some("Y".to_string()), eci_raw: authn_data.eci.clone(), authentication_date, + effective_authentication_type, } }); @@ -1418,6 +1439,7 @@ impl .authentication_data .as_ref() .map(|authn_data| { + let effective_authentication_type = authn_data.authentication_type.map(Into::into); let (ucaf_authentication_data, cavv, ucaf_collection_indicator) = if ccard.card_network == Some(common_enums::CardNetwork::Mastercard) { (Some(authn_data.cavv.clone()), None, Some("2".to_string())) @@ -1439,11 +1461,12 @@ impl .ds_trans_id .clone() .map(Secret::new), - specification_version: None, + specification_version: authn_data.message_version.clone(), pa_specification_version: authn_data.message_version.clone(), veres_enrolled: Some("Y".to_string()), eci_raw: authn_data.eci.clone(), authentication_date, + effective_authentication_type, } }); @@ -1520,6 +1543,8 @@ impl .authentication_data .as_ref() .map(|authn_data| { + let effective_authentication_type = authn_data.authentication_type.map(Into::into); + let (ucaf_authentication_data, cavv, ucaf_collection_indicator) = if token_data.card_network == Some(common_enums::CardNetwork::Mastercard) { (Some(authn_data.cavv.clone()), None, Some("2".to_string())) @@ -1541,11 +1566,12 @@ impl .ds_trans_id .clone() .map(Secret::new), - specification_version: None, + specification_version: authn_data.message_version.clone(), pa_specification_version: authn_data.message_version.clone(), veres_enrolled: Some("Y".to_string()), eci_raw: authn_data.eci.clone(), authentication_date, + effective_authentication_type, } }); @@ -1725,11 +1751,12 @@ impl directory_server_transaction_id: three_ds_info .three_ds_data .directory_server_transaction_id, - specification_version: three_ds_info.three_ds_data.specification_version, - pa_specification_version: None, + specification_version: three_ds_info.three_ds_data.specification_version.clone(), + pa_specification_version: three_ds_info.three_ds_data.specification_version.clone(), veres_enrolled: None, eci_raw: None, authentication_date: None, + effective_authentication_type: None, }); let merchant_defined_information = item @@ -1827,6 +1854,7 @@ impl veres_enrolled: None, eci_raw: None, authentication_date: None, + effective_authentication_type: None, }), merchant_defined_information, }) @@ -1971,6 +1999,7 @@ impl veres_enrolled: None, eci_raw: None, authentication_date: None, + effective_authentication_type: None, }), merchant_defined_information, }) @@ -2172,6 +2201,7 @@ impl TryFrom<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for Cybersour veres_enrolled: None, eci_raw: None, authentication_date: None, + effective_authentication_type: None, }, ), }) @@ -3221,7 +3251,7 @@ pub struct CybersourceConsumerAuthValidateResponse { cavv: Option<Secret<String>>, ucaf_authentication_data: Option<Secret<String>>, xid: Option<String>, - specification_version: Option<String>, + specification_version: Option<SemanticVersion>, directory_server_transaction_id: Option<Secret<String>>, indicator: Option<String>, } diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index c7ac3664835..9e6dd7ea3c7 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -683,6 +683,7 @@ pub struct AuthenticationData { pub message_version: Option<common_utils::types::SemanticVersion>, pub ds_trans_id: Option<String>, pub created_at: time::PrimitiveDateTime, + pub authentication_type: Option<common_enums::DecoupledAuthenticationType>, } #[derive(Debug, Clone)] diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs index acba2c35edc..10df4034c92 100644 --- a/crates/router/src/core/payments/types.rs +++ b/crates/router/src/core/payments/types.rs @@ -390,6 +390,7 @@ impl threeds_server_transaction_id, message_version, ds_trans_id: authentication.ds_trans_id.clone(), + authentication_type: authentication.authentication_type, }) } else { Err(errors::ApiErrorResponse::PaymentAuthenticationFailed { data: None }.into())
2025-07-28T10:17:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [X] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Context - Cybersource payments via Netcetera are failing for a France based acquirer in prod, the PR provides fix for the same by introducing field **_consumerAuthenticationInformation. effectiveAuthenticationType_** and making sure **_consumerAuthenticationInformation.specificationVersion** is sent. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 3. `crates/router/src/configs` 4. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> **Testing for field effective_authentication_type and specification_version** ### Step 1 - Call /payments **Curl** `curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: integ-custom' \ --header 'api-key: dev_TSUxfiSwiAelCPTr9xN2ValUdd1fvmeYg0AtMUwdJukRkTlCpHL9p2IWxn6fouYl' \ --data-raw '{ "amount": 2540, "currency": "USD", "profile_id": "pro_aKVBsBqyTIq2T1UIaapY", "confirm": true, "amount_to_capture": 2540, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "request_external_three_ds_authentication": true, "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "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" } }, "routing": { "type": "single", "data": "nmi" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4000000000002370", "card_exp_month": "08", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "999" } }, "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" } } }'` <img width="837" height="743" alt="Screenshot 2025-07-29 at 6 40 54β€―PM" src="https://github.com/user-attachments/assets/5810eda7-6dcf-474a-813b-eab7f2fb3e28" /> ### Step 2- Call /3ds/authentication via Netcetera **Curl** `curl --location 'http://localhost:8080/payments/pay_1tQlG51BwoiUpLE3YKBV/3ds/authentication' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_8891a001315d40d0a26d1028ad51fe0b' \ --data '{ "client_secret": "pay_1tQlG51BwoiUpLE3YKBV_secret_EqDy0WeEHEfkkOjUd9R0", "device_channel": "BRW", "threeds_method_comp_ind": "Y" }'` <img width="1035" height="782" alt="Screenshot 2025-07-29 at 6 41 14β€―PM" src="https://github.com/user-attachments/assets/0b683f45-472f-47fe-9ef8-84a8db019c3b" /> ### Step 3- Call /authorize via Cybersource `curl --location --request POST 'http://localhost:8080/payments/pay_1tQlG51BwoiUpLE3YKBV/merchant_1753777600/authorize/cybersource' \ --header 'api-key: dev_TSUxfiSwiAelCPTr9xN2ValUdd1fvmeYg0AtMUwdJukRkTlCpHL9p2IWxn6fouYl'` <img width="1035" height="750" alt="Screenshot 2025-07-29 at 6 44 11β€―PM" src="https://github.com/user-attachments/assets/6ae685e7-0816-4164-9fae-840cd5f2266e" /> **specificationVersion and effectiveAuthenticationType are getting populated, and are sent to Cybersource_** <img width="1488" height="343" alt="Screenshot 2025-07-29 at 3 25 00β€―PM" src="https://github.com/user-attachments/assets/a62d4e3d-a168-48a2-bd02-67c279b087ad" /> Please note - Effective authentication type is FR, since the test flow is Frictionless ## 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.115.0
8dc4061f9edb1ac2527216b2279a765d0b797523
8dc4061f9edb1ac2527216b2279a765d0b797523
juspay/hyperswitch
juspay__hyperswitch-8777
Bug: [FEAT] (CONNECTOR): Facilitapay webhook support add support for facilitapay webhooks
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 90aae593617..cfc8589bdf2 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -6157,8 +6157,8 @@ api_secret="Secret Key" key1="Username" [facilitapay.metadata.destination_account_number] name="destination_account_number" - label="Destination Account Number" - placeholder="Enter Destination Account Number" + label="Merchant Account Number" + placeholder="Enter Merchant's (to_bank_account_id) Account Number" required=true type="Text" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 704d85ea665..5e21a2246b0 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -4725,8 +4725,8 @@ key1 = "Username" [facilitapay.metadata.destination_account_number] name="destination_account_number" -label="Destination Account Number" -placeholder="Enter Destination Account Number" +label="Merchant Account Number" +placeholder="Enter Merchant's (to_bank_account_id) Account Number" required=true type="Text" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 22819c5d4be..a256b81af66 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -6139,8 +6139,8 @@ key1 = "Username" [facilitapay.metadata.destination_account_number] name="destination_account_number" -label="Destination Account Number" -placeholder="Enter Destination Account Number" +label="Merchant Account Number" +placeholder="Enter Merchant's (to_bank_account_id) Account Number" required=true type="Text" diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay.rs index 9b1a6486df4..ffb74cc3a87 100644 --- a/crates/hyperswitch_connectors/src/connectors/facilitapay.rs +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay.rs @@ -4,12 +4,13 @@ pub mod transformers; use common_enums::enums; use common_utils::{ + crypto, errors::CustomResult, - ext_traits::BytesExt, + ext_traits::{ByteSliceExt, BytesExt, ValueExt}, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; -use error_stack::{report, ResultExt}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data::{AccessToken, ErrorResponse, RouterData}, router_flow_types::{ @@ -30,8 +31,8 @@ use hyperswitch_domain_models::{ SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ - ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, - PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, + ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, + PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ @@ -46,18 +47,19 @@ use hyperswitch_interfaces::{ webhooks, }; use lazy_static::lazy_static; -use masking::{Mask, PeekInterface}; +use masking::{ExposeInterface, Mask, PeekInterface}; use requests::{ FacilitapayAuthRequest, FacilitapayCustomerRequest, FacilitapayPaymentsRequest, - FacilitapayRefundRequest, FacilitapayRouterData, + FacilitapayRouterData, }; use responses::{ FacilitapayAuthResponse, FacilitapayCustomerResponse, FacilitapayPaymentsResponse, - FacilitapayRefundResponse, + FacilitapayRefundResponse, FacilitapayWebhookEventType, }; use transformers::parse_facilitapay_error_response; use crate::{ + connectors::facilitapay::responses::FacilitapayVoidResponse, constants::headers, types::{RefreshTokenRouterData, ResponseRouterData}, utils::{self, RefundsRequestData}, @@ -581,12 +583,10 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo } } -impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Facilitapay {} - -impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Facilitapay { +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Facilitapay { fn get_headers( &self, - req: &RefundsRouterData<Execute>, + req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) @@ -598,30 +598,81 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Facilit fn get_url( &self, - req: &RefundsRouterData<Execute>, + req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( - "{}/transactions/{}/refund_received_transaction", + "{}/transactions/{}/refund", self.base_url(connectors), req.request.connector_transaction_id )) } - fn get_request_body( + fn build_request( + &self, + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Get) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { + let response: FacilitapayVoidResponse = res + .response + .parse_struct("FacilitapayCancelResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Facilitapay { + fn get_headers( &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, - )?; + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } - let connector_router_data = FacilitapayRouterData::from((refund_amount, req)); - let connector_req = FacilitapayRefundRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) + 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> { + Ok(format!( + "{}/transactions/{}/refund_received_transaction", + self.base_url(connectors), + req.request.connector_transaction_id + )) } fn build_request( @@ -629,16 +680,22 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Facilit req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { + // Validate that this is a full refund + if req.request.payment_amount != req.request.refund_amount { + return Err(errors::ConnectorError::NotSupported { + message: "Partial refund not supported by Facilitapay".to_string(), + connector: "Facilitapay", + } + .into()); + } + let request = RequestBuilder::new() - .method(Method::Post) + .method(Method::Get) .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)) } @@ -743,25 +800,117 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Facilitap #[async_trait::async_trait] impl webhooks::IncomingWebhook for Facilitapay { + async fn verify_webhook_source( + &self, + request: &webhooks::IncomingWebhookRequestDetails<'_>, + _merchant_id: &common_utils::id_type::MerchantId, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: crypto::Encryptable<masking::Secret<serde_json::Value>>, + _connector_name: &str, + ) -> CustomResult<bool, errors::ConnectorError> { + let webhook_body: responses::FacilitapayWebhookNotification = request + .body + .parse_struct("FacilitapayWebhookNotification") + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + + let connector_webhook_secrets = match connector_webhook_details { + Some(secret_value) => { + let secret = secret_value + .parse_value::<api_models::admin::MerchantConnectorWebhookDetails>( + "MerchantConnectorWebhookDetails", + ) + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + secret.merchant_secret.expose() + } + None => "default_secret".to_string(), + }; + + // FacilitaPay uses a simple 4-digit secret for verification + Ok(webhook_body.notification.secret.peek() == &connector_webhook_secrets) + } + fn get_webhook_object_reference_id( &self, - _request: &webhooks::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let webhook_body: responses::FacilitapayWebhookNotification = request + .body + .parse_struct("FacilitapayWebhookNotification") + .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + + // Extract transaction ID from the webhook data + let transaction_id = match &webhook_body.notification.data { + responses::FacilitapayWebhookData::Transaction { transaction_id } + | responses::FacilitapayWebhookData::CardPayment { transaction_id, .. } => { + transaction_id.clone() + } + responses::FacilitapayWebhookData::Exchange { + transaction_ids, .. + } + | responses::FacilitapayWebhookData::Wire { + transaction_ids, .. + } + | responses::FacilitapayWebhookData::WireError { + transaction_ids, .. + } => transaction_ids + .first() + .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)? + .clone(), + }; + + // For refund webhooks, Facilitapay sends the original payment transaction ID + // not the refund transaction ID + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId(transaction_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: responses::FacilitapayWebhookNotification = request + .body + .parse_struct("FacilitapayWebhookNotification") + .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; + + // Note: For "identified" events, we need additional logic to determine if it's cross-currency + // Since we don't have access to the payment data here, we'll default to Success for now + // The actual status determination happens in the webhook processing flow + let event = match webhook_body.notification.event_type { + FacilitapayWebhookEventType::ExchangeCreated => { + api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing + } + FacilitapayWebhookEventType::Identified + | FacilitapayWebhookEventType::PaymentApproved + | FacilitapayWebhookEventType::WireCreated => { + api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess + } + FacilitapayWebhookEventType::PaymentExpired + | FacilitapayWebhookEventType::PaymentFailed => { + api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure + } + FacilitapayWebhookEventType::PaymentRefunded => { + api_models::webhooks::IncomingWebhookEvent::RefundSuccess + } + FacilitapayWebhookEventType::WireWaitingCorrection => { + api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired + } + }; + + Ok(event) } 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: responses::FacilitapayWebhookNotification = request + .body + .parse_struct("FacilitapayWebhookNotification") + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + + Ok(Box::new(webhook_body)) } } @@ -794,7 +943,9 @@ lazy_static! { facilitapay_supported_payment_methods }; - static ref FACILITAPAY_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); + static ref FACILITAPAY_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = vec![ + enums::EventClass::Payments, + ]; } impl ConnectorSpecifications for Facilitapay { diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay/requests.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay/requests.rs index 29c2f34f332..a14da2dd57a 100644 --- a/crates/hyperswitch_connectors/src/connectors/facilitapay/requests.rs +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay/requests.rs @@ -69,12 +69,6 @@ pub struct FacilitapayPaymentsRequest { pub transaction: FacilitapayTransactionRequest, } -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] -pub struct FacilitapayRefundRequest { - pub amount: StringMajorUnit, -} - #[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "snake_case")] pub struct FacilitapayCustomerRequest { diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs index dfa01402ce9..ead8569154f 100644 --- a/crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs @@ -136,6 +136,7 @@ pub struct BankAccountDetail { pub routing_number: Option<Secret<String>>, pub pix_info: Option<PixInfo>, pub owner_name: Option<Secret<String>>, + pub owner_document_type: Option<String>, pub owner_document_number: Option<Secret<String>>, pub owner_company: Option<OwnerCompany>, pub internal: Option<bool>, @@ -176,7 +177,7 @@ pub struct TransactionData { pub subject_is_receiver: Option<bool>, // Source identification (potentially redundant with subject or card/bank info) - pub source_name: Secret<String>, + pub source_name: Option<Secret<String>>, pub source_document_type: DocumentType, pub source_document_number: Secret<String>, @@ -204,14 +205,124 @@ pub struct TransactionData { pub meta: Option<serde_json::Value>, } +// Void response structures (for /refund endpoint) #[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RefundData { +pub struct VoidBankTransaction { #[serde(rename = "id")] - pub refund_id: String, + pub transaction_id: String, + pub value: StringMajorUnit, + pub currency: api_models::enums::Currency, + pub iof_value: Option<StringMajorUnit>, + pub fx_value: Option<StringMajorUnit>, + pub exchange_rate: Option<StringMajorUnit>, + pub exchange_currency: api_models::enums::Currency, + pub exchanged_value: StringMajorUnit, + pub exchange_approved: bool, + pub wire_id: Option<String>, + pub exchange_id: Option<String>, + pub movement_date: String, + pub source_name: Secret<String>, + pub source_document_number: Secret<String>, + pub source_document_type: String, + pub source_id: String, + pub source_type: String, + pub source_description: String, + pub source_bank: Option<String>, + pub source_branch: Option<String>, + pub source_account: Option<String>, + pub source_bank_ispb: Option<String>, + pub company_id: String, + pub company_name: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct VoidData { + #[serde(rename = "id")] + pub void_id: String, + pub reason: Option<String>, + pub inserted_at: String, pub status: FacilitapayPaymentStatus, + pub transaction_kind: String, + pub bank_transaction: VoidBankTransaction, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FacilitapayVoidResponse { + pub data: VoidData, } +// Refund response uses the same TransactionData structure as payments #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FacilitapayRefundResponse { - pub data: RefundData, + pub data: TransactionData, +} + +// Webhook structures +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FacilitapayWebhookNotification { + pub notification: FacilitapayWebhookBody, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct FacilitapayWebhookBody { + #[serde(rename = "type")] + pub event_type: FacilitapayWebhookEventType, + pub secret: Secret<String>, + #[serde(flatten)] + pub data: FacilitapayWebhookData, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum FacilitapayWebhookEventType { + ExchangeCreated, + Identified, + PaymentApproved, + PaymentExpired, + PaymentFailed, + PaymentRefunded, + WireCreated, + WireWaitingCorrection, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "UPPERCASE")] +pub enum FacilitapayWebhookErrorCode { + /// Creditor account number invalid or missing (branch_number or account_number incorrect) + Ac03, + /// Creditor account type missing or invalid (account_type incorrect) + Ac14, + /// Value in Creditor Identifier is incorrect (owner_document_number incorrect) + Ch11, + /// Transaction type not supported/authorized on this account (account rejected the payment) + Ag03, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum FacilitapayWebhookData { + CardPayment { + transaction_id: String, + checkout_id: Option<String>, + }, + Exchange { + exchange_id: String, + transaction_ids: Vec<String>, + }, + Transaction { + transaction_id: String, + }, + Wire { + wire_id: String, + transaction_ids: Vec<String>, + }, + WireError { + error_code: FacilitapayWebhookErrorCode, + error_description: String, + bank_account_owner_id: String, + bank_account_id: String, + transaction_ids: Vec<String>, + wire_id: String, + }, } diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs index c0025fe44ff..d0e186cf35b 100644 --- a/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs @@ -11,8 +11,11 @@ use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{BankTransferData, PaymentMethodData}, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, - router_flow_types::refunds::{Execute, RSync}, - router_request_types::ResponseId, + router_flow_types::{ + payments::Void, + refunds::{Execute, RSync}, + }, + router_request_types::{PaymentsCancelData, ResponseId}, router_response_types::{PaymentsResponseData, RefundsResponseData}, types, }; @@ -27,12 +30,12 @@ use url::Url; use super::{ requests::{ DocumentType, FacilitapayAuthRequest, FacilitapayCredentials, FacilitapayCustomerRequest, - FacilitapayPaymentsRequest, FacilitapayPerson, FacilitapayRefundRequest, - FacilitapayRouterData, FacilitapayTransactionRequest, PixTransactionRequest, + FacilitapayPaymentsRequest, FacilitapayPerson, FacilitapayRouterData, + FacilitapayTransactionRequest, PixTransactionRequest, }, responses::{ FacilitapayAuthResponse, FacilitapayCustomerResponse, FacilitapayPaymentStatus, - FacilitapayPaymentsResponse, FacilitapayRefundResponse, + FacilitapayPaymentsResponse, FacilitapayRefundResponse, FacilitapayVoidResponse, }, }; use crate::{ @@ -509,17 +512,6 @@ fn get_qr_code_data( .change_context(errors::ConnectorError::ResponseHandlingFailed) } -impl<F> TryFrom<&FacilitapayRouterData<&types::RefundsRouterData<F>>> for FacilitapayRefundRequest { - type Error = Error; - fn try_from( - item: &FacilitapayRouterData<&types::RefundsRouterData<F>>, - ) -> Result<Self, Self::Error> { - Ok(Self { - amount: item.amount.clone(), - }) - } -} - impl From<FacilitapayPaymentStatus> for enums::RefundStatus { fn from(item: FacilitapayPaymentStatus) -> Self { match item { @@ -532,6 +524,56 @@ impl From<FacilitapayPaymentStatus> for enums::RefundStatus { } } +// Void (cancel unprocessed payment) transformer +impl + TryFrom< + ResponseRouterData<Void, FacilitapayVoidResponse, PaymentsCancelData, PaymentsResponseData>, + > for RouterData<Void, PaymentsCancelData, PaymentsResponseData> +{ + type Error = Error; + fn try_from( + item: ResponseRouterData< + Void, + FacilitapayVoidResponse, + PaymentsCancelData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let status = common_enums::AttemptStatus::from(item.response.data.status.clone()); + + Ok(Self { + status, + response: if is_payment_failure(status) { + Err(ErrorResponse { + code: item.response.data.status.clone().to_string(), + message: item.response.data.status.clone().to_string(), + reason: item.response.data.reason, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(item.response.data.void_id.clone()), + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + }) + } else { + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.response.data.void_id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(item.response.data.void_id), + incremental_authorization_allowed: None, + charges: None, + }) + }, + ..item.data + }) + } +} + impl TryFrom<RefundsResponseRouterData<Execute, FacilitapayRefundResponse>> for types::RefundsRouterData<Execute> { @@ -541,7 +583,7 @@ impl TryFrom<RefundsResponseRouterData<Execute, FacilitapayRefundResponse>> ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { - connector_refund_id: item.response.data.refund_id.to_string(), + connector_refund_id: item.response.data.transaction_id.clone(), refund_status: enums::RefundStatus::from(item.response.data.status), }), ..item.data @@ -558,7 +600,7 @@ impl TryFrom<RefundsResponseRouterData<RSync, FacilitapayRefundResponse>> ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { - connector_refund_id: item.response.data.refund_id.to_string(), + connector_refund_id: item.response.data.transaction_id.clone(), refund_status: enums::RefundStatus::from(item.response.data.status), }), ..item.data
2025-07-28T19:30:24Z
## 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 Facilitapay PR introudces 2 new features and a bug fix which is described below: - Add support for webhooks - Source verification supported - Payments - Refunds (It is only supported for pix payment when a third party makes a transaction instead of the actual user). The payload for both payments and refunds is exactly the same with 0 difference. It is kind of use less to have webhook for support for Refunds - Add support for voiding payments - At Facilita, `refund` means voiding a payment - This is a `GET` call with no request body - Fix a bug in Refunds (It was not testable until now) - At Facilita, `refund_received_transaction` means refunding a payment - This is a `GET` call with no request body - Does not support partial refunds ### 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 https://github.com/juspay/hyperswitch/issues/8777 ## 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)? --> <details> <summary>Partial refunds</summary> ```sh curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_FwRHVH9xL5cvYOsONW8YzIphnGhIibnEy9tCWuNCpDLwSnzR4Ilogl6sia26pcND' \ --data '{ "payment_id": "pay_le5uOFoizxZPXFHPQuK1", "amount": 1000, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "error": { "type": "invalid_request", "message": "Payment method type not supported", "code": "IR_19", "reason": "Partial refund not supported by Facilitapay is not supported by Facilitapay" } } ``` </details> <details> <summary>Refunds</summary> ```sh curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_FwRHVH9xL5cvYOsONW8YzIphnGhIibnEy9tCWuNCpDLwSnzR4Ilogl6sia26pcND' \ --data '{ "payment_id": "pay_le5uOFoizxZPXFHPQuK1", "amount": 10400, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "refund_id": "ref_bEMav88LA7llD0KS6Twk", "payment_id": "pay_le5uOFoizxZPXFHPQuK1", "amount": 10400, "currency": "BRL", "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-07-28T18:43:11.748Z", "updated_at": "2025-07-28T18:43:12.819Z", "connector": "facilitapay", "profile_id": "pro_ODZKRkH2uJIfAPClUy8B", "merchant_connector_id": "mca_A4Kpc6NUvBsN8RGvvJsm", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ``` will introduce cypress in a separate pr </details> <details> <summary>Void</summary> ```sh curl --location 'https://pix-mbp.orthrus-monster.ts.net/payments/pay_XIq2h8snAnSp425StpHM/cancel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_FwRHVH9xL5cvYOsONW8YzIphnGhIibnEy9tCWuNCpDLwSnzR4Ilogl6sia26pcND' \ --data '{"cancellation_reason":"requested_by_customer"}' ``` ```json { "payment_id": "pay_XIq2h8snAnSp425StpHM", "merchant_id": "postman_merchant_GHAction_1753728068", "status": "cancelled", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_XIq2h8snAnSp425StpHM_secret_Za7LqUCCvag8LBMCyYBp", "created": "2025-07-28T18:44:39.081Z", "currency": "BRL", "customer_id": null, "customer": { "id": null, "name": null, "email": "guesjhvghht@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "THE" }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": "requested_by_customer", "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": 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_ODZKRkH2uJIfAPClUy8B", "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-07-28T18:59:39.081Z", "fingerprint": null, "browser_info": { "language": "en-GB", "time_zone": -330, "ip_address": "208.127.127.193", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0", "color_depth": 24, "java_enabled": true, "screen_width": 1280, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 720, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-07-28T18:44:43.912Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` </details> <details> <summary>Webhook Setup</summary> ```sh curl --location 'https://sandbox-api.facilitapay.com/api/v1/enable_webhooks' \ --header 'Authorization: Bearer <jwt_token>' \ --header 'Content-Type: application/json' \ --data '{ "url": "https://baseUrl/webhooks/:merchant_id/facilitapay" }' ``` ```json { "data": { "secret": "1111" } } ``` </details> <details> <summary>Payment Webhook</summary> Source verification: <img width="930" height="192" alt="image" src="https://github.com/user-attachments/assets/cfcb1f63-4102-4b84-95d7-c16522725e67" /> Incoming Webhook Logs: <img width="1682" height="607" alt="image" src="https://github.com/user-attachments/assets/1411a32c-195a-4e4c-b0ba-2fc062087d43" /> Outgoing Webhook: <img width="1435" height="558" alt="image" src="https://github.com/user-attachments/assets/b98c4292-1855-4315-8962-62b7bfb4ba85" /> </details> <details> <summary>Refund Webhook</summary> The `payment_refunded` webhook is only sent for a very specific use case - when a pix payment is automatically refunded because it was paid from a third-party account. for regular api-initiated refunds, facilitapay sends the same identified and wire_created webhooks as for payments, making it impossible to distinguish between payment and refund webhooks. </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 `just clippy && just clippy_v2` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.115.0
f6cdddcb98e08f97dc518c8c14569fe67426bd6f
f6cdddcb98e08f97dc518c8c14569fe67426bd6f
juspay/hyperswitch
juspay__hyperswitch-8789
Bug: [FEATURE] populate status_code in response Populate UCS status_code (connector HTTP status code) in response headers
diff --git a/Cargo.lock b/Cargo.lock index 3e1101fdbf4..60f064c45e4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3525,7 +3525,7 @@ dependencies = [ [[package]] name = "grpc-api-types" version = "0.1.0" -source = "git+https://github.com/juspay/connector-service?rev=0409f6aa1014dd1b9827fabfa4fa424e16d07ebc#0409f6aa1014dd1b9827fabfa4fa424e16d07ebc" +source = "git+https://github.com/juspay/connector-service?rev=4387a6310dc9c2693b453b455a8032623f3d6a81#4387a6310dc9c2693b453b455a8032623f3d6a81" dependencies = [ "axum 0.8.4", "error-stack 0.5.0", @@ -6899,7 +6899,7 @@ dependencies = [ [[package]] name = "rust-grpc-client" version = "0.1.0" -source = "git+https://github.com/juspay/connector-service?rev=0409f6aa1014dd1b9827fabfa4fa424e16d07ebc#0409f6aa1014dd1b9827fabfa4fa424e16d07ebc" +source = "git+https://github.com/juspay/connector-service?rev=4387a6310dc9c2693b453b455a8032623f3d6a81#4387a6310dc9c2693b453b455a8032623f3d6a81" dependencies = [ "grpc-api-types", ] diff --git a/config/config.example.toml b/config/config.example.toml index 55ab8675605..9cb4065b5f9 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -1171,3 +1171,6 @@ allow_connected_merchants = false # Enable or disable connected merchant account [chat] enabled = false # Enable or disable chat features hyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow host + +[proxy_status_mapping] +proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response \ No newline at end of file diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 23ff9f16e70..6ce8611ef02 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -386,3 +386,6 @@ connection_timeout = 10 # Connection Timeout Duration in Seconds [chat] enabled = false # Enable or disable chat features hyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow host + +[proxy_status_mapping] +proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response \ No newline at end of file diff --git a/config/development.toml b/config/development.toml index b3aa9fcb9a5..403a55552b2 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1269,3 +1269,6 @@ version = "HOSTNAME" [chat] enabled = false hyperswitch_ai_host = "http://0.0.0.0:8000" + +[proxy_status_mapping] +proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response \ No newline at end of file diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 09ef545f584..b6ef24fcd2c 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -1160,3 +1160,6 @@ connector_names = "stripe, adyen" # Comma-separated list of allowe [infra_values] cluster = "CLUSTER" # value of CLUSTER from deployment version = "HOSTNAME" # value of HOSTNAME from deployment which tells its version + +[proxy_status_mapping] +proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response \ No newline at end of file diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index bfa0a8b6132..9e83f331b94 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -53,7 +53,7 @@ reqwest = { version = "0.11.27", features = ["rustls-tls"] } http = "0.2.12" url = { version = "2.5.4", features = ["serde"] } quick-xml = { version = "0.31.0", features = ["serialize"] } -unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "0409f6aa1014dd1b9827fabfa4fa424e16d07ebc", package = "rust-grpc-client" } +unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "4387a6310dc9c2693b453b455a8032623f3d6a81", package = "rust-grpc-client" } # First party crates diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 3f3e574fcdd..4d1e9917ad1 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -88,7 +88,7 @@ reqwest = { version = "0.11.27", features = ["json", "rustls-tls", "gzip", "mult ring = "0.17.14" rust_decimal = { version = "1.37.1", features = ["serde-with-float", "serde-with-str"] } rust-i18n = { git = "https://github.com/kashif-m/rust-i18n", rev = "f2d8096aaaff7a87a847c35a5394c269f75e077a" } -unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "0409f6aa1014dd1b9827fabfa4fa424e16d07ebc", package = "rust-grpc-client" } +unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "4387a6310dc9c2693b453b455a8032623f3d6a81", package = "rust-grpc-client" } rustc-hash = "1.1.0" rustls = "0.22" rustls-pemfile = "2" diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index f517cb69739..d00ece8360a 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -87,7 +87,7 @@ where let response = S::try_from(response); match response { Ok(response) => match serde_json::to_string(&response) { - Ok(res) => api::http_response_json_with_headers(res, headers, None), + Ok(res) => api::http_response_json_with_headers(res, headers, None, None), Err(_) => api::http_response_err( r#"{ "error": { diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 4f53a2ef2df..6cb720650a2 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -548,5 +548,6 @@ pub(crate) async fn fetch_raw_secrets( merchant_id_auth: conf.merchant_id_auth, infra_values: conf.infra_values, enhancement: conf.enhancement, + proxy_status_mapping: conf.proxy_status_mapping, } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 1604b7eaa9d..29c3d3598c6 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -164,6 +164,7 @@ pub struct Settings<S: SecretState> { pub infra_values: Option<HashMap<String, String>>, #[serde(default)] pub enhancement: Option<HashMap<String, String>>, + pub proxy_status_mapping: ProxyStatusMapping, } #[derive(Debug, Deserialize, Clone, Default)] @@ -844,6 +845,12 @@ pub struct MerchantIdAuthSettings { pub merchant_id_auth_enabled: bool, } +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct ProxyStatusMapping { + pub proxy_connector_http_status_code: bool, +} + #[derive(Debug, Clone, Default, Deserialize)] #[serde(default)] pub struct WebhooksSettings { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index a912dc27b82..106db14fdef 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -214,6 +214,7 @@ where .perform_routing(&merchant_context, profile, state, &mut payment_data) .await?; + let mut connector_http_status_code = None; let (payment_data, connector_response_data) = match connector { ConnectorCallType::PreDetermined(connector_data) => { let (mca_type_details, updated_customer, router_data) = @@ -265,6 +266,9 @@ where let payments_response_operation = Box::new(PaymentResponse); + connector_http_status_code = router_data.connector_http_status_code; + add_connector_http_status_code_metrics(connector_http_status_code); + payments_response_operation .to_post_update_tracker()? .save_pm_and_mandate( @@ -342,6 +346,9 @@ where let payments_response_operation = Box::new(PaymentResponse); + connector_http_status_code = router_data.connector_http_status_code; + add_connector_http_status_code_metrics(connector_http_status_code); + payments_response_operation .to_post_update_tracker()? .save_pm_and_mandate( @@ -395,7 +402,7 @@ where payment_data, req, customer, - None, + connector_http_status_code, None, connector_response_data, )) @@ -492,6 +499,9 @@ where let payments_response_operation = Box::new(PaymentResponse); + let connector_http_status_code = router_data.connector_http_status_code; + add_connector_http_status_code_metrics(connector_http_status_code); + let payment_data = payments_response_operation .to_post_update_tracker()? .update_tracker( @@ -503,7 +513,13 @@ where ) .await?; - Ok((payment_data, req, None, None, connector_response_data)) + Ok(( + payment_data, + req, + connector_http_status_code, + None, + connector_response_data, + )) } #[cfg(feature = "v1")] diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index e077362cc1f..2aa69e6a36b 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -860,7 +860,7 @@ async fn call_unified_connector_service_authorize( let payment_authorize_response = response.into_inner(); - let (status, router_data_response) = + let (status, router_data_response, status_code) = handle_unified_connector_service_response_for_payment_authorize( payment_authorize_response.clone(), ) @@ -872,6 +872,7 @@ async fn call_unified_connector_service_authorize( router_data.raw_connector_response = payment_authorize_response .raw_connector_response .map(Secret::new); + router_data.connector_http_status_code = Some(status_code); Ok(()) } @@ -916,7 +917,7 @@ async fn call_unified_connector_service_repeat_payment( let payment_repeat_response = response.into_inner(); - let (status, router_data_response) = + let (status, router_data_response, status_code) = handle_unified_connector_service_response_for_payment_repeat( payment_repeat_response.clone(), ) @@ -928,6 +929,7 @@ async fn call_unified_connector_service_repeat_payment( router_data.raw_connector_response = payment_repeat_response .raw_connector_response .map(Secret::new); + router_data.connector_http_status_code = Some(status_code); Ok(()) } diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index 84752f16520..641af1d397e 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -250,7 +250,7 @@ impl Feature<api::PSync, types::PaymentsSyncData> let payment_get_response = response.into_inner(); - let (status, router_data_response) = + let (status, router_data_response, status_code) = handle_unified_connector_service_response_for_payment_get(payment_get_response.clone()) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize UCS response")?; @@ -258,6 +258,7 @@ impl Feature<api::PSync, types::PaymentsSyncData> self.status = status; self.response = router_data_response; self.raw_connector_response = payment_get_response.raw_connector_response.map(Secret::new); + self.connector_http_status_code = Some(status_code); Ok(()) } diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 6204d521680..c89f04aa69a 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -246,7 +246,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup let payment_register_response = response.into_inner(); - let (status, router_data_response) = + let (status, router_data_response, status_code) = handle_unified_connector_service_response_for_payment_register( payment_register_response.clone(), ) @@ -255,6 +255,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup self.status = status; self.response = router_data_response; + self.connector_http_status_code = Some(status_code); // UCS does not return raw connector response for setup mandate right now // self.raw_connector_response = payment_register_response // .raw_connector_response diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index dd9b41ee9d2..55bf4fe4298 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -36,7 +36,7 @@ use crate::{ payments::{self, helpers}, utils as core_utils, }, - headers::X_PAYMENT_CONFIRM_SOURCE, + headers::{X_CONNECTOR_HTTP_STATUS_CODE, X_PAYMENT_CONFIRM_SOURCE}, routes::{metrics, SessionState}, services::{self, RedirectForm}, types::{ @@ -1586,9 +1586,17 @@ where status: payment_intent.status, }; + let headers = connector_http_status_code + .map(|status_code| { + vec![( + X_CONNECTOR_HTTP_STATUS_CODE.to_string(), + Maskable::new_normal(status_code.to_string()), + )] + }) + .unwrap_or_default(); + Ok(services::ApplicationResponse::JsonWithHeaders(( - response, - vec![], + response, headers, ))) } } @@ -1969,6 +1977,15 @@ where .clone() .or(profile.return_url.clone()); + let headers = connector_http_status_code + .map(|status_code| { + vec![( + X_CONNECTOR_HTTP_STATUS_CODE.to_string(), + Maskable::new_normal(status_code.to_string()), + )] + }) + .unwrap_or_default(); + let response = api_models::payments::PaymentsResponse { id: payment_intent.id.clone(), status: payment_intent.status, @@ -2000,8 +2017,7 @@ where }; Ok(services::ApplicationResponse::JsonWithHeaders(( - response, - vec![], + response, headers, ))) } } @@ -2066,6 +2082,15 @@ where let return_url = payment_intent.return_url.or(profile.return_url.clone()); + let headers = connector_http_status_code + .map(|status_code| { + vec![( + X_CONNECTOR_HTTP_STATUS_CODE.to_string(), + Maskable::new_normal(status_code.to_string()), + )] + }) + .unwrap_or_default(); + let response = api_models::payments::PaymentsResponse { id: payment_intent.id.clone(), status: payment_intent.status, @@ -2101,8 +2126,7 @@ where }; Ok(services::ApplicationResponse::JsonWithHeaders(( - response, - vec![], + response, headers, ))) } } @@ -2540,7 +2564,7 @@ where let mut headers = connector_http_status_code .map(|status_code| { vec![( - "connector_http_status_code".to_string(), + X_CONNECTOR_HTTP_STATUS_CODE.to_string(), Maskable::new_normal(status_code.to_string()), )] }) diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs index 79dd1cc7013..107b6e7e7a2 100644 --- a/crates/router/src/core/unified_connector_service.rs +++ b/crates/router/src/core/unified_connector_service.rs @@ -241,161 +241,79 @@ pub fn build_unified_connector_service_auth_metadata( pub fn handle_unified_connector_service_response_for_payment_authorize( response: PaymentServiceAuthorizeResponse, ) -> CustomResult< - (AttemptStatus, Result<PaymentsResponseData, ErrorResponse>), + ( + AttemptStatus, + Result<PaymentsResponseData, ErrorResponse>, + u16, + ), UnifiedConnectorServiceError, > { let status = AttemptStatus::foreign_try_from(response.status())?; - // <<<<<<< HEAD - // let connector_response_reference_id = - // response.response_ref_id.as_ref().and_then(|identifier| { - // identifier - // .id_type - // .clone() - // .and_then(|id_type| match id_type { - // payments_grpc::identifier::IdType::Id(id) => Some(id), - // payments_grpc::identifier::IdType::EncodedData(encoded_data) => { - // Some(encoded_data) - // } - // payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, - // }) - // }); - - // let transaction_id = response.transaction_id.as_ref().and_then(|id| { - // id.id_type.clone().and_then(|id_type| match id_type { - // payments_grpc::identifier::IdType::Id(id) => Some(id), - // payments_grpc::identifier::IdType::EncodedData(encoded_data) => Some(encoded_data), - // payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, - // }) - // }); - - // let (connector_metadata, redirection_data) = match response.redirection_data.clone() { - // Some(redirection_data) => match redirection_data.form_type { - // Some(ref form_type) => match form_type { - // payments_grpc::redirect_form::FormType::Uri(uri) => { - // let image_data = QrImage::new_from_data(uri.uri.clone()) - // .change_context(UnifiedConnectorServiceError::ParsingFailed)?; - // let image_data_url = Url::parse(image_data.data.clone().as_str()) - // .change_context(UnifiedConnectorServiceError::ParsingFailed)?; - // let qr_code_info = QrCodeInformation::QrDataUrl { - // image_data_url, - // display_to_timestamp: None, - // }; - // ( - // Some(qr_code_info.encode_to_value()) - // .transpose() - // .change_context(UnifiedConnectorServiceError::ParsingFailed)?, - // None, - // ) - // } - // _ => ( - // None, - // Some(RedirectForm::foreign_try_from(redirection_data)).transpose()?, - // ), - // }, - // None => (None, None), - // }, - // None => (None, None), - // }; - - // let router_data_response = match status { - // AttemptStatus::Charged | - // AttemptStatus::Authorized | - // AttemptStatus::AuthenticationPending | - // AttemptStatus::DeviceDataCollectionPending | - // AttemptStatus::Started | - // AttemptStatus::AuthenticationSuccessful | - // AttemptStatus::Authorizing | - // AttemptStatus::ConfirmationAwaited | - // AttemptStatus::Pending => Ok(PaymentsResponseData::TransactionResponse { - // resource_id: match transaction_id.as_ref() { - // Some(transaction_id) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(transaction_id.clone()), - // None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId, - // }, - // redirection_data: Box::new( - // redirection_data - // ), - // mandate_reference: Box::new(None), - // connector_metadata, - // network_txn_id: response.network_txn_id.clone(), - // connector_response_reference_id, - // incremental_authorization_allowed: response.incremental_authorization_allowed, - // charges: None, - // }), - // AttemptStatus::AuthenticationFailed - // | AttemptStatus::AuthorizationFailed - // | AttemptStatus::Unresolved - // | AttemptStatus::Failure => Err(ErrorResponse { - // code: response.error_code().to_owned(), - // message: response.error_message().to_owned(), - // reason: Some(response.error_message().to_owned()), - // status_code: 500, - // attempt_status: Some(status), - // connector_transaction_id: connector_response_reference_id, - // network_decline_code: None, - // network_advice_code: None, - // network_error_message: None, - // }), - // AttemptStatus::RouterDeclined | - // AttemptStatus::CodInitiated | - // AttemptStatus::Voided | - // AttemptStatus::VoidInitiated | - // AttemptStatus::CaptureInitiated | - // AttemptStatus::VoidFailed | - // AttemptStatus::AutoRefunded | - // AttemptStatus::PartialCharged | - // AttemptStatus::PartialChargedAndChargeable | - // AttemptStatus::PaymentMethodAwaited | - // AttemptStatus::CaptureFailed | - // AttemptStatus::IntegrityFailure => return Err(UnifiedConnectorServiceError::NotImplemented(format!( - // "AttemptStatus {status:?} is not implemented for Unified Connector Service" - // )).into()), - // }; - // ======= + let status_code = transformers::convert_connector_service_status_code(response.status_code)?; + let router_data_response = Result::<PaymentsResponseData, ErrorResponse>::foreign_try_from(response)?; - Ok((status, router_data_response)) + Ok((status, router_data_response, status_code)) } pub fn handle_unified_connector_service_response_for_payment_get( response: payments_grpc::PaymentServiceGetResponse, ) -> CustomResult< - (AttemptStatus, Result<PaymentsResponseData, ErrorResponse>), + ( + AttemptStatus, + Result<PaymentsResponseData, ErrorResponse>, + u16, + ), UnifiedConnectorServiceError, > { let status = AttemptStatus::foreign_try_from(response.status())?; + let status_code = transformers::convert_connector_service_status_code(response.status_code)?; + let router_data_response = Result::<PaymentsResponseData, ErrorResponse>::foreign_try_from(response)?; - Ok((status, router_data_response)) + Ok((status, router_data_response, status_code)) } pub fn handle_unified_connector_service_response_for_payment_register( response: payments_grpc::PaymentServiceRegisterResponse, ) -> CustomResult< - (AttemptStatus, Result<PaymentsResponseData, ErrorResponse>), + ( + AttemptStatus, + Result<PaymentsResponseData, ErrorResponse>, + u16, + ), UnifiedConnectorServiceError, > { let status = AttemptStatus::foreign_try_from(response.status())?; + let status_code = transformers::convert_connector_service_status_code(response.status_code)?; + let router_data_response = Result::<PaymentsResponseData, ErrorResponse>::foreign_try_from(response)?; - Ok((status, router_data_response)) + Ok((status, router_data_response, status_code)) } pub fn handle_unified_connector_service_response_for_payment_repeat( response: payments_grpc::PaymentServiceRepeatEverythingResponse, ) -> CustomResult< - (AttemptStatus, Result<PaymentsResponseData, ErrorResponse>), + ( + AttemptStatus, + Result<PaymentsResponseData, ErrorResponse>, + u16, + ), UnifiedConnectorServiceError, > { let status = AttemptStatus::foreign_try_from(response.status())?; + let status_code = transformers::convert_connector_service_status_code(response.status_code)?; + let router_data_response = Result::<PaymentsResponseData, ErrorResponse>::foreign_try_from(response)?; - Ok((status, router_data_response)) + Ok((status, router_data_response, status_code)) } diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs index 267896ce8ea..9f8ad6c128e 100644 --- a/crates/router/src/core/unified_connector_service/transformers.rs +++ b/crates/router/src/core/unified_connector_service/transformers.rs @@ -397,12 +397,14 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse> None => (None, None), }; + let status_code = convert_connector_service_status_code(response.status_code)?; + let response = if response.error_code.is_some() { Err(ErrorResponse { code: response.error_code().to_owned(), message: response.error_message().to_owned(), reason: Some(response.error_message().to_owned()), - status_code: 500, //TODO: To be handled once UCS sends proper status codes + status_code, attempt_status: Some(status), connector_transaction_id: connector_response_reference_id, network_decline_code: None, @@ -455,12 +457,14 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceGetResponse> }) }); + let status_code = convert_connector_service_status_code(response.status_code)?; + let response = if response.error_code.is_some() { Err(ErrorResponse { code: response.error_code().to_owned(), message: response.error_message().to_owned(), reason: Some(response.error_message().to_owned()), - status_code: 500, //TODO: To be handled once UCS sends proper status codes + status_code, attempt_status: Some(status), connector_transaction_id: connector_response_reference_id, network_decline_code: None, @@ -514,12 +518,14 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceRegisterResponse> }) }); + let status_code = convert_connector_service_status_code(response.status_code)?; + let response = if response.error_code.is_some() { Err(ErrorResponse { code: response.error_code().to_owned(), message: response.error_message().to_owned(), reason: Some(response.error_message().to_owned()), - status_code: 500, //TODO: To be handled once UCS sends proper status codes + status_code, attempt_status: Some(status), connector_transaction_id: connector_response_reference_id, network_decline_code: None, @@ -603,12 +609,14 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceRepeatEverythingResponse> }) }); + let status_code = convert_connector_service_status_code(response.status_code)?; + let response = if response.error_code.is_some() { Err(ErrorResponse { code: response.error_code().to_owned(), message: response.error_message().to_owned(), reason: Some(response.error_message().to_owned()), - status_code: 500, //TODO: To be handled once UCS sends proper status codes + status_code, attempt_status: Some(status), connector_transaction_id: transaction_id, network_decline_code: None, @@ -994,3 +1002,14 @@ impl ForeignTryFrom<common_types::payments::CustomerAcceptance> }) } } + +pub fn convert_connector_service_status_code( + status_code: u32, +) -> Result<u16, error_stack::Report<UnifiedConnectorServiceError>> { + u16::try_from(status_code).map_err(|err| { + UnifiedConnectorServiceError::RequestEncodingFailedWithReason(format!( + "Failed to convert connector service status code to u16: {err}" + )) + .into() + }) +} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 01676a11d49..828986aeeee 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -92,6 +92,12 @@ pub mod headers { pub const X_CLIENT_SECRET: &str = "X-Client-Secret"; pub const X_CUSTOMER_ID: &str = "X-Customer-Id"; pub const X_CONNECTED_MERCHANT_ID: &str = "x-connected-merchant-id"; + // Header value for X_CONNECTOR_HTTP_STATUS_CODE differs by version. + // Constant name is kept the same for consistency across versions. + #[cfg(feature = "v1")] + pub const X_CONNECTOR_HTTP_STATUS_CODE: &str = "connector_http_status_code"; + #[cfg(feature = "v2")] + pub const X_CONNECTOR_HTTP_STATUS_CODE: &str = "x-connector-http-status-code"; } pub mod pii { diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 780093fd012..e738747f6a4 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -898,8 +898,45 @@ where None } }); + let proxy_connector_http_status_code = if state + .conf + .proxy_status_mapping + .proxy_connector_http_status_code + { + headers + .iter() + .find(|(key, _)| key == headers::X_CONNECTOR_HTTP_STATUS_CODE) + .and_then(|(_, value)| { + match value.clone().into_inner().parse::<u16>() { + Ok(code) => match http::StatusCode::from_u16(code) { + Ok(status_code) => Some(status_code), + Err(err) => { + logger::error!( + "Invalid HTTP status code parsed from connector_http_status_code: {:?}", + err + ); + None + } + }, + Err(err) => { + logger::error!( + "Failed to parse connector_http_status_code from header: {:?}", + err + ); + None + } + } + }) + } else { + None + }; match serde_json::to_string(&response) { - Ok(res) => http_response_json_with_headers(res, headers, request_elapsed_time), + Ok(res) => http_response_json_with_headers( + res, + headers, + request_elapsed_time, + proxy_connector_http_status_code, + ), Err(_) => http_response_err( r#"{ "error": { @@ -991,8 +1028,9 @@ pub fn http_response_json_with_headers<T: body::MessageBody + 'static>( response: T, headers: Vec<(String, Maskable<String>)>, request_duration: Option<Duration>, + status_code: Option<http::StatusCode>, ) -> HttpResponse { - let mut response_builder = HttpResponse::Ok(); + let mut response_builder = HttpResponse::build(status_code.unwrap_or(http::StatusCode::OK)); for (header_name, header_value) in headers { let is_sensitive_header = header_value.is_masked(); let mut header_value = header_value.into_inner();
2025-07-29T09:24:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR populates UCS status_code (connector HTTP code) in response headers. It also introduces proxy_connector_http_status_code which when enabled, configures Hyperswitch to mirror (proxy) the connector’s HTTP status code in its own response. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Enable UCS Config ``` curl --location 'http://localhost:8080/configs/' \ --header 'api-key: test_admin' \ --header 'x-tenant-id: public' \ --header 'Content-Type: application/json' \ --data '{ "key": "ucs_rollout_config_{{merchant_id}}_razorpay_upi_Authorize", "value": "1.0" }' ``` Make a payment ``` curl --location 'http://localhost:8080/v2/payments' \ --header 'api-key: dev_mwKUL6tWhsO8FbwWtKjNllSa7GnZutXqKsv9oLxJRv4c7l8UX9muRdsC4r9Wh2A5' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_cQ4q1A6oYpi89Zi7zyxW' \ --header 'Authorization: api-key=dev_mwKUL6tWhsO8FbwWtKjNllSa7GnZutXqKsv9oLxJRv4c7l8UX9muRdsC4r9Wh2A5' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "INR" }, "capture_method":"automatic", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method_data": { "upi": { "upi_collect": { "vpa_id": "success" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "Swangi", "last_name": "Kumari" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" } }, "payment_method_subtype": "upi_collect", "payment_method_type": "upi", "return_raw_connector_response": true }' ``` Response ``` { "id": "12345_pay_019860443e3d7f939e80e9a98effba3d", "status": "requires_merchant_action", "amount": { "order_amount": 100, "currency": "INR", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "customer_id": null, "connector": "razorpay", "created": "2025-07-31T11:35:41.885Z", "payment_method_data": { "billing": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "Swangi", "last_name": "Kumari" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" } }, "payment_method_type": "upi", "payment_method_subtype": "upi_collect", "connector_transaction_id": "order_QzezHblnRQM45h", "connector_reference_id": null, "merchant_connector_id": "mca_BIFmH1dr6Vh5UoYu2srb", "browser_info": null, "error": { "code": "BAD_REQUEST_ERROR", "message": "Invalid VPA. Please enter a valid Virtual Payment Address", "unified_code": null, "unified_message": null, "network_advice_code": null, "network_decline_code": null, "network_error_message": null }, "shipping": null, "billing": null, "attempts": null, "connector_token_details": null, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds", "is_iframe_redirection_enabled": null, "merchant_reference_id": null, "raw_connector_response": "{\"error\":{\"code\":\"BAD_REQUEST_ERROR\",\"description\":\"Invalid VPA. Please enter a valid Virtual Payment Address\",\"source\":\"customer\",\"step\":\"payment_initiation\",\"reason\":\"invalid_vpa\",\"metadata\":{},\"field\":\"vpa\"}}", "feature_metadata": null } ``` Verify response headers for connector_http_status_code <img width="806" height="373" alt="image" src="https://github.com/user-attachments/assets/d948782f-d7d2-45f8-bff5-ef62c7a93111" /> If proxy_connector_http_status_code is enabled Hyperswitch resoponse status code will also be 400 <img width="825" height="277" alt="image" src="https://github.com/user-attachments/assets/518446a8-5989-4862-b441-81c20c8dab1a" /> ## 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.115.0
90f3b09a77484a4262608b0a4eeca7d452a4c968
90f3b09a77484a4262608b0a4eeca7d452a4c968
juspay/hyperswitch
juspay__hyperswitch-8784
Bug: [FEATURE] Add Google Pay Payment Method In Barclaycard ### Feature Description Add Google Pay Payment Method In Barclaycard ### Possible Implementation Add Google Pay Payment Method In Barclaycard ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index e2cdf7fd3f2..5b414d7eea1 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -690,6 +690,11 @@ google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN samsung_pay = { currency = "USD,GBP,EUR,SEK" } paze = { currency = "USD,SEK" } +[pm_filters.barclaycard] +credit = { currency = "USD,GBP,EUR,PLN,SEK" } +debit = { currency = "USD,GBP,EUR,PLN,SEK" } +google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } + [pm_filters.globepay] ali_pay = { country = "GB",currency = "GBP" } we_chat_pay = { country = "GB",currency = "GBP" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 9e64b7928e4..6660a1cbbea 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -496,6 +496,11 @@ google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN samsung_pay = { currency = "USD,GBP,EUR,SEK" } paze = { currency = "USD,SEK" } +[pm_filters.barclaycard] +credit = { currency = "USD,GBP,EUR,PLN,SEK" } +debit = { currency = "USD,GBP,EUR,PLN,SEK" } +google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } + [pm_filters.itaubank] pix = { country = "BR", currency = "BRL" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index fe7041d5539..78f6e2c0671 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -430,6 +430,11 @@ google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN samsung_pay = { currency = "USD,GBP,EUR,SEK" } paze = { currency = "USD,SEK" } +[pm_filters.barclaycard] +credit = { currency = "USD,GBP,EUR,PLN,SEK" } +debit = { currency = "USD,GBP,EUR,PLN,SEK" } +google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } + [pm_filters.itaubank] pix = { country = "BR", currency = "BRL" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index e9f5b09c752..f5155be4e2f 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -439,6 +439,11 @@ google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN samsung_pay = { currency = "USD,GBP,EUR,SEK" } paze = { currency = "USD,SEK" } +[pm_filters.barclaycard] +credit = { currency = "USD,GBP,EUR,PLN,SEK" } +debit = { currency = "USD,GBP,EUR,PLN,SEK" } +google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } + [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,AU,BR,US", 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,AU,BR,US", 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" } diff --git a/config/development.toml b/config/development.toml index c06d9798cd3..257e857c2f7 100644 --- a/config/development.toml +++ b/config/development.toml @@ -598,6 +598,11 @@ google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN samsung_pay = { currency = "USD,GBP,EUR,SEK" } paze = { currency = "USD,SEK" } +[pm_filters.barclaycard] +credit = { currency = "USD,GBP,EUR,PLN,SEK" } +debit = { currency = "USD,GBP,EUR,PLN,SEK" } +google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } + [pm_filters.globepay] ali_pay = { country = "GB",currency = "GBP,CNY" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 8893834e23e..d8b310d241e 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -633,6 +633,11 @@ google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN samsung_pay = { currency = "USD,GBP,EUR,SEK" } paze = { currency = "USD,SEK" } +[pm_filters.barclaycard] +credit = { currency = "USD,GBP,EUR,PLN,SEK" } +debit = { currency = "USD,GBP,EUR,PLN,SEK" } +google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } + [pm_filters.globepay] ali_pay = { country = "GB",currency = "GBP,CNY" } we_chat_pay = { country = "GB",currency = "GBP,CNY" } diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 2b5130aaea5..db8a914a031 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -1026,11 +1026,83 @@ options=["visa","masterCard","amex","discover"] payment_method_type = "CartesBancaires" [[barclaycard.debit]] payment_method_type = "UnionPay" +[[barclaycard.wallet]] + payment_method_type = "google_pay" [barclaycard.connector_auth.SignatureKey] api_key="Key" key1="Merchant ID" api_secret="Shared Secret" +[[barclaycard.metadata.google_pay]] +name = "merchant_name" +label = "Google Pay Merchant Name" +placeholder = "Enter Google Pay Merchant Name" +required = true +type = "Text" +[[barclaycard.metadata.google_pay]] +name = "merchant_id" +label = "Google Pay Merchant Id" +placeholder = "Enter Google Pay Merchant Id" +required = true +type = "Text" +[[barclaycard.metadata.google_pay]] +name = "gateway_merchant_id" +label = "Google Pay Merchant Key" +placeholder = "Enter Google Pay Merchant Key" +required = true +type = "Text" +[[barclaycard.metadata.google_pay]] +name = "allowed_auth_methods" +label = "Allowed Auth Methods" +placeholder = "Enter Allowed Auth Methods" +required = true +type = "MultiSelect" +options = ["PAN_ONLY", "CRYPTOGRAM_3DS"] + +[[barclaycard.connector_wallets_details.google_pay]] +name = "merchant_name" +label = "Google Pay Merchant Name" +placeholder = "Enter Google Pay Merchant Name" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "merchant_id" +label = "Google Pay Merchant Id" +placeholder = "Enter Google Pay Merchant Id" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "gateway_merchant_id" +label = "Google Pay Merchant Key" +placeholder = "Enter Google Pay Merchant Key" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "public_key" +label = "Google Pay Public Key" +placeholder = "Enter Google Pay Public Key" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "private_key" +label = "Google Pay Private Key" +placeholder = "Enter Google Pay Private Key" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "recipient_id" +label = "Recipient Id" +placeholder = "Enter Recipient Id" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "allowed_auth_methods" +label = "Allowed Auth Methods" +placeholder = "Enter Allowed Auth Methods" +required = true +type = "MultiSelect" +options = ["PAN_ONLY", "CRYPTOGRAM_3DS"] + [bitpay] [[bitpay.crypto]] payment_method_type = "crypto_currency" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 2f5281162f7..1186e7a34f1 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -1028,11 +1028,83 @@ payment_method_type = "DinersClub" payment_method_type = "CartesBancaires" [[barclaycard.debit]] payment_method_type = "UnionPay" +[[barclaycard.wallet]] + payment_method_type = "google_pay" [barclaycard.connector_auth.SignatureKey] api_key = "Key" key1 = "Merchant ID" api_secret = "Shared Secret" +[[barclaycard.metadata.google_pay]] +name = "merchant_name" +label = "Google Pay Merchant Name" +placeholder = "Enter Google Pay Merchant Name" +required = true +type = "Text" +[[barclaycard.metadata.google_pay]] +name = "merchant_id" +label = "Google Pay Merchant Id" +placeholder = "Enter Google Pay Merchant Id" +required = true +type = "Text" +[[barclaycard.metadata.google_pay]] +name = "gateway_merchant_id" +label = "Google Pay Merchant Key" +placeholder = "Enter Google Pay Merchant Key" +required = true +type = "Text" +[[barclaycard.metadata.google_pay]] +name = "allowed_auth_methods" +label = "Allowed Auth Methods" +placeholder = "Enter Allowed Auth Methods" +required = true +type = "MultiSelect" +options = ["PAN_ONLY", "CRYPTOGRAM_3DS"] + +[[barclaycard.connector_wallets_details.google_pay]] +name = "merchant_name" +label = "Google Pay Merchant Name" +placeholder = "Enter Google Pay Merchant Name" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "merchant_id" +label = "Google Pay Merchant Id" +placeholder = "Enter Google Pay Merchant Id" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "gateway_merchant_id" +label = "Google Pay Merchant Key" +placeholder = "Enter Google Pay Merchant Key" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "public_key" +label = "Google Pay Public Key" +placeholder = "Enter Google Pay Public Key" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "private_key" +label = "Google Pay Private Key" +placeholder = "Enter Google Pay Private Key" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "recipient_id" +label = "Recipient Id" +placeholder = "Enter Recipient Id" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "allowed_auth_methods" +label = "Allowed Auth Methods" +placeholder = "Enter Allowed Auth Methods" +required = true +type = "MultiSelect" +options = ["PAN_ONLY", "CRYPTOGRAM_3DS"] + [cashtocode] [[cashtocode.reward]] payment_method_type = "classic" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index cc3c8afc666..52238493ebc 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -1026,11 +1026,83 @@ payment_method_type = "DinersClub" payment_method_type = "CartesBancaires" [[barclaycard.debit]] payment_method_type = "UnionPay" +[[barclaycard.wallet]] + payment_method_type = "google_pay" [barclaycard.connector_auth.SignatureKey] api_key = "Key" key1 = "Merchant ID" api_secret = "Shared Secret" +[[barclaycard.metadata.google_pay]] +name = "merchant_name" +label = "Google Pay Merchant Name" +placeholder = "Enter Google Pay Merchant Name" +required = true +type = "Text" +[[barclaycard.metadata.google_pay]] +name = "merchant_id" +label = "Google Pay Merchant Id" +placeholder = "Enter Google Pay Merchant Id" +required = true +type = "Text" +[[barclaycard.metadata.google_pay]] +name = "gateway_merchant_id" +label = "Google Pay Merchant Key" +placeholder = "Enter Google Pay Merchant Key" +required = true +type = "Text" +[[barclaycard.metadata.google_pay]] +name = "allowed_auth_methods" +label = "Allowed Auth Methods" +placeholder = "Enter Allowed Auth Methods" +required = true +type = "MultiSelect" +options = ["PAN_ONLY", "CRYPTOGRAM_3DS"] + +[[barclaycard.connector_wallets_details.google_pay]] +name = "merchant_name" +label = "Google Pay Merchant Name" +placeholder = "Enter Google Pay Merchant Name" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "merchant_id" +label = "Google Pay Merchant Id" +placeholder = "Enter Google Pay Merchant Id" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "gateway_merchant_id" +label = "Google Pay Merchant Key" +placeholder = "Enter Google Pay Merchant Key" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "public_key" +label = "Google Pay Public Key" +placeholder = "Enter Google Pay Public Key" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "private_key" +label = "Google Pay Private Key" +placeholder = "Enter Google Pay Private Key" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "recipient_id" +label = "Recipient Id" +placeholder = "Enter Recipient Id" +required = true +type = "Text" +[[barclaycard.connector_wallets_details.google_pay]] +name = "allowed_auth_methods" +label = "Allowed Auth Methods" +placeholder = "Enter Allowed Auth Methods" +required = true +type = "MultiSelect" +options = ["PAN_ONLY", "CRYPTOGRAM_3DS"] + [bitpay] [[bitpay.crypto]] payment_method_type = "crypto_currency" diff --git a/crates/hyperswitch_connectors/src/connectors/barclaycard.rs b/crates/hyperswitch_connectors/src/connectors/barclaycard.rs index 950b985fa68..8448855ac1e 100644 --- a/crates/hyperswitch_connectors/src/connectors/barclaycard.rs +++ b/crates/hyperswitch_connectors/src/connectors/barclaycard.rs @@ -1003,19 +1003,30 @@ static BARCLAYCARD_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, - supported_capture_methods, + 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, + supported_card_networks: supported_card_network.clone(), } }), ), }, ); + barclaycard_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::GooglePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: None, + }, + ); + barclaycard_supported_payment_methods }); diff --git a/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs b/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs index d66782b093c..f519d96e884 100644 --- a/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs @@ -1,7 +1,8 @@ +use base64::Engine; use common_enums::enums; -use common_utils::pii; +use common_utils::{consts, pii}; use hyperswitch_domain_models::{ - payment_method_data::PaymentMethodData, + payment_method_data::{GooglePayWalletData, PaymentMethodData, WalletData}, router_data::{ AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, ErrorResponse, RouterData, @@ -99,6 +100,7 @@ pub struct BarclaycardPaymentsRequest { pub struct ProcessingInformation { commerce_indicator: String, capture: Option<bool>, + payment_solution: Option<String>, } #[derive(Debug, Serialize)] @@ -125,10 +127,17 @@ pub struct CardPaymentInformation { card: Card, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GooglePayPaymentInformation { + fluid_data: FluidData, +} + #[derive(Debug, Serialize)] #[serde(untagged)] pub enum PaymentInformation { Cards(Box<CardPaymentInformation>), + GooglePay(Box<GooglePayPaymentInformation>), } #[derive(Debug, Serialize)] @@ -142,6 +151,12 @@ pub struct Card { card_type: Option<String>, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FluidData { + value: Secret<String>, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderInformationWithBill { @@ -159,55 +174,48 @@ pub struct Amount { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BillTo { - first_name: Option<Secret<String>>, - last_name: Option<Secret<String>>, - address1: Option<Secret<String>>, - locality: Option<String>, - #[serde(skip_serializing_if = "Option::is_none")] - administrative_area: Option<Secret<String>>, - #[serde(skip_serializing_if = "Option::is_none")] - postal_code: Option<Secret<String>>, - country: Option<enums::CountryAlpha2>, + first_name: Secret<String>, + last_name: Secret<String>, + address1: Secret<String>, + locality: String, + administrative_area: Secret<String>, + postal_code: Secret<String>, + country: enums::CountryAlpha2, email: pii::Email, } +fn truncate_string(state: &Secret<String>, max_len: usize) -> Secret<String> { + let exposed = state.clone().expose(); + let truncated = exposed.get(..max_len).unwrap_or(&exposed); + Secret::new(truncated.to_string()) +} + fn build_bill_to( - address_details: Option<&hyperswitch_domain_models::address::Address>, + address_details: &hyperswitch_domain_models::address::AddressDetails, email: pii::Email, ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { - let default_address = BillTo { - first_name: None, - last_name: None, - address1: None, - locality: None, - administrative_area: None, - postal_code: None, - country: None, - email: email.clone(), - }; - - Ok(address_details - .and_then(|addr| { - addr.address.as_ref().map(|addr| { - let administrative_area = addr.to_state_code_as_optional().unwrap_or_else(|_| { - addr.state - .clone() - .map(|state| Secret::new(format!("{:.20}", state.expose()))) - }); - - BillTo { - first_name: addr.first_name.clone(), - last_name: addr.last_name.clone(), - address1: addr.line1.clone(), - locality: addr.city.clone(), - administrative_area, - postal_code: addr.zip.clone(), - country: addr.country, - email, - } - }) + let administrative_area = address_details + .to_state_code_as_optional() + .unwrap_or_else(|_| { + address_details + .get_state() + .ok() + .map(|state| truncate_string(state, 20)) }) - .unwrap_or(default_address)) + .ok_or_else(|| errors::ConnectorError::MissingRequiredField { + field_name: "billing_address.state", + })?; + + Ok(BillTo { + first_name: address_details.get_first_name()?.clone(), + last_name: address_details.get_last_name()?.clone(), + address1: address_details.get_line1()?.clone(), + locality: address_details.get_city()?.clone(), + administrative_area, + postal_code: address_details.get_zip()?.clone(), + country: address_details.get_country()?.to_owned(), + email, + }) } fn get_barclaycard_card_type(card_network: common_enums::CardNetwork) -> Option<&'static str> { @@ -231,6 +239,20 @@ fn get_barclaycard_card_type(card_network: common_enums::CardNetwork) -> Option< } } +#[derive(Debug, Serialize)] +pub enum PaymentSolution { + GooglePay, +} + +impl From<PaymentSolution> for String { + fn from(solution: PaymentSolution) -> Self { + let payment_solution = match solution { + PaymentSolution::GooglePay => "012", + }; + payment_solution.to_string() + } +} + impl From<( &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, @@ -256,14 +278,16 @@ impl impl TryFrom<( &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, + Option<PaymentSolution>, Option<String>, )> for ProcessingInformation { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (item, network): ( + (item, solution, network): ( &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, + Option<PaymentSolution>, Option<String>, ), ) -> Result<Self, Self::Error> { @@ -274,6 +298,7 @@ impl item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None )), + payment_solution: solution.map(String::from), commerce_indicator, }) } @@ -432,10 +457,48 @@ impl }; let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; + let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let payment_information = PaymentInformation::try_from(&ccard)?; - let processing_information = ProcessingInformation::try_from((item, None))?; + let processing_information = ProcessingInformation::try_from((item, None, None))?; + let client_reference_information = ClientReferenceInformation::from(item); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(convert_metadata_to_merchant_defined_info); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + merchant_defined_information, + consumer_authentication_information: None, + }) + } +} + +impl + TryFrom<( + &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, + GooglePayWalletData, + )> for BarclaycardPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, google_pay_data): ( + &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, + GooglePayWalletData, + ), + ) -> Result<Self, Self::Error> { + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?; + let order_information = OrderInformationWithBill::from((item, Some(bill_to))); + let payment_information = PaymentInformation::from(&google_pay_data); + let processing_information = + ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay), None))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item .router_data @@ -462,8 +525,45 @@ impl TryFrom<&BarclaycardRouterData<&PaymentsAuthorizeRouterData>> for Barclayca ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), - PaymentMethodData::Wallet(_) - | PaymentMethodData::MandatePayment + PaymentMethodData::Wallet(wallet_data) => match wallet_data { + WalletData::GooglePay(google_pay_data) => Self::try_from((item, google_pay_data)), + WalletData::AliPayQr(_) + | WalletData::AliPayRedirect(_) + | WalletData::AliPayHkRedirect(_) + | WalletData::AmazonPayRedirect(_) + | WalletData::ApplePay(_) + | 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::RevolutPay(_) + | WalletData::SamsungPay(_) + | WalletData::TwintRedirect {} + | WalletData::VippsRedirect {} + | WalletData::TouchNGoRedirect(_) + | WalletData::WeChatPayRedirect(_) + | WalletData::WeChatPayQr(_) + | WalletData::CashappQr(_) + | WalletData::SwishQr(_) + | WalletData::Paysera(_) + | WalletData::Skrill(_) + | WalletData::BluecodeRedirect {} + | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Barclaycard"), + ) + .into()), + }, + PaymentMethodData::MandatePayment | PaymentMethodData::CardRedirect(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) @@ -1575,6 +1675,18 @@ impl TryFrom<&hyperswitch_domain_models::payment_method_data::Card> for PaymentI } } +impl From<&GooglePayWalletData> for PaymentInformation { + fn from(google_pay_data: &GooglePayWalletData) -> Self { + Self::GooglePay(Box::new(GooglePayPaymentInformation { + fluid_data: FluidData { + value: Secret::from( + consts::BASE64_ENGINE.encode(google_pay_data.tokenization_data.token.clone()), + ), + }, + })) + } +} + fn get_commerce_indicator(network: Option<String>) -> String { match network { Some(card_network) => match card_network.to_lowercase().as_str() { diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs index 875813f4e10..1d7f081c6d8 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -1242,6 +1242,14 @@ fn get_cards_required_fields() -> HashMap<Connector, RequiredFieldFinal> { [card_basic(), email(), full_name(), billing_address()].concat(), ), ), + ( + Connector::Barclaycard, + fields( + vec![], + vec![], + [card_basic(), full_name(), billing_address()].concat(), + ), + ), (Connector::Billwerk, fields(vec![], vec![], card_basic())), ( Connector::Bluesnap, @@ -2408,6 +2416,10 @@ fn get_wallet_required_fields() -> HashMap<enums::PaymentMethodType, ConnectorFi ]), }, ), + ( + Connector::Barclaycard, + fields(vec![], vec![], [full_name(), billing_address()].concat()), + ), (Connector::Bluesnap, fields(vec![], vec![], vec![])), (Connector::Noon, fields(vec![], vec![], vec![])), ( diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 5118bbe1ecc..a626aa60014 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -426,6 +426,11 @@ ideal = { country = "NL", currency = "EUR" } credit = { country = "US,CA", currency = "USD" } debit = { country = "US,CA", currency = "USD" } +[pm_filters.barclaycard] +credit = { currency = "USD,GBP,EUR,PLN,SEK" } +debit = { currency = "USD,GBP,EUR,PLN,SEK" } +google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" } + [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,AU,BR,US", 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,AU,BR,US", 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" }
2025-07-29T08:52:25Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/8784) ## Description <!-- Describe your changes in detail --> Added Google Pay Payment Method ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Payments - Create: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ZJ8oxbhNRWAqo9uJJXbWZF92Y0ym0c9yIDIVZ5tXfsQPOHtBzVsd37g3QGqSGKK7' \ --data-raw ' { "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_data": { "wallet": { "google_pay": { "description": "Visa β€’β€’β€’β€’ 1111", "tokenization_data": { "type": "PAYMENT_GATEWAY", "token": "TOKEN" }, "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" }, "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": "2025-07-25T11:46:12Z" } }' ``` Response: ``` { "payment_id": "pay_OXOmL1tg7bb13kFx9tFL", "merchant_id": "merchant_1753778023", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "barclaycard", "client_secret": "pay_OXOmL1tg7bb13kFx9tFL_secret_pNHiqQi8WiXXXLkluaJW", "created": "2025-07-29T08:33:55.882Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": 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": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "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": 1753778035, "expires": 1753781635, "secret": "epk_b31322ddae424bd2beb80cd2cb99524b" }, "manual_retry_allowed": false, "connector_transaction_id": "7537780387666315904807", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2025-07-25T11:46:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_OXOmL1tg7bb13kFx9tFL_1", "payment_link": null, "profile_id": "pro_9kjWPGq7O6DWWt5nKz01", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_dXVXqDFV5tjATHuyDMbn", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-29T08:48:55.882Z", "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-07-29T08:34:00.138Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": 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.115.0
c1d982e3009ebe192b350c2067bf9c2a708d7320
c1d982e3009ebe192b350c2067bf9c2a708d7320
juspay/hyperswitch
juspay__hyperswitch-8771
Bug: [REFACTOR] move repeated code to a separate function address comments given in this pr: https://github.com/juspay/hyperswitch/pull/8616
diff --git a/crates/diesel_models/src/mandate.rs b/crates/diesel_models/src/mandate.rs index 7ed37dc2fd6..f4c507e471d 100644 --- a/crates/diesel_models/src/mandate.rs +++ b/crates/diesel_models/src/mandate.rs @@ -78,10 +78,26 @@ pub struct MandateNew { pub customer_user_agent_extended: Option<String>, } +impl Mandate { + /// Returns customer_user_agent_extended with customer_user_agent as fallback + pub fn get_user_agent_extended(&self) -> Option<String> { + self.customer_user_agent_extended + .clone() + .or_else(|| self.customer_user_agent.clone()) + } +} + impl MandateNew { pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } + + /// Returns customer_user_agent_extended with customer_user_agent as fallback + pub fn get_customer_user_agent_extended(&self) -> Option<String> { + self.customer_user_agent_extended + .clone() + .or_else(|| self.customer_user_agent.clone()) + } } #[derive(Debug)] @@ -238,10 +254,7 @@ impl From<&MandateNew> for Mandate { merchant_connector_id: mandate_new.merchant_connector_id.clone(), updated_by: mandate_new.updated_by.clone(), // Using customer_user_agent as a fallback - customer_user_agent_extended: mandate_new - .customer_user_agent_extended - .clone() - .or_else(|| mandate_new.customer_user_agent.clone()), + customer_user_agent_extended: mandate_new.get_customer_user_agent_extended(), } } } diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs index 3bd80407fc2..caae9dec68c 100644 --- a/crates/router/src/db/mandate.rs +++ b/crates/router/src/db/mandate.rs @@ -661,6 +661,8 @@ impl MandateInterface for MockDb { _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let mut mandates = self.mandates.lock().await; + let customer_user_agent_extended = mandate_new.get_customer_user_agent_extended(); + let mandate = storage_types::Mandate { mandate_id: mandate_new.mandate_id.clone(), customer_id: mandate_new.customer_id, @@ -688,10 +690,7 @@ impl MandateInterface for MockDb { connector_mandate_ids: mandate_new.connector_mandate_ids, merchant_connector_id: mandate_new.merchant_connector_id, updated_by: mandate_new.updated_by, - // Using customer_user_agent as a fallback - customer_user_agent_extended: mandate_new - .customer_user_agent_extended - .or_else(|| mandate_new.customer_user_agent.clone()), + customer_user_agent_extended, }; mandates.push(mandate.clone()); Ok(mandate) diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs index 343d6e196ba..5d39c5e1943 100644 --- a/crates/router/src/types/api/mandates.rs +++ b/crates/router/src/types/api/mandates.rs @@ -95,6 +95,7 @@ impl MandateResponseExt for MandateResponse { let payment_method_type = payment_method .get_payment_method_subtype() .map(|pmt| pmt.to_string()); + let user_agent = mandate.get_user_agent_extended().unwrap_or_default(); Ok(Self { mandate_id: mandate.mandate_id, customer_acceptance: Some(api::payments::CustomerAcceptance { @@ -106,11 +107,7 @@ impl MandateResponseExt for MandateResponse { accepted_at: mandate.customer_accepted_at, online: Some(api::payments::OnlineMandate { ip_address: mandate.customer_ip_address, - // Using customer_user_agent as a fallback - user_agent: mandate - .customer_user_agent_extended - .or(mandate.customer_user_agent) - .unwrap_or_default(), + user_agent, }), }), card,
2025-07-28T11:25:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> this pr addresses the comments which is concerned about reducing repeated code by moving them into a separate function within impl block. ### 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). --> address comments that was given in [this](https://github.com/juspay/hyperswitch/pull/8616) pr. closes https://github.com/juspay/hyperswitch/issues/8771 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> just a minor refactor. nothing to test here. however: - ci should pass - tested mandates by following https://github.com/juspay/hyperswitch/pull/8616 ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `just clippy && just clippy_v2` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.115.0
5ca0fb5f654c9b32186dab8a2a2d475f2eb7df6a
5ca0fb5f654c9b32186dab8a2a2d475f2eb7df6a
juspay/hyperswitch
juspay__hyperswitch-8781
Bug: [BUG] user bank options sent inside the eps `user_bank_options` field should be dynamic for stripe the user bank options sent in `user_bank_options` should be dynamic and picked from .toml files
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 9239142f57b..4dd171215e2 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -27686,7 +27686,8 @@ "items": { "$ref": "#/components/schemas/BankCodeResponse" }, - "description": "The list of banks enabled, if applicable for a payment method type", + "description": "The list of banks enabled, if applicable for a payment method type . To be deprecated soon.", + "deprecated": true, "nullable": true }, "bank_debits": { diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index a70dceb962d..278d158fe46 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -1442,7 +1442,8 @@ pub struct ResponsePaymentMethodTypes { /// The list of card networks enabled, if applicable for a payment method type pub card_networks: Option<Vec<CardNetworkTypes>>, - /// The list of banks enabled, if applicable for a payment method type + #[schema(deprecated)] + /// The list of banks enabled, if applicable for a payment method type . To be deprecated soon. pub bank_names: Option<Vec<BankCodeResponse>>, /// The Bank debit payment method information, if applicable for a payment method type. diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs index 2dd291d16f5..90399dde29e 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -6,8 +6,9 @@ use api_models::{ }; use crate::configs::settings::{ - ConnectorFields, Mandates, RequiredFieldFinal, SupportedConnectorsForMandate, - SupportedPaymentMethodTypesForMandate, SupportedPaymentMethodsForMandate, ZeroMandates, + BankRedirectConfig, ConnectorFields, Mandates, RequiredFieldFinal, + SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate, + SupportedPaymentMethodsForMandate, ZeroMandates, }; #[cfg(feature = "v1")] use crate::configs::settings::{PaymentMethodType, RequiredFields}; @@ -1003,8 +1004,8 @@ pub fn get_shipping_required_fields() -> HashMap<String, RequiredFieldInfo> { } #[cfg(feature = "v1")] -impl Default for RequiredFields { - fn default() -> Self { +impl RequiredFields { + pub fn new(bank_config: &BankRedirectConfig) -> Self { let cards_required_fields = get_cards_required_fields(); let mut debit_required_fields = cards_required_fields.clone(); debit_required_fields.extend(HashMap::from([ @@ -1045,7 +1046,7 @@ impl Default for RequiredFields { ), ( enums::PaymentMethod::BankRedirect, - PaymentMethodType(get_bank_redirect_required_fields()), + PaymentMethodType(get_bank_redirect_required_fields(bank_config)), ), ( enums::PaymentMethod::Wallet, @@ -1203,6 +1204,13 @@ impl Default for RequiredFields { } } +#[cfg(feature = "v1")] +impl Default for RequiredFields { + fn default() -> Self { + Self::new(&BankRedirectConfig::default()) + } +} + #[cfg(feature = "v1")] fn get_cards_required_fields() -> HashMap<Connector, RequiredFieldFinal> { HashMap::from([ @@ -1563,7 +1571,9 @@ fn get_cards_required_fields() -> HashMap<Connector, RequiredFieldFinal> { } #[cfg(feature = "v1")] -fn get_bank_redirect_required_fields() -> HashMap<enums::PaymentMethodType, ConnectorFields> { +fn get_bank_redirect_required_fields( + bank_config: &BankRedirectConfig, +) -> HashMap<enums::PaymentMethodType, ConnectorFields> { HashMap::from([ ( enums::PaymentMethodType::OpenBankingUk, @@ -2028,69 +2038,14 @@ fn get_bank_redirect_required_fields() -> HashMap<enums::PaymentMethodType, Conn FieldType::UserFullName, ), RequiredField::EpsBankOptions( - vec![ - enums::BankNames::AbnAmro, - enums::BankNames::ArzteUndApothekerBank, - enums::BankNames::AsnBank, - enums::BankNames::AustrianAnadiBankAg, - enums::BankNames::BankAustria, - enums::BankNames::BankhausCarlSpangler, - enums::BankNames::BankhausSchelhammerUndSchatteraAg, - enums::BankNames::BawagPskAg, - enums::BankNames::BksBankAg, - enums::BankNames::BrullKallmusBankAg, - enums::BankNames::BtvVierLanderBank, - enums::BankNames::Bunq, - enums::BankNames::CapitalBankGraweGruppeAg, - enums::BankNames::Citi, - enums::BankNames::Dolomitenbank, - enums::BankNames::EasybankAg, - enums::BankNames::ErsteBankUndSparkassen, - enums::BankNames::Handelsbanken, - enums::BankNames::HypoAlpeadriabankInternationalAg, - enums::BankNames::HypoNoeLbFurNiederosterreichUWien, - enums::BankNames::HypoOberosterreichSalzburgSteiermark, - enums::BankNames::HypoTirolBankAg, - enums::BankNames::HypoVorarlbergBankAg, - enums::BankNames::HypoBankBurgenlandAktiengesellschaft, - enums::BankNames::Ing, - enums::BankNames::Knab, - enums::BankNames::MarchfelderBank, - enums::BankNames::OberbankAg, - enums::BankNames::RaiffeisenBankengruppeOsterreich, - enums::BankNames::Rabobank, - enums::BankNames::Regiobank, - enums::BankNames::Revolut, - enums::BankNames::SnsBank, - enums::BankNames::TriodosBank, - enums::BankNames::VanLanschot, - enums::BankNames::Moneyou, - enums::BankNames::SchoellerbankAg, - enums::BankNames::SpardaBankWien, - enums::BankNames::VolksbankGruppe, - enums::BankNames::VolkskreditbankAg, - enums::BankNames::VrBankBraunau, - enums::BankNames::PlusBank, - enums::BankNames::EtransferPocztowy24, - enums::BankNames::BankiSpbdzielcze, - enums::BankNames::BankNowyBfgSa, - enums::BankNames::GetinBank, - enums::BankNames::Blik, - enums::BankNames::NoblePay, - enums::BankNames::IdeaBank, - enums::BankNames::EnveloBank, - enums::BankNames::NestPrzelew, - enums::BankNames::MbankMtransfer, - enums::BankNames::Inteligo, - enums::BankNames::PbacZIpko, - enums::BankNames::BnpParibas, - enums::BankNames::BankPekaoSa, - enums::BankNames::VolkswagenBank, - enums::BankNames::AliorBank, - enums::BankNames::Boz, - ] - .into_iter() - .collect(), + bank_config + .0 + .get(&enums::PaymentMethodType::Eps) + .and_then(|connector_bank_names| { + connector_bank_names.0.get("stripe") + }) + .map(|bank_names| bank_names.banks.clone()) + .unwrap_or_default(), ), RequiredField::BillingLastName("billing_name", FieldType::UserFullName), ], diff --git a/crates/payment_methods/src/configs/settings.rs b/crates/payment_methods/src/configs/settings.rs index 888a17cd0a8..9bad38ccad9 100644 --- a/crates/payment_methods/src/configs/settings.rs +++ b/crates/payment_methods/src/configs/settings.rs @@ -22,6 +22,17 @@ pub struct ConnectorFields { pub fields: HashMap<enums::Connector, RequiredFieldFinal>, } +#[derive(Debug, Deserialize, Clone, Default)] +pub struct BankRedirectConfig(pub HashMap<enums::PaymentMethodType, ConnectorBankNames>); +#[derive(Debug, Deserialize, Clone)] +pub struct ConnectorBankNames(pub HashMap<String, BanksVector>); + +#[derive(Debug, Deserialize, Clone)] +pub struct BanksVector { + #[serde(deserialize_with = "deserialize_hashset")] + pub banks: HashSet<common_enums::enums::BankNames>, +} + #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize, Clone)] pub struct RequiredFieldFinal { diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index ae4c8a3cda0..0e057d5310d 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -30,9 +30,10 @@ use hyperswitch_interfaces::{ }; use masking::Secret; pub use payment_methods::configs::settings::{ - ConnectorFields, EligiblePaymentMethods, Mandates, PaymentMethodAuth, PaymentMethodType, - RequiredFieldFinal, RequiredFields, SupportedConnectorsForMandate, - SupportedPaymentMethodTypesForMandate, SupportedPaymentMethodsForMandate, ZeroMandates, + BankRedirectConfig, BanksVector, ConnectorBankNames, ConnectorFields, EligiblePaymentMethods, + Mandates, PaymentMethodAuth, PaymentMethodType, RequiredFieldFinal, RequiredFields, + SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate, + SupportedPaymentMethodsForMandate, ZeroMandates, }; use redis_interface::RedisSettings; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; @@ -652,17 +653,6 @@ pub enum PaymentMethodTypeTokenFilter { AllAccepted, } -#[derive(Debug, Deserialize, Clone, Default)] -pub struct BankRedirectConfig(pub HashMap<enums::PaymentMethodType, ConnectorBankNames>); -#[derive(Debug, Deserialize, Clone)] -pub struct ConnectorBankNames(pub HashMap<String, BanksVector>); - -#[derive(Debug, Deserialize, Clone)] -pub struct BanksVector { - #[serde(deserialize_with = "deserialize_hashset")] - pub banks: HashSet<common_enums::enums::BankNames>, -} - #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct ConnectorFilters(pub HashMap<String, PaymentMethodFilters>); @@ -986,9 +976,14 @@ impl Settings<SecuredSecret> { .build() .change_context(ApplicationError::ConfigurationError)?; - serde_path_to_error::deserialize(config) + let mut settings: Self = serde_path_to_error::deserialize(config) .attach_printable("Unable to deserialize application configuration") - .change_context(ApplicationError::ConfigurationError) + .change_context(ApplicationError::ConfigurationError)?; + #[cfg(feature = "v1")] + { + settings.required_fields = RequiredFields::new(&settings.bank_config); + } + Ok(settings) } pub fn validate(&self) -> ApplicationResult<()> {
2025-07-29T04:58:58Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Previously the bank names were hard coded but we needed to read form `{config}.toml` files to send the supported banks inside `user_bank_options` ## Depricating bank list on top level of `ResponsePaymentMethodTypes` as we need to send it inside particular required fields . ```rust pub struct ResponsePaymentMethodTypes { /// The payment method type enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The list of payment experiences enabled, if applicable for a payment method type pub payment_experience: Option<Vec<PaymentExperienceTypes>>, /// The list of card networks enabled, if applicable for a payment method type pub card_networks: Option<Vec<CardNetworkTypes>>, #[schema(deprecated)] // --------------------DEPRICATED-------------------------- // /// The list of banks enabled, if applicable for a payment method type pub bank_names: Option<Vec<BankCodeResponse>>, /// The Bank debit payment method information, if applicable for a payment method type. pub bank_debits: Option<BankDebitTypes>, /// The Bank transfer payment method information, if applicable for a payment method type. pub bank_transfers: Option<BankTransferTypes>, /// Required fields for the payment_method_type. pub required_fields: Option<HashMap<String, RequiredFieldInfo>>, /// surcharge details for this payment method type if exists pub surcharge_details: Option<SurchargeDetailsResponse>, /// auth service connector label for this payment method type, if exists pub pm_auth_connector: Option<String>, } ``` ## payment method types response <details> <summary>Payment Request</summary> ```json { "payment_id": "pay_6W7NAlavGWBsNle4fjCm", "merchant_id": "merchant_1751973151", "status": "requires_payment_method", "amount": 6500, "net_amount": 6500, "amount_capturable": 0, "client_secret": "pay_6W7NAlavGWBsNle4fjCm_secret_cGp7blq0k5NBezW6gCmH", "created": "2025-07-08T11:49:13.894Z", "currency": "EUR", "customer_id": "hyperswitch_sdk_demo_id", "customer": { "id": "hyperswitch_sdk_demo_id", "email": "user@gmail.com" }, "description": "Hello this is description", "setup_future_usage": "on_session", "capture_method": "automatic", "shipping": { "address": { "city": "Banglore", "country": "AT", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "billing": { "address": { "city": "San Fransico", "country": "AT", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "order_details": [ { "amount": 6500, "quantity": 1, "product_name": "Apple iphone 15" } ], "email": "user@gmail.com", "business_label": "default", "ephemeral_key": { "customer_id": "hyperswitch_sdk_demo_id", "created_at": 1751975353, "expires": 1751978953, "secret": "epk_78740ac9b3a7426e9ed57c14c801fb4f" }, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "noon": { "order_category": "applepay" } }, "profile_id": "pro_2UxGWjdVxvRMEw6zBI2V", "attempt_count": 1, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-08T12:04:13.894Z", "updated": "2025-07-08T11:49:13.908Z", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false } ``` </details> ### GET http://localhost:8080/account/payment_methods?client_secret=pay_gvSgEeG6HZU6PnwbHhno_secret_gTL5Uke9uC8r3XGUs3Kx ```json { "redirect_url": "https://google.com/success", "currency": "EUR", "payment_methods": [ { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "eps", "payment_experience": null, "card_networks": null, "bank_names": [ { "bank_name": [ "hypo_tirol_bank_ag", "brull_kallmus_bank_ag", "volkskreditbank_ag", "capital_bank_grawe_gruppe_ag", "btv_vier_lander_bank", "marchfelder_bank", "easybank_ag", "hypo_vorarlberg_bank_ag", "hypo_alpeadriabank_international_ag", "oberbank_ag", "hypo_noe_lb_fur_niederosterreich_u_wien", "volksbank_gruppe", "hypo_oberosterreich_salzburg_steiermark", "hypo_bank_burgenland_aktiengesellschaft", "dolomitenbank", "austrian_anadi_bank_ag", "raiffeisen_bankengruppe_osterreich", "sparda_bank_wien", "arzte_und_apotheker_bank", "bankhaus_schelhammer_und_schattera_ag", "bank_austria", "bawag_psk_ag", "schoellerbank_ag", "vr_bank_braunau", "erste_bank_und_sparkassen", "bankhaus_carl_spangler", "bks_bank_ag" ], "eligible_connectors": ["stripe"] } ], "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "billing_name", "field_type": "user_full_name", "value": "joseph" }, "payment_method_data.bank_redirect.eps.bank_name": { "required_field": "payment_method_data.bank_redirect.eps.bank_name", "display_name": "bank_name", "field_type": { "user_bank_options": { "options": [ "hypo_tirol_bank_ag", "brull_kallmus_bank_ag", "volkskreditbank_ag", "capital_bank_grawe_gruppe_ag", "btv_vier_lander_bank", "marchfelder_bank", "easybank_ag", "hypo_vorarlberg_bank_ag", "hypo_alpeadriabank_international_ag", "oberbank_ag", "hypo_noe_lb_fur_niederosterreich_u_wien", "volksbank_gruppe", "hypo_oberosterreich_salzburg_steiermark", "hypo_bank_burgenland_aktiengesellschaft", "dolomitenbank", "austrian_anadi_bank_ag", "raiffeisen_bankengruppe_osterreich", "sparda_bank_wien", "arzte_und_apotheker_bank", "bankhaus_schelhammer_und_schattera_ag", "bank_austria", "bawag_psk_ag", "schoellerbank_ag", "vr_bank_braunau", "erste_bank_und_sparkassen", "bankhaus_carl_spangler", "bks_bank_ag" ] } }, "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "billing_name", "field_type": "user_full_name", "value": "Doe" } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false, "is_tax_calculation_enabled": false } ``` Related Pr: https://github.com/juspay/hyperswitch/pull/8577 ### Additional Changes - [x] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.115.0
1e6a088c04b40c7fdd5bc65c1973056bf58de764
1e6a088c04b40c7fdd5bc65c1973056bf58de764
juspay/hyperswitch
juspay__hyperswitch-8740
Bug: [FEATURE] Checkbook connector ACH integrate ### Feature Description Integrate CHECKBOOK CONNECTOR ### Possible Implementation https://docs.checkbook.io/docs/concepts/environments/ ### 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/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index ccd6d2e11b7..67a9aa9735d 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -11183,6 +11183,7 @@ "cashtocode", "celero", "chargebee", + "checkbook", "checkout", "coinbase", "coingate", @@ -28310,6 +28311,7 @@ "celero", "chargebee", "custombilling", + "checkbook", "checkout", "coinbase", "coingate", diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 5550c859ca9..23092be8de9 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -8198,6 +8198,7 @@ "cashtocode", "celero", "chargebee", + "checkbook", "checkout", "coinbase", "coingate", @@ -22824,6 +22825,7 @@ "celero", "chargebee", "custombilling", + "checkbook", "checkout", "coinbase", "coingate", diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index ddff65fa9c0..d0a49abaf8d 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -346,6 +346,9 @@ credit = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IS,IE,IT,LV,LI,LT,L google_pay = { country = "AL, DZ, AS, AO, AG, AR, AU, AT, AZ, BH, BY, BE, BR, CA, BG, CL, CO, HR, DK, DO, EE, EG, FI, FR, DE, GR, HK, HU, IN, ID, IE, IL, IT, JP, JO, KZ, KE, KW, LV, LB, LT, LU, MY, MX, NL, NZ, NO, OM, PK, PA, PE, PH, PL, PT, QA, RO, SA, SG, SK, ZA, ES, LK, SE, CH, TH, TW, TR, UA, AE, US, UY, VN", currency = "AED, ALL, AOA, AUD, AZN, BGN, BHD, BRL, CAD, CHF, CLP, COP, CZK, DKK, DOP, DZD, EGP, EUR, GBP, HKD, HUF, IDR, ILS, INR, JPY, KES, KWD, KZT, LKR, MXN, MYR, NOK, NZD, OMR, PAB, PEN, PHP, PKR, PLN, QAR, RON, SAR, SEK, SGD, THB, TRY, TWD, UAH, USD, UYU, VND, XCD, ZAR" } apple_pay = { country = "AM, AT, AZ, BY, BE, BG, HR, CY, 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, VA, AU , HK, JP , MY , MN, NZ, SG, TW, VN, EG , MA, ZA, AR, BR, CL, CO, CR, DO, EC, SV, GT, HN, MX, PA, PY, PE, UY, BH, IL, JO, KW, OM,QA, SA, AE, CA", currency = "EGP, MAD, ZAR, AUD, CNY, HKD, JPY, MOP, MYR, MNT, NZD, SGD, KRW, TWD, VND, AMD, EUR, BGN, CZK, DKK, GEL, GBP, HUF, ISK, KZT, CHF, MDL, NOK, PLN, RON, RSD, SEK, UAH, BRL, COP, CRC, DOP, GTQ, HNL, MXN, PAB, PYG, PEN, BSD, UYU, BHD, ILS, JOD, KWD, OMR, QAR, SAR, AED, CAD, USD" } +[pm_filters.checkbook] +ach = { country = "US", currency = "USD" } + [pm_filters.elavon] credit = { country = "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,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" } debit = { country = "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,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" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 11d96d6269f..79de6f569fc 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -546,6 +546,9 @@ eps = { country = "AT" , currency = "EUR" } mb_way = { country = "PT" , currency = "EUR" } sofort = { country = "AT,BE,FR,DE,IT,PL,ES,CH,GB" , currency = "EUR"} +[pm_filters.checkbook] +ach = { country = "US", currency = "USD" } + [pm_filters.cashtocode] classic = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,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,BYN,BZD,CAD,CDF,CHF,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } evoucher = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,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,BYN,BZD,CAD,CDF,CHF,CLF,CLP,CNY,COP,CRC,CUC,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,STD,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" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index a372c873c78..4f95f8a2ed5 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -421,6 +421,9 @@ apple_pay = { currency = "USD" } google_pay = { currency = "USD" } samsung_pay = { currency = "USD" } +[pm_filters.checkbook] +ach = { country = "US", currency = "USD" } + [pm_filters.cybersource] credit = { currency = "USD,GBP,EUR,PLN,SEK" } debit = { currency = "USD,GBP,EUR,PLN,SEK" } diff --git a/config/development.toml b/config/development.toml index 173d9363f2a..3f7ba18a9b9 100644 --- a/config/development.toml +++ b/config/development.toml @@ -620,6 +620,9 @@ credit = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IS,IE,IT,LV,LI,LT,L google_pay = { country = "AL, DZ, AS, AO, AG, AR, AU, AT, AZ, BH, BY, BE, BR, CA, BG, CL, CO, HR, DK, DO, EE, EG, FI, FR, DE, GR, HK, HU, IN, ID, IE, IL, IT, JP, JO, KZ, KE, KW, LV, LB, LT, LU, MY, MX, NL, NZ, NO, OM, PK, PA, PE, PH, PL, PT, QA, RO, SA, SG, SK, ZA, ES, LK, SE, CH, TH, TW, TR, UA, AE, US, UY, VN", currency = "AED, ALL, AOA, AUD, AZN, BGN, BHD, BRL, CAD, CHF, CLP, COP, CZK, DKK, DOP, DZD, EGP, EUR, GBP, HKD, HUF, IDR, ILS, INR, JPY, KES, KWD, KZT, LKR, MXN, MYR, NOK, NZD, OMR, PAB, PEN, PHP, PKR, PLN, QAR, RON, SAR, SEK, SGD, THB, TRY, TWD, UAH, USD, UYU, VND, XCD, ZAR" } apple_pay = { country = "AM, AT, AZ, BY, BE, BG, HR, CY, 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, VA, AU , HK, JP , MY , MN, NZ, SG, TW, VN, EG , MA, ZA, AR, BR, CL, CO, CR, DO, EC, SV, GT, HN, MX, PA, PY, PE, UY, BH, IL, JO, KW, OM,QA, SA, AE, CA", currency = "EGP, MAD, ZAR, AUD, CNY, HKD, JPY, MOP, MYR, MNT, NZD, SGD, KRW, TWD, VND, AMD, EUR, BGN, CZK, DKK, GEL, GBP, HUF, ISK, KZT, CHF, MDL, NOK, PLN, RON, RSD, SEK, UAH, BRL, COP, CRC, DOP, GTQ, HNL, MXN, PAB, PYG, PEN, BSD, UYU, BHD, ILS, JOD, KWD, OMR, QAR, SAR, AED, CAD, USD" } +[pm_filters.checkbook] +ach = { country = "US", 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,AU,BR,US", 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,AU,BR,US", 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" } diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index cb5195925c5..11aa2e7104e 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -78,7 +78,7 @@ pub enum RoutableConnectors { Celero, Chargebee, Custombilling, - // Checkbook, + Checkbook, Checkout, Coinbase, Coingate, @@ -238,7 +238,7 @@ pub enum Connector { Cashtocode, Celero, Chargebee, - // Checkbook, + Checkbook, Checkout, Coinbase, Coingate, @@ -426,7 +426,7 @@ impl Connector { | Self::Cashtocode | Self::Celero | Self::Chargebee - // | Self::Checkbook + | Self::Checkbook | Self::Coinbase | Self::Coingate | Self::Cryptopay @@ -593,7 +593,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Celero => Self::Celero, RoutableConnectors::Chargebee => Self::Chargebee, RoutableConnectors::Custombilling => Self::Custombilling, - // RoutableConnectors::Checkbook => Self::Checkbook, + RoutableConnectors::Checkbook => Self::Checkbook, RoutableConnectors::Checkout => Self::Checkout, RoutableConnectors::Coinbase => Self::Coinbase, RoutableConnectors::Cryptopay => Self::Cryptopay, @@ -716,7 +716,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Cashtocode => Ok(Self::Cashtocode), Connector::Celero => Ok(Self::Celero), Connector::Chargebee => Ok(Self::Chargebee), - // Connector::Checkbook => Ok(Self::Checkbook), + Connector::Checkbook => Ok(Self::Checkbook), Connector::Checkout => Ok(Self::Checkout), Connector::Coinbase => Ok(Self::Coinbase), Connector::Coingate => Ok(Self::Coingate), diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 61736a42edf..cb6c9062ca3 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -390,6 +390,7 @@ impl ConnectorConfig { Connector::Cashtocode => Ok(connector_data.cashtocode), Connector::Celero => Ok(connector_data.celero), Connector::Chargebee => Ok(connector_data.chargebee), + Connector::Checkbook => Ok(connector_data.checkbook), Connector::Checkout => Ok(connector_data.checkout), Connector::Coinbase => Ok(connector_data.coinbase), Connector::Coingate => Ok(connector_data.coingate), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 9e493eb6a54..0a3897aedc4 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -1360,6 +1360,17 @@ merchant_id_evoucher="MerchantId Evoucher" [cashtocode.connector_webhook_details] merchant_secret="Source verification key" +[checkbook] +[[checkbook.bank_transfer]] +payment_method_type = "ach" + +[checkbook.connector_auth.BodyKey] +key1 = "Checkbook Publishable key" +api_key = "Checkbook API Secret key" + +[checkbook.connector_webhook_details] +merchant_secret="Source verification key" + [checkout] [[checkout.credit]] payment_method_type = "Mastercard" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index e81c3f6aac9..cebc0aaabec 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -1122,6 +1122,15 @@ key1 = "Secret Key" [cryptopay.connector_webhook_details] merchant_secret = "Source verification key" +[checkbook] +[[checkbook.bank_transfer]] + payment_method_type = "ach" +[checkbook.connector_auth.BodyKey] + key1 = "Checkbook Publishable key" + api_key = "Checkbook API Secret key" +[checkbook.connector_webhook_details] + merchant_secret="Source verification key" + [checkout] [[checkout.credit]] payment_method_type = "Mastercard" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index bdd9cde57f0..d16708ff4f4 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -1359,6 +1359,15 @@ merchant_id_evoucher = "MerchantId Evoucher" [cashtocode.connector_webhook_details] merchant_secret = "Source verification key" +[checkbook] +[[checkbook.bank_transfer]] + payment_method_type = "ach" +[checkbook.connector_auth.BodyKey] + key1 = "Checkbook Publishable key" + api_key = "Checkbook API Secret key" +[checkbook.connector_webhook_details] + merchant_secret="Source verification key" + [checkout] [[checkout.credit]] payment_method_type = "Mastercard" diff --git a/crates/hyperswitch_connectors/src/connectors/checkbook.rs b/crates/hyperswitch_connectors/src/connectors/checkbook.rs index e0f31ceb57f..90148c84f88 100644 --- a/crates/hyperswitch_connectors/src/connectors/checkbook.rs +++ b/crates/hyperswitch_connectors/src/connectors/checkbook.rs @@ -1,12 +1,16 @@ pub mod transformers; +use std::sync::LazyLock; + +use api_models::{enums, payments::PaymentIdType}; use common_utils::{ + crypto, errors::CustomResult, - ext_traits::BytesExt, + ext_traits::{ByteSliceExt, BytesExt}, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; -use error_stack::{report, ResultExt}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ @@ -19,9 +23,12 @@ 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, + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; @@ -39,7 +46,7 @@ use hyperswitch_interfaces::{ use masking::{ExposeInterface, Mask}; use transformers as checkbook; -use crate::{constants::headers, types::ResponseRouterData, utils}; +use crate::{constants::headers, types::ResponseRouterData}; #[derive(Clone)] pub struct Checkbook { @@ -115,9 +122,14 @@ impl ConnectorCommon for Checkbook { ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = checkbook::CheckbookAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let auth_key = format!( + "{}:{}", + auth.publishable_key.expose(), + auth.secret_key.expose() + ); Ok(vec![( headers::AUTHORIZATION.to_string(), - auth.api_key.expose().into_masked(), + auth_key.into_masked(), )]) } @@ -148,9 +160,7 @@ impl ConnectorCommon for Checkbook { } } -impl ConnectorValidation for Checkbook { - //TODO: implement functions when support enabled -} +impl ConnectorValidation for Checkbook {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Checkbook { //TODO: implement sessions flow @@ -179,9 +189,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!("{}/v3/invoice", self.base_url(connectors))) } fn get_request_body( @@ -189,14 +199,11 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData 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 = checkbook::CheckbookRouterData::from((amount, req)); - let connector_req = checkbook::CheckbookPaymentsRequest::try_from(&connector_router_data)?; + let amount = self + .amount_converter + .convert(req.request.minor_amount, req.request.currency) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let connector_req = checkbook::CheckbookPaymentsRequest::try_from((amount, req))?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -265,10 +272,19 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Che 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_txn_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + Ok(format!( + "{}/v3/invoice/{}", + self.base_url(connectors), + connector_txn_id + )) } fn build_request( @@ -314,64 +330,53 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Che } } -impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Checkbook { +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Checkbook {} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Checkbook { fn get_headers( &self, - req: &PaymentsCaptureRouterData, + req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - fn get_url( &self, - _req: &PaymentsCaptureRouterData, - _connectors: &Connectors, + req: &PaymentsCancelRouterData, + 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()) + Ok(format!( + "{}v3/invoice/{}", + self.base_url(connectors), + req.request.connector_transaction_id + )) } fn build_request( &self, - req: &PaymentsCaptureRouterData, + req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() - .method(Method::Post) - .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .method(Method::Delete) + .url(&types::PaymentsVoidType::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, - )?) + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &PaymentsCaptureRouterData, + data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: checkbook::CheckbookPaymentsResponse = res .response - .parse_struct("Checkbook PaymentsCaptureResponse") + .parse_struct("Checkbook PaymentsCancelResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -391,8 +396,6 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo } } -impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Checkbook {} - impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Checkbook { fn get_headers( &self, @@ -411,23 +414,23 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Checkbo _req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Err(errors::ConnectorError::NotSupported { + message: "Refunds are not supported".to_string(), + connector: "checkbook", + } + .into()) } fn get_request_body( &self, - req: &RefundsRouterData<Execute>, + _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 = checkbook::CheckbookRouterData::from((refund_amount, req)); - let connector_req = checkbook::CheckbookRefundRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) + Err(errors::ConnectorError::NotSupported { + message: "Refunds are not supported".to_string(), + connector: "checkbook", + } + .into()) } fn build_request( @@ -451,21 +454,11 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Checkbo fn handle_response( &self, - data: &RefundsRouterData<Execute>, - event_builder: Option<&mut ConnectorEvent>, - res: Response, + _data: &RefundsRouterData<Execute>, + _event_builder: Option<&mut ConnectorEvent>, + _res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { - let response: checkbook::RefundResponse = res - .response - .parse_struct("checkbook 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, - }) + Err(errors::ConnectorError::NotImplemented("Refunds are not supported".to_string()).into()) } fn get_error_response( @@ -518,21 +511,11 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Checkbook fn handle_response( &self, - data: &RefundSyncRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, + _data: &RefundSyncRouterData, + _event_builder: Option<&mut ConnectorEvent>, + _res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { - let response: checkbook::RefundResponse = res - .response - .parse_struct("checkbook 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, - }) + Err(errors::ConnectorError::NotImplemented("Refunds are not supported".to_string()).into()) } fn get_error_response( @@ -548,24 +531,128 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Checkbook impl webhooks::IncomingWebhook for Checkbook { fn get_webhook_object_reference_id( &self, - _request: &webhooks::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let details: checkbook::CheckbookPaymentsResponse = request + .body + .parse_struct("CheckbookWebhookResponse") + .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + PaymentIdType::ConnectorTransactionId(details.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 details: checkbook::CheckbookPaymentsResponse = request + .body + .parse_struct("CheckbookWebhookResponse") + .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; + Ok(api_models::webhooks::IncomingWebhookEvent::from( + details.status, + )) } 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 details: checkbook::CheckbookPaymentsResponse = request + .body + .parse_struct("CheckbookWebhookResponse") + .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; + Ok(Box::new(details)) + } + + fn get_webhook_source_verification_algorithm( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + Ok(Box::new(crypto::HmacSha256)) + } + + fn get_webhook_source_verification_signature( + &self, + request: &webhooks::IncomingWebhookRequestDetails<'_>, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let header_value = request + .headers + .get("signature") + .ok_or(errors::ConnectorError::WebhookSignatureNotFound) + .attach_printable("Failed to get signature for checkbook")? + .to_str() + .map_err(|_| errors::ConnectorError::WebhookSignatureNotFound) + .attach_printable("Failed to get signature for checkbook")?; + let signature = header_value + .split(',') + .find_map(|s| s.strip_prefix("signature=")) + .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?; + hex::decode(signature) + .change_context(errors::ConnectorError::WebhookSignatureNotFound) + .attach_printable("Failed to decrypt checkbook webhook payload for verification") + } + + 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 header_value = request + .headers + .get("signature") + .ok_or(errors::ConnectorError::WebhookSignatureNotFound)? + .to_str() + .map_err(|_| errors::ConnectorError::WebhookSignatureNotFound)?; + let nonce = header_value + .split(',') + .find_map(|s| s.strip_prefix("nonce=")) + .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?; + let message = format!("{}{}", String::from_utf8_lossy(request.body), nonce); + Ok(message.into_bytes()) } } -impl ConnectorSpecifications for Checkbook {} +static CHECKBOOK_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { + let supported_capture_methods = vec![enums::CaptureMethod::Automatic]; + + let mut checkbook_supported_payment_methods = SupportedPaymentMethods::new(); + + checkbook_supported_payment_methods.add( + enums::PaymentMethod::BankTransfer, + enums::PaymentMethodType::Ach, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::NotSupported, + supported_capture_methods, + specific_features: None, + }, + ); + checkbook_supported_payment_methods + }); + +static CHECKBOOK_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Checkbook", + description: + "Checkbook is a payment platform that allows users to send and receive digital checks.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; + +static CHECKBOOK_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments]; + +impl ConnectorSpecifications for Checkbook { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&CHECKBOOK_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*CHECKBOOK_SUPPORTED_PAYMENT_METHODS) + } + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&CHECKBOOK_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/checkbook/transformers.rs b/crates/hyperswitch_connectors/src/connectors/checkbook/transformers.rs index d9f009f78fe..176fe81f962 100644 --- a/crates/hyperswitch_connectors/src/connectors/checkbook/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/checkbook/transformers.rs @@ -1,102 +1,84 @@ -use common_enums::enums; -use common_utils::types::FloatMajorUnit; +use api_models::webhooks::IncomingWebhookEvent; +use common_utils::{pii, types::FloatMajorUnit}; use hyperswitch_domain_models::{ - payment_method_data::PaymentMethodData, + payment_method_data::{BankTransferData, PaymentMethodData}, router_data::{ConnectorAuthType, RouterData}, - router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, - router_response_types::{PaymentsResponseData, RefundsResponseData}, - types::{PaymentsAuthorizeRouterData, RefundsRouterData}, + router_response_types::PaymentsResponseData, + types::PaymentsAuthorizeRouterData, }; -use hyperswitch_interfaces::errors; +use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ - types::{RefundsResponseRouterData, ResponseRouterData}, - utils::PaymentsAuthorizeRequestData, + types::ResponseRouterData, + utils::{get_unimplemented_payment_method_error_message, RouterData as _}, }; -//TODO: Fill the struct with respective fields -pub struct CheckbookRouterData<T> { - pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. - pub router_data: T, -} - -impl<T> From<(FloatMajorUnit, T)> for CheckbookRouterData<T> { - fn from((amount, item): (FloatMajorUnit, 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)] +#[derive(Debug, Serialize)] pub struct CheckbookPaymentsRequest { + name: Secret<String>, + recipient: pii::Email, amount: FloatMajorUnit, - card: CheckbookCard, + description: String, } -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct CheckbookCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, -} - -impl TryFrom<&CheckbookRouterData<&PaymentsAuthorizeRouterData>> for CheckbookPaymentsRequest { - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<(FloatMajorUnit, &PaymentsAuthorizeRouterData)> for CheckbookPaymentsRequest { + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: &CheckbookRouterData<&PaymentsAuthorizeRouterData>, + (amount, item): (FloatMajorUnit, &PaymentsAuthorizeRouterData), ) -> Result<Self, Self::Error> { - match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(req_card) => { - let card = CheckbookCard { - number: req_card.card_number, - expiry_month: req_card.card_exp_month, - expiry_year: req_card.card_exp_year, - cvc: req_card.card_cvc, - complete: item.router_data.request.is_auto_capture()?, - }; - Ok(Self { - amount: item.amount, - card, - }) - } - _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + match item.request.payment_method_data.clone() { + PaymentMethodData::BankTransfer(bank_transfer_data) => match *bank_transfer_data { + BankTransferData::AchBankTransfer {} => Ok(Self { + name: item.get_billing_full_name()?, + recipient: item.get_billing_email()?, + amount, + description: item.get_description()?, + }), + _ => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Checkbook"), + ) + .into()), + }, + _ => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Checkbook"), + ) + .into()), } } } -//TODO: Fill the struct with respective fields -// Auth Struct pub struct CheckbookAuthType { - pub(super) api_key: Secret<String>, + pub(super) publishable_key: Secret<String>, + pub(super) secret_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for CheckbookAuthType { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<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(), + ConnectorAuthType::BodyKey { key1, api_key } => Ok(Self { + publishable_key: key1.to_owned(), + secret_key: api_key.to_owned(), }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } // PaymentsResponse -//TODO: Append the remaining status flags #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "lowercase")] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CheckbookPaymentStatus { - Succeeded, + Unpaid, + InProcess, + Paid, + Mailed, + Printed, Failed, + Expired, + Void, #[default] Processing, } @@ -104,24 +86,48 @@ pub enum CheckbookPaymentStatus { impl From<CheckbookPaymentStatus> for common_enums::AttemptStatus { fn from(item: CheckbookPaymentStatus) -> Self { match item { - CheckbookPaymentStatus::Succeeded => Self::Charged, - CheckbookPaymentStatus::Failed => Self::Failure, - CheckbookPaymentStatus::Processing => Self::Authorizing, + CheckbookPaymentStatus::Paid + | CheckbookPaymentStatus::Mailed + | CheckbookPaymentStatus::Printed => Self::Charged, + CheckbookPaymentStatus::Failed | CheckbookPaymentStatus::Expired => Self::Failure, + CheckbookPaymentStatus::Unpaid => Self::AuthenticationPending, + CheckbookPaymentStatus::InProcess | CheckbookPaymentStatus::Processing => Self::Pending, + CheckbookPaymentStatus::Void => Self::Voided, + } + } +} + +impl From<CheckbookPaymentStatus> for IncomingWebhookEvent { + fn from(status: CheckbookPaymentStatus) -> Self { + match status { + CheckbookPaymentStatus::Mailed + | CheckbookPaymentStatus::Printed + | CheckbookPaymentStatus::Paid => Self::PaymentIntentSuccess, + CheckbookPaymentStatus::Failed | CheckbookPaymentStatus::Expired => { + Self::PaymentIntentFailure + } + CheckbookPaymentStatus::Unpaid + | CheckbookPaymentStatus::InProcess + | CheckbookPaymentStatus::Processing => Self::PaymentIntentProcessing, + CheckbookPaymentStatus::Void => Self::PaymentIntentCancelled, } } } -//TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct CheckbookPaymentsResponse { - status: CheckbookPaymentStatus, - id: String, + pub status: CheckbookPaymentStatus, + pub id: String, + pub amount: Option<FloatMajorUnit>, + pub description: Option<String>, + pub name: Option<String>, + pub recipient: Option<String>, } impl<F, T> TryFrom<ResponseRouterData<F, CheckbookPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData<F, CheckbookPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { @@ -142,83 +148,6 @@ impl<F, T> TryFrom<ResponseRouterData<F, CheckbookPaymentsResponse, T, PaymentsR } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] -pub struct CheckbookRefundRequest { - pub amount: FloatMajorUnit, -} - -impl<F> TryFrom<&CheckbookRouterData<&RefundsRouterData<F>>> for CheckbookRefundRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &CheckbookRouterData<&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 CheckbookErrorResponse { pub status_code: u16, diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs index 2dd291d16f5..62f4c098992 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -199,6 +199,7 @@ enum RequiredField { DcbMsisdn, DcbClientUid, OrderDetailsProductName, + Description, } impl RequiredField { @@ -868,6 +869,15 @@ impl RequiredField { value: None, }, ), + Self::Description => ( + "description".to_string(), + RequiredFieldInfo { + required_field: "description".to_string(), + display_name: "description".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), } } } @@ -3192,8 +3202,17 @@ fn get_bank_transfer_required_fields() -> HashMap<enums::PaymentMethodType, Conn ( enums::PaymentMethodType::Ach, connectors(vec![( - Connector::Stripe, - fields(vec![], vec![], vec![RequiredField::BillingEmail]), + Connector::Checkbook, + fields( + vec![], + vec![], + vec![ + RequiredField::BillingUserFirstName, + RequiredField::BillingUserLastName, + RequiredField::BillingEmail, + RequiredField::Description, + ], + ), )]), ), ( diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rs index f04edb139f2..72ce6179dc8 100644 --- a/crates/router/src/core/connector_validation.rs +++ b/crates/router/src/core/connector_validation.rs @@ -146,10 +146,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { celero::transformers::CeleroAuthType::try_from(self.auth_type)?; Ok(()) } - // api_enums::Connector::Checkbook => { - // checkbook::transformers::CheckbookAuthType::try_from(self.auth_type)?; - // Ok(()) - // }, + api_enums::Connector::Checkbook => { + checkbook::transformers::CheckbookAuthType::try_from(self.auth_type)?; + Ok(()) + } api_enums::Connector::Checkout => { checkout::transformers::CheckoutAuthType::try_from(self.auth_type)?; Ok(()) diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs index e80d75a7ec1..5e3649461b2 100644 --- a/crates/router/src/types/api/connector_mapping.rs +++ b/crates/router/src/types/api/connector_mapping.rs @@ -157,9 +157,9 @@ impl ConnectorData { enums::Connector::Chargebee => { Ok(ConnectorEnum::Old(Box::new(connector::Chargebee::new()))) } - // enums::Connector::Checkbook => { - // Ok(ConnectorEnum::Old(Box::new(connector::Checkbook))) - // } + enums::Connector::Checkbook => { + Ok(ConnectorEnum::Old(Box::new(connector::Checkbook::new()))) + } enums::Connector::Checkout => { Ok(ConnectorEnum::Old(Box::new(connector::Checkout::new()))) } diff --git a/crates/router/src/types/connector_transformers.rs b/crates/router/src/types/connector_transformers.rs index 47cdf592aa1..673829a06c7 100644 --- a/crates/router/src/types/connector_transformers.rs +++ b/crates/router/src/types/connector_transformers.rs @@ -27,7 +27,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Cashtocode => Self::Cashtocode, api_enums::Connector::Celero => Self::Celero, api_enums::Connector::Chargebee => Self::Chargebee, - // api_enums::Connector::Checkbook => Self::Checkbook, + api_enums::Connector::Checkbook => Self::Checkbook, api_enums::Connector::Checkout => Self::Checkout, api_enums::Connector::Coinbase => Self::Coinbase, api_enums::Connector::Coingate => Self::Coingate, diff --git a/crates/router/tests/connectors/checkbook.rs b/crates/router/tests/connectors/checkbook.rs index b6b4252f852..a312de7fdfd 100644 --- a/crates/router/tests/connectors/checkbook.rs +++ b/crates/router/tests/connectors/checkbook.rs @@ -1,6 +1,8 @@ +use std::str::FromStr; + +use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; -use router::types::{self, api, domain, storage::enums}; -use test_utils::connector_auth; +use router::types::{self, api, storage::enums, Email}; use crate::utils::{self, ConnectorActions}; @@ -12,19 +14,17 @@ impl utils::Connector for CheckbookTest { use router::connector::Checkbook; utils::construct_connector_data_old( Box::new(Checkbook::new()), - types::Connector::DummyConnector1, + types::Connector::Checkbook, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { - utils::to_connector_auth_type( - connector_auth::ConnectorAuthentication::new() - .checkbook - .expect("Missing connector authentication configuration") - .into(), - ) + types::ConnectorAuthType::BodyKey { + key1: Secret::new("dummy_publishable_key".to_string()), + api_key: Secret::new("dummy_secret_key".to_string()), + } } fn get_name(&self) -> String { @@ -35,52 +35,40 @@ impl utils::Connector for CheckbookTest { static CONNECTOR: CheckbookTest = CheckbookTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { - None + Some(utils::PaymentInfo { + address: Some(types::PaymentAddress::new( + None, + None, + Some(Address { + address: Some(AddressDetails { + first_name: Some(Secret::new("John".to_string())), + last_name: Some(Secret::new("Doe".to_string())), + ..Default::default() + }), + phone: None, + email: Some(Email::from_str("abc@gmail.com").unwrap()), + }), + None, + )), + ..Default::default() + }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } -// Cards Positive Tests -// Creates a payment using the manual capture flow (Non 3DS). +// Creates a payment. #[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); + assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); } -// 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). +// Synchronizes a payment. #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR @@ -90,7 +78,7 @@ async fn should_sync_authorized_payment() { let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( - enums::AttemptStatus::Authorized, + enums::AttemptStatus::AuthenticationPending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), @@ -101,320 +89,20 @@ async fn should_sync_authorized_payment() { ) .await .expect("PSync response"); - assert_eq!(response.status, enums::AttemptStatus::Authorized,); + assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); } -// Voids a payment using the manual capture flow (Non 3DS). +// Voids a payment. #[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()) + .authorize_payment(payment_method_details(), get_default_payment_info()) .await - .unwrap(); - assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); - assert_ne!(txn_id, None, "Empty connector transaction id"); - let response = CONNECTOR - .psync_retry_till_status_matches( - enums::AttemptStatus::Charged, - Some(types::PaymentsSyncData { - connector_transaction_id: types::ResponseId::ConnectorTransactionId( - txn_id.unwrap(), - ), - capture_method: Some(enums::CaptureMethod::Automatic), - ..Default::default() - }), - get_default_payment_info(), - ) - .await - .unwrap(); - assert_eq!(response.status, enums::AttemptStatus::Charged,); -} - -// Refunds a payment using the automatic capture flow (Non 3DS). -#[actix_web::test] -async fn should_refund_auto_captured_payment() { - let response = CONNECTOR - .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) - .await - .unwrap(); - assert_eq!( - response.response.unwrap().refund_status, - enums::RefundStatus::Success, - ); -} - -// Partially refunds a payment using the automatic capture flow (Non 3DS). -#[actix_web::test] -async fn should_partially_refund_succeeded_payment() { - let refund_response = CONNECTOR - .make_payment_and_refund( - payment_method_details(), - Some(types::RefundsData { - refund_amount: 50, - ..utils::PaymentRefundType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - assert_eq!( - refund_response.response.unwrap().refund_status, - enums::RefundStatus::Success, - ); -} - -// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). -#[actix_web::test] -async fn should_refund_succeeded_payment_multiple_times() { - CONNECTOR - .make_payment_and_multiple_refund( - payment_method_details(), - Some(types::RefundsData { - refund_amount: 50, - ..utils::PaymentRefundType::default().0 - }), - get_default_payment_info(), - ) - .await; -} - -// Synchronizes a refund using the automatic capture flow (Non 3DS). -#[actix_web::test] -async fn should_sync_refund() { - let refund_response = CONNECTOR - .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) - .await - .unwrap(); - let response = CONNECTOR - .rsync_retry_till_status_matches( - enums::RefundStatus::Success, - refund_response.response.unwrap().connector_refund_id, - None, - get_default_payment_info(), - ) - .await - .unwrap(); - assert_eq!( - response.response.unwrap().refund_status, - enums::RefundStatus::Success, - ); -} - -// Cards Negative scenarios -// Creates a payment with incorrect CVC. -#[actix_web::test] -async fn should_fail_payment_for_incorrect_cvc() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: domain::PaymentMethodData::Card(domain::Card { - card_cvc: Secret::new("12345".to_string()), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - assert_eq!( - response.response.unwrap_err().message, - "Your card's security code is invalid.".to_string(), - ); -} - -// Creates a payment with incorrect expiry month. -#[actix_web::test] -async fn should_fail_payment_for_invalid_exp_month() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: domain::PaymentMethodData::Card(domain::Card { - card_exp_month: Secret::new("20".to_string()), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - assert_eq!( - response.response.unwrap_err().message, - "Your card's expiration month is invalid.".to_string(), - ); -} - -// Creates a payment with incorrect expiry year. -#[actix_web::test] -async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: domain::PaymentMethodData::Card(domain::Card { - card_exp_year: Secret::new("2000".to_string()), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - assert_eq!( - response.response.unwrap_err().message, - "Your card's expiration year is invalid.".to_string(), - ); -} - -// Voids a payment using automatic capture flow (Non 3DS). -#[actix_web::test] -async fn should_fail_void_payment_for_auto_capture() { - let authorize_response = CONNECTOR - .make_payment(payment_method_details(), get_default_payment_info()) - .await - .unwrap(); - assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); - let txn_id = utils::get_connector_transaction_id(authorize_response.response); - assert_ne!(txn_id, None, "Empty connector transaction id"); - let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await - .unwrap(); - assert_eq!( - void_response.response.unwrap_err().message, - "You cannot cancel this PaymentIntent because it has a status of succeeded." - ); -} - -// Captures a payment using invalid connector payment id. -#[actix_web::test] -async fn should_fail_capture_for_invalid_payment() { - let capture_response = CONNECTOR - .capture_payment("123456789".to_string(), None, get_default_payment_info()) - .await - .unwrap(); - assert_eq!( - capture_response.response.unwrap_err().message, - String::from("No such payment_intent: '123456789'") - ); -} - -// Refunds a payment with refund amount higher than payment amount. -#[actix_web::test] -async fn should_fail_for_refund_amount_higher_than_payment_amount() { - let response = CONNECTOR - .make_payment_and_refund( - payment_method_details(), - Some(types::RefundsData { - refund_amount: 150, - ..utils::PaymentRefundType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - assert_eq!( - response.response.unwrap_err().message, - "Refund amount (β‚Ή1.50) is greater than charge amount (β‚Ή1.00)", - ); + .expect("Void payment response"); + assert_eq!(response.status, enums::AttemptStatus::Voided); } - -// Connector dependent test cases goes here - -// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
2025-07-23T10:58:42Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### 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` --> Integrate CHECKBOOK_IO DOCS - https://docs.checkbook.io/docs/concepts/environments/ - https://sandbox.app.checkbook.io/account/dashboard Implement BANKTRANSFER/ACH ** NOTE : payment link will only be sent via email ## How did you test it? ### ACH <details> <summary> PAYMENT CREATION </summary> ```json { "confirm": true, "billing": { "address": { "zip": "560095", "country": "US", "first_name": "akshakaya N", "last_name": "sss", "line1": "Fasdf", "line2": "Fasdf", "city": "Fasdf" }, "email": "nithingowdan77@gmail.com" }, "email": "hyperswitch_sdk_demo_id@gmail.com", "amount": 333, "currency": "USD", "capture_method": "automatic", "payment_method": "bank_transfer", "payment_method_type": "ach", "description": "hellow world", "payment_method_data": { "bank_transfer": { "ach_bank_transfer": {} } } } ``` </summary> </details> <details> <summary>payment response </summary> ```json { "payment_id": "pay_iY6zT9EeXtCC6FWDNJcX", "merchant_id": "merchant_1753248277", "status": "requires_customer_action", "amount": 333, "net_amount": 333, "shipping_cost": null, "amount_capturable": 333, "amount_received": null, "connector": "checkbook", "client_secret": "pay_iY6zT9EeXtCC6FWDNJcX_secret_8UkJCDq38T6itlYKhvfh", "created": "2025-07-23T10:53:11.390Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": null, "email": "hyperswitch_sdk_demo_id@gmail.com", "phone": null, "phone_country_code": null }, "description": "hellow world", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_transfer", "payment_method_data": { "bank_transfer": { "ach": {} }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "Fasdf", "country": "US", "line1": "Fasdf", "line2": "Fasdf", "line3": null, "zip": "560095", "state": null, "first_name": "akshakaya N", "last_name": "sss" }, "phone": null, "email": "nithingowdan77@gmail.com" }, "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": "ach", "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": "1b3e42f27214433ca90a9b791806aa4b", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_0osoWZTgnVYIc9tHhKTu", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_eqxZAe2nz9gsBmMYb1xP", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-23T11:08:11.390Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-07-23T10:53:12.389Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` </details> <details> <summary>Check MAIL FOR link</summary> <img width="1040" height="705" alt="Screenshot 2025-07-23 at 4 22 37β€―PM" src="https://github.com/user-attachments/assets/a04ef1cd-c0c2-4d93-b6dc-464bbcf2474d" /> <img width="1079" height="639" alt="Screenshot 2025-07-23 at 4 26 07β€―PM" src="https://github.com/user-attachments/assets/e5adcdd1-cba4-4f5c-a9a9-0e44a164a220" /> <img width="885" height="441" alt="Screenshot 2025-07-23 at 4 27 28β€―PM" src="https://github.com/user-attachments/assets/f6473fa9-cf4c-4e18-a776-9d941a3c79ef" /> </details> ** NOTE : UNABLE TO VERIFY SUCCESS IN SANDBOX FOR INVOICE ### cypress test attachment <img width="648" height="843" alt="Screenshot 2025-07-24 at 10 16 26β€―AM" src="https://github.com/user-attachments/assets/b0c36856-ca2b-4034-979c-3f44dca3ceba" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.115.0
63cc6ae2815c465f6f7ee975a6413d314b5df141
63cc6ae2815c465f6f7ee975a6413d314b5df141
juspay/hyperswitch
juspay__hyperswitch-8737
Bug: [FEATURE] Hyperswitch <|> UCS Mandate flow integration Add UCS integration for SetupMandate and RepeatPayment (recurring) flows.
diff --git a/Cargo.lock b/Cargo.lock index f65a0fd4be0..d835074cfe2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3363,8 +3363,7 @@ dependencies = [ [[package]] name = "g2h" version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0aece561ff748cdd2a37c8ee938a47bbf9b2c03823b393a332110599b14ee827" +source = "git+https://github.com/NishantJoshi00/g2h?branch=fixing-response-serializing#fd2c856b2c6c88a85d6fe51d95b4d3342b788d31" dependencies = [ "cargo_metadata 0.19.2", "heck 0.5.0", @@ -3526,7 +3525,7 @@ dependencies = [ [[package]] name = "grpc-api-types" version = "0.1.0" -source = "git+https://github.com/juspay/connector-service?rev=4918efedd5ea6c33e4a1600b988b2cf4948bed10#4918efedd5ea6c33e4a1600b988b2cf4948bed10" +source = "git+https://github.com/juspay/connector-service?rev=a9f7cd96693fa034ea69d8e21125ea0f76182fae#a9f7cd96693fa034ea69d8e21125ea0f76182fae" dependencies = [ "axum 0.8.4", "error-stack 0.5.0", @@ -6900,7 +6899,7 @@ dependencies = [ [[package]] name = "rust-grpc-client" version = "0.1.0" -source = "git+https://github.com/juspay/connector-service?rev=4918efedd5ea6c33e4a1600b988b2cf4948bed10#4918efedd5ea6c33e4a1600b988b2cf4948bed10" +source = "git+https://github.com/juspay/connector-service?rev=a9f7cd96693fa034ea69d8e21125ea0f76182fae#a9f7cd96693fa034ea69d8e21125ea0f76182fae" dependencies = [ "grpc-api-types", ] diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index 30ee8ee5a2c..d7fa5897526 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -53,7 +53,7 @@ reqwest = { version = "0.11.27", features = ["rustls-tls"] } http = "0.2.12" url = { version = "2.5.4", features = ["serde"] } quick-xml = { version = "0.31.0", features = ["serialize"] } -unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "4918efedd5ea6c33e4a1600b988b2cf4948bed10", package = "rust-grpc-client" } +unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "a9f7cd96693fa034ea69d8e21125ea0f76182fae", package = "rust-grpc-client" } # First party crates diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs index 5a4a912b798..bac66a3bb50 100644 --- a/crates/external_services/src/grpc_client/unified_connector_service.rs +++ b/crates/external_services/src/grpc_client/unified_connector_service.rs @@ -88,6 +88,14 @@ pub enum UnifiedConnectorServiceError { /// Failed to perform Payment Get from gRPC Server #[error("Failed to perform Payment Get from gRPC Server")] PaymentGetFailure, + + /// Failed to perform Payment Setup Mandate from gRPC Server + #[error("Failed to perform Setup Mandate from gRPC Server")] + PaymentRegisterFailure, + + /// Failed to perform Payment Repeat Payment from gRPC Server + #[error("Failed to perform Repeat Payment from gRPC Server")] + PaymentRepeatEverythingFailure, } /// Result type for Dynamic Routing @@ -160,7 +168,10 @@ impl UnifiedConnectorServiceClient { .await; match connect_result { - Ok(Ok(client)) => Some(Self { client }), + Ok(Ok(client)) => { + logger::info!("Successfully connected to Unified Connector Service"); + Some(Self { client }) + } Ok(Err(err)) => { logger::error!(error = ?err, "Failed to connect to Unified Connector Service"); None @@ -217,6 +228,51 @@ impl UnifiedConnectorServiceClient { .change_context(UnifiedConnectorServiceError::PaymentGetFailure) .inspect_err(|error| logger::error!(?error)) } + + /// Performs Payment Setup Mandate + pub async fn payment_setup_mandate( + &self, + payment_register_request: payments_grpc::PaymentServiceRegisterRequest, + connector_auth_metadata: ConnectorAuthMetadata, + grpc_headers: GrpcHeaders, + ) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PaymentServiceRegisterResponse>> + { + let mut request = tonic::Request::new(payment_register_request); + + let metadata = + build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?; + *request.metadata_mut() = metadata; + + self.client + .clone() + .register(request) + .await + .change_context(UnifiedConnectorServiceError::PaymentRegisterFailure) + .inspect_err(|error| logger::error!(?error)) + } + + /// Performs Payment repeat (MIT - Merchant Initiated Transaction). + pub async fn payment_repeat( + &self, + payment_repeat_request: payments_grpc::PaymentServiceRepeatEverythingRequest, + connector_auth_metadata: ConnectorAuthMetadata, + grpc_headers: GrpcHeaders, + ) -> UnifiedConnectorServiceResult< + tonic::Response<payments_grpc::PaymentServiceRepeatEverythingResponse>, + > { + let mut request = tonic::Request::new(payment_repeat_request); + + let metadata = + build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?; + *request.metadata_mut() = metadata; + + self.client + .clone() + .repeat_everything(request) + .await + .change_context(UnifiedConnectorServiceError::PaymentRepeatEverythingFailure) + .inspect_err(|error| logger::error!(?error)) + } } /// Build the gRPC Headers for Unified Connector Service Request diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 8b80d22dc2a..9399c0d3b3a 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -88,7 +88,7 @@ reqwest = { version = "0.11.27", features = ["json", "rustls-tls", "gzip", "mult ring = "0.17.14" rust_decimal = { version = "1.37.1", features = ["serde-with-float", "serde-with-str"] } rust-i18n = { git = "https://github.com/kashif-m/rust-i18n", rev = "f2d8096aaaff7a87a847c35a5394c269f75e077a" } -unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "4918efedd5ea6c33e4a1600b988b2cf4948bed10", package = "rust-grpc-client" } +unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "a9f7cd96693fa034ea69d8e21125ea0f76182fae", package = "rust-grpc-client" } rustc-hash = "1.1.0" rustls = "0.22" rustls-pemfile = "2" diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 21215ea7235..e077362cc1f 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -20,6 +20,7 @@ use crate::{ unified_connector_service::{ build_unified_connector_service_auth_metadata, handle_unified_connector_service_response_for_payment_authorize, + handle_unified_connector_service_response_for_payment_repeat, }, }, logger, @@ -515,51 +516,23 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, merchant_context: &domain::MerchantContext, ) -> RouterResult<()> { - let client = state - .grpc_client - .unified_connector_service_client - .clone() - .ok_or(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to fetch Unified Connector Service client")?; - - let payment_authorize_request = - payments_grpc::PaymentServiceAuthorizeRequest::foreign_try_from(self) - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to construct Payment Authorize Request")?; - - let connector_auth_metadata = build_unified_connector_service_auth_metadata( - merchant_connector_account, - merchant_context, - ) - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to construct request metadata")?; - - let response = client - .payment_authorize( - payment_authorize_request, - connector_auth_metadata, - state.get_grpc_headers(), + if self.request.mandate_id.is_some() { + call_unified_connector_service_repeat_payment( + self, + state, + merchant_connector_account, + merchant_context, ) .await - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to authorize payment")?; - - let payment_authorize_response = response.into_inner(); - - let (status, router_data_response) = - handle_unified_connector_service_response_for_payment_authorize( - payment_authorize_response.clone(), + } else { + call_unified_connector_service_authorize( + self, + state, + merchant_connector_account, + merchant_context, ) - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to deserialize UCS response")?; - - self.status = status; - self.response = router_data_response; - self.raw_connector_response = payment_authorize_response - .raw_connector_response - .map(Secret::new); - - Ok(()) + .await + } } } @@ -846,3 +819,115 @@ async fn process_capture_flow( router_data.response = Ok(updated_response); Ok(router_data) } + +async fn call_unified_connector_service_authorize( + router_data: &mut types::RouterData< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + state: &SessionState, + #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType, + #[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, + merchant_context: &domain::MerchantContext, +) -> RouterResult<()> { + let client = state + .grpc_client + .unified_connector_service_client + .clone() + .ok_or(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch Unified Connector Service client")?; + + let payment_authorize_request = + payments_grpc::PaymentServiceAuthorizeRequest::foreign_try_from(router_data) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct Payment Authorize Request")?; + + let connector_auth_metadata = + build_unified_connector_service_auth_metadata(merchant_connector_account, merchant_context) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct request metadata")?; + + let response = client + .payment_authorize( + payment_authorize_request, + connector_auth_metadata, + state.get_grpc_headers(), + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to authorize payment")?; + + let payment_authorize_response = response.into_inner(); + + let (status, router_data_response) = + handle_unified_connector_service_response_for_payment_authorize( + payment_authorize_response.clone(), + ) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize UCS response")?; + + router_data.status = status; + router_data.response = router_data_response; + router_data.raw_connector_response = payment_authorize_response + .raw_connector_response + .map(Secret::new); + + Ok(()) +} + +async fn call_unified_connector_service_repeat_payment( + router_data: &mut types::RouterData< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + state: &SessionState, + #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType, + #[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, + merchant_context: &domain::MerchantContext, +) -> RouterResult<()> { + let client = state + .grpc_client + .unified_connector_service_client + .clone() + .ok_or(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch Unified Connector Service client")?; + + let payment_repeat_request = + payments_grpc::PaymentServiceRepeatEverythingRequest::foreign_try_from(router_data) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct Payment Authorize Request")?; + + let connector_auth_metadata = + build_unified_connector_service_auth_metadata(merchant_connector_account, merchant_context) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct request metadata")?; + + let response = client + .payment_repeat( + payment_repeat_request, + connector_auth_metadata, + state.get_grpc_headers(), + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to authorize payment")?; + + let payment_repeat_response = response.into_inner(); + + let (status, router_data_response) = + handle_unified_connector_service_response_for_payment_repeat( + payment_repeat_response.clone(), + ) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize UCS response")?; + + router_data.status = status; + router_data.response = router_data_response; + router_data.raw_connector_response = payment_repeat_response + .raw_connector_response + .map(Secret::new); + + Ok(()) +} diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index eb43bff64fd..6204d521680 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -1,19 +1,25 @@ use async_trait::async_trait; use common_types::payments as common_payments_types; +use error_stack::ResultExt; use router_env::logger; +use unified_connector_service_client::payments as payments_grpc; use super::{ConstructFlowSpecificData, Feature}; use crate::{ core::{ - errors::{ConnectorErrorExt, RouterResult}, + errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult}, mandate, payments::{ self, access_token, customers, helpers, tokenization, transformers, PaymentData, }, + unified_connector_service::{ + build_unified_connector_service_auth_metadata, + handle_unified_connector_service_response_for_payment_register, + }, }, routes::SessionState, services, - types::{self, api, domain}, + types::{self, api, domain, transformers::ForeignTryFrom}, }; #[cfg(feature = "v1")] @@ -200,6 +206,62 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup _ => Ok((None, true)), } } + + async fn call_unified_connector_service<'a>( + &mut self, + state: &SessionState, + #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType, + #[cfg(feature = "v2")] + merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, + merchant_context: &domain::MerchantContext, + ) -> RouterResult<()> { + let client = state + .grpc_client + .unified_connector_service_client + .clone() + .ok_or(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch Unified Connector Service client")?; + + let payment_register_request = + payments_grpc::PaymentServiceRegisterRequest::foreign_try_from(self) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct Payment Setup Mandate Request")?; + + let connector_auth_metadata = build_unified_connector_service_auth_metadata( + merchant_connector_account, + merchant_context, + ) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct request metadata")?; + + let response = client + .payment_setup_mandate( + payment_register_request, + connector_auth_metadata, + state.get_grpc_headers(), + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to Setup Mandate payment")?; + + let payment_register_response = response.into_inner(); + + let (status, router_data_response) = + handle_unified_connector_service_response_for_payment_register( + payment_register_response.clone(), + ) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize UCS response")?; + + self.status = status; + self.response = router_data_response; + // UCS does not return raw connector response for setup mandate right now + // self.raw_connector_response = payment_register_response + // .raw_connector_response + // .map(Secret::new); + + Ok(()) + } } impl mandate::MandateBehaviour for types::SetupMandateRequestData { diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs index 14836ff20c6..badd424abcf 100644 --- a/crates/router/src/core/unified_connector_service.rs +++ b/crates/router/src/core/unified_connector_service.rs @@ -10,7 +10,7 @@ use hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAcco use hyperswitch_domain_models::{ merchant_context::MerchantContext, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, - router_response_types::{PaymentsResponseData, RedirectForm}, + router_response_types::PaymentsResponseData, }; use masking::{ExposeInterface, PeekInterface, Secret}; use unified_connector_service_client::payments::{ @@ -226,85 +226,8 @@ pub fn handle_unified_connector_service_response_for_payment_authorize( > { let status = AttemptStatus::foreign_try_from(response.status())?; - let connector_response_reference_id = - response.response_ref_id.as_ref().and_then(|identifier| { - identifier - .id_type - .clone() - .and_then(|id_type| match id_type { - payments_grpc::identifier::IdType::Id(id) => Some(id), - payments_grpc::identifier::IdType::EncodedData(encoded_data) => { - Some(encoded_data) - } - payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, - }) - }); - - let transaction_id = response.transaction_id.as_ref().and_then(|id| { - id.id_type.clone().and_then(|id_type| match id_type { - payments_grpc::identifier::IdType::Id(id) => Some(id), - payments_grpc::identifier::IdType::EncodedData(encoded_data) => Some(encoded_data), - payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, - }) - }); - - let router_data_response = match status { - AttemptStatus::Charged | - AttemptStatus::Authorized | - AttemptStatus::AuthenticationPending | - AttemptStatus::DeviceDataCollectionPending | - AttemptStatus::Started | - AttemptStatus::AuthenticationSuccessful | - AttemptStatus::Authorizing | - AttemptStatus::ConfirmationAwaited | - AttemptStatus::Pending => Ok(PaymentsResponseData::TransactionResponse { - resource_id: match transaction_id.as_ref() { - Some(transaction_id) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(transaction_id.clone()), - None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId, - }, - redirection_data: Box::new( - response - .redirection_data - .clone() - .map(RedirectForm::foreign_try_from) - .transpose()? - ), - mandate_reference: Box::new(None), - connector_metadata: None, - network_txn_id: response.network_txn_id.clone(), - connector_response_reference_id, - incremental_authorization_allowed: response.incremental_authorization_allowed, - charges: None, - }), - AttemptStatus::AuthenticationFailed - | AttemptStatus::AuthorizationFailed - | AttemptStatus::Unresolved - | AttemptStatus::Failure => Err(ErrorResponse { - code: response.error_code().to_owned(), - message: response.error_message().to_owned(), - reason: Some(response.error_message().to_owned()), - status_code: 500, - attempt_status: Some(status), - connector_transaction_id: connector_response_reference_id, - network_decline_code: None, - network_advice_code: None, - network_error_message: None, - }), - AttemptStatus::RouterDeclined | - AttemptStatus::CodInitiated | - AttemptStatus::Voided | - AttemptStatus::VoidInitiated | - AttemptStatus::CaptureInitiated | - AttemptStatus::VoidFailed | - AttemptStatus::AutoRefunded | - AttemptStatus::PartialCharged | - AttemptStatus::PartialChargedAndChargeable | - AttemptStatus::PaymentMethodAwaited | - AttemptStatus::CaptureFailed | - AttemptStatus::IntegrityFailure => return Err(UnifiedConnectorServiceError::NotImplemented(format!( - "AttemptStatus {status:?} is not implemented for Unified Connector Service" - )).into()), - }; + let router_data_response = + Result::<PaymentsResponseData, ErrorResponse>::foreign_try_from(response)?; Ok((status, router_data_response)) } @@ -317,75 +240,36 @@ pub fn handle_unified_connector_service_response_for_payment_get( > { let status = AttemptStatus::foreign_try_from(response.status())?; - let connector_response_reference_id = - response.response_ref_id.as_ref().and_then(|identifier| { - identifier - .id_type - .clone() - .and_then(|id_type| match id_type { - payments_grpc::identifier::IdType::Id(id) => Some(id), - payments_grpc::identifier::IdType::EncodedData(encoded_data) => { - Some(encoded_data) - } - payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, - }) - }); + let router_data_response = + Result::<PaymentsResponseData, ErrorResponse>::foreign_try_from(response)?; - let router_data_response = match status { - AttemptStatus::Charged | - AttemptStatus::Authorized | - AttemptStatus::AuthenticationPending | - AttemptStatus::DeviceDataCollectionPending | - AttemptStatus::Started | - AttemptStatus::AuthenticationSuccessful | - AttemptStatus::Authorizing | - AttemptStatus::ConfirmationAwaited | - AttemptStatus::Pending => Ok( - PaymentsResponseData::TransactionResponse { - resource_id: match connector_response_reference_id.as_ref() { - Some(connector_response_reference_id) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(connector_response_reference_id.clone()), - None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId, - }, - redirection_data: Box::new( - None - ), - mandate_reference: Box::new(None), - connector_metadata: None, - network_txn_id: response.network_txn_id.clone(), - connector_response_reference_id, - incremental_authorization_allowed: None, - charges: None, - } - ), - AttemptStatus::AuthenticationFailed - | AttemptStatus::AuthorizationFailed - | AttemptStatus::Failure => Err(ErrorResponse { - code: response.error_code().to_owned(), - message: response.error_message().to_owned(), - reason: Some(response.error_message().to_owned()), - status_code: 500, - attempt_status: Some(status), - connector_transaction_id: connector_response_reference_id, - network_decline_code: None, - network_advice_code: None, - network_error_message: None, - }), - AttemptStatus::RouterDeclined | - AttemptStatus::CodInitiated | - AttemptStatus::Voided | - AttemptStatus::VoidInitiated | - AttemptStatus::CaptureInitiated | - AttemptStatus::VoidFailed | - AttemptStatus::AutoRefunded | - AttemptStatus::PartialCharged | - AttemptStatus::PartialChargedAndChargeable | - AttemptStatus::Unresolved | - AttemptStatus::PaymentMethodAwaited | - AttemptStatus::CaptureFailed | - AttemptStatus::IntegrityFailure => return Err(UnifiedConnectorServiceError::NotImplemented(format!( - "AttemptStatus {status:?} is not implemented for Unified Connector Service" - )).into()), - }; + Ok((status, router_data_response)) +} + +pub fn handle_unified_connector_service_response_for_payment_register( + response: payments_grpc::PaymentServiceRegisterResponse, +) -> CustomResult< + (AttemptStatus, Result<PaymentsResponseData, ErrorResponse>), + UnifiedConnectorServiceError, +> { + let status = AttemptStatus::foreign_try_from(response.status())?; + + let router_data_response = + Result::<PaymentsResponseData, ErrorResponse>::foreign_try_from(response)?; + + Ok((status, router_data_response)) +} + +pub fn handle_unified_connector_service_response_for_payment_repeat( + response: payments_grpc::PaymentServiceRepeatEverythingResponse, +) -> CustomResult< + (AttemptStatus, Result<PaymentsResponseData, ErrorResponse>), + UnifiedConnectorServiceError, +> { + let status = AttemptStatus::foreign_try_from(response.status())?; + + let router_data_response = + Result::<PaymentsResponseData, ErrorResponse>::foreign_try_from(response)?; Ok((status, router_data_response)) } diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs index e937a7e7d2d..719b82ffd12 100644 --- a/crates/router/src/core/unified_connector_service/transformers.rs +++ b/crates/router/src/core/unified_connector_service/transformers.rs @@ -6,9 +6,11 @@ use diesel_models::enums as storage_enums; use error_stack::ResultExt; use external_services::grpc_client::unified_connector_service::UnifiedConnectorServiceError; use hyperswitch_domain_models::{ - router_data::RouterData, - router_flow_types::payments::{Authorize, PSync}, - router_request_types::{AuthenticationData, PaymentsAuthorizeData, PaymentsSyncData}, + router_data::{ErrorResponse, RouterData}, + router_flow_types::payments::{Authorize, PSync, SetupMandate}, + router_request_types::{ + AuthenticationData, PaymentsAuthorizeData, PaymentsSyncData, SetupMandateRequestData, + }, router_response_types::{PaymentsResponseData, RedirectForm}, }; use masking::{ExposeInterface, PeekInterface}; @@ -167,6 +169,443 @@ impl ForeignTryFrom<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsRespon } } +impl ForeignTryFrom<&RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>> + for payments_grpc::PaymentServiceRegisterRequest +{ + type Error = error_stack::Report<UnifiedConnectorServiceError>; + + fn foreign_try_from( + router_data: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let currency = payments_grpc::Currency::foreign_try_from(router_data.request.currency)?; + let payment_method = router_data + .request + .payment_method_type + .map(|payment_method_type| { + build_unified_connector_service_payment_method( + router_data.request.payment_method_data.clone(), + payment_method_type, + ) + }) + .transpose()?; + let address = payments_grpc::PaymentAddress::foreign_try_from(router_data.address.clone())?; + let auth_type = payments_grpc::AuthenticationType::foreign_try_from(router_data.auth_type)?; + let browser_info = router_data + .request + .browser_info + .clone() + .map(payments_grpc::BrowserInformation::foreign_try_from) + .transpose()?; + let setup_future_usage = router_data + .request + .setup_future_usage + .map(payments_grpc::FutureUsage::foreign_try_from) + .transpose()?; + let customer_acceptance = router_data + .request + .customer_acceptance + .clone() + .map(payments_grpc::CustomerAcceptance::foreign_try_from) + .transpose()?; + + Ok(Self { + request_ref_id: Some(Identifier { + id_type: Some(payments_grpc::identifier::IdType::Id( + router_data.connector_request_reference_id.clone(), + )), + }), + currency: currency.into(), + payment_method, + minor_amount: router_data.request.amount, + email: router_data + .request + .email + .clone() + .map(|e| e.expose().expose()), + customer_name: router_data + .request + .customer_name + .clone() + .map(|customer_name| customer_name.peek().to_owned()), + connector_customer_id: router_data + .request + .customer_id + .as_ref() + .map(|id| id.get_string_repr().to_string()), + address: Some(address), + auth_type: auth_type.into(), + enrolled_for_3ds: false, + authentication_data: None, + metadata: router_data + .request + .metadata + .as_ref() + .map(|secret| secret.peek()) + .and_then(|val| val.as_object()) //secret + .map(|map| { + map.iter() + .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string()))) + .collect::<HashMap<String, String>>() + }) + .unwrap_or_default(), + return_url: router_data.request.router_return_url.clone(), + webhook_url: router_data.request.webhook_url.clone(), + complete_authorize_url: router_data.request.complete_authorize_url.clone(), + access_token: None, + session_token: None, + order_tax_amount: None, + order_category: None, + merchant_order_reference_id: None, + shipping_cost: router_data + .request + .shipping_cost + .map(|cost| cost.get_amount_as_i64()), + setup_future_usage: setup_future_usage.map(|s| s.into()), + off_session: router_data.request.off_session, + request_incremental_authorization: router_data + .request + .request_incremental_authorization, + request_extended_authorization: None, + customer_acceptance, + browser_info, + payment_experience: None, + }) + } +} + +impl ForeignTryFrom<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>> + for payments_grpc::PaymentServiceRepeatEverythingRequest +{ + type Error = error_stack::Report<UnifiedConnectorServiceError>; + + fn foreign_try_from( + router_data: &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let currency = payments_grpc::Currency::foreign_try_from(router_data.request.currency)?; + + let mandate_reference = match &router_data.request.mandate_id { + Some(mandate) => match &mandate.mandate_reference_id { + Some(api_models::payments::MandateReferenceId::ConnectorMandateId( + connector_mandate_id, + )) => Some(payments_grpc::MandateReference { + mandate_id: connector_mandate_id.get_connector_mandate_id(), + }), + _ => { + return Err(UnifiedConnectorServiceError::MissingRequiredField { + field_name: "connector_mandate_id", + } + .into()) + } + }, + None => { + return Err(UnifiedConnectorServiceError::MissingRequiredField { + field_name: "connector_mandate_id", + } + .into()) + } + }; + + Ok(Self { + request_ref_id: Some(Identifier { + id_type: Some(payments_grpc::identifier::IdType::Id( + router_data.connector_request_reference_id.clone(), + )), + }), + mandate_reference, + amount: router_data.request.amount, + currency: currency.into(), + minor_amount: router_data.request.amount, + merchant_order_reference_id: router_data.request.merchant_order_reference_id.clone(), + metadata: router_data + .request + .metadata + .as_ref() + .and_then(|val| val.as_object()) + .map(|map| { + map.iter() + .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string()))) + .collect::<HashMap<String, String>>() + }) + .unwrap_or_default(), + webhook_url: router_data.request.webhook_url.clone(), + }) + } +} + +impl ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse> + for Result<PaymentsResponseData, ErrorResponse> +{ + type Error = error_stack::Report<UnifiedConnectorServiceError>; + + fn foreign_try_from( + response: payments_grpc::PaymentServiceAuthorizeResponse, + ) -> Result<Self, Self::Error> { + let status = AttemptStatus::foreign_try_from(response.status())?; + + let connector_response_reference_id = + response.response_ref_id.as_ref().and_then(|identifier| { + identifier + .id_type + .clone() + .and_then(|id_type| match id_type { + payments_grpc::identifier::IdType::Id(id) => Some(id), + payments_grpc::identifier::IdType::EncodedData(encoded_data) => { + Some(encoded_data) + } + payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, + }) + }); + + let transaction_id = response.transaction_id.as_ref().and_then(|id| { + id.id_type.clone().and_then(|id_type| match id_type { + payments_grpc::identifier::IdType::Id(id) => Some(id), + payments_grpc::identifier::IdType::EncodedData(encoded_data) => Some(encoded_data), + payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, + }) + }); + + let response = if response.error_code.is_some() { + Err(ErrorResponse { + code: response.error_code().to_owned(), + message: response.error_message().to_owned(), + reason: Some(response.error_message().to_owned()), + status_code: 500, //TODO: To be handled once UCS sends proper status codes + attempt_status: Some(status), + connector_transaction_id: connector_response_reference_id, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + }) + } else { + Ok(PaymentsResponseData::TransactionResponse { + resource_id: match transaction_id.as_ref() { + Some(transaction_id) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(transaction_id.clone()), + None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId, + }, + redirection_data: Box::new( + response + .redirection_data + .clone() + .map(RedirectForm::foreign_try_from) + .transpose()? + ), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: response.network_txn_id.clone(), + connector_response_reference_id, + incremental_authorization_allowed: response.incremental_authorization_allowed, + charges: None, + }) + }; + + Ok(response) + } +} + +impl ForeignTryFrom<payments_grpc::PaymentServiceGetResponse> + for Result<PaymentsResponseData, ErrorResponse> +{ + type Error = error_stack::Report<UnifiedConnectorServiceError>; + + fn foreign_try_from( + response: payments_grpc::PaymentServiceGetResponse, + ) -> Result<Self, Self::Error> { + let status = AttemptStatus::foreign_try_from(response.status())?; + + let connector_response_reference_id = + response.response_ref_id.as_ref().and_then(|identifier| { + identifier + .id_type + .clone() + .and_then(|id_type| match id_type { + payments_grpc::identifier::IdType::Id(id) => Some(id), + payments_grpc::identifier::IdType::EncodedData(encoded_data) => { + Some(encoded_data) + } + payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, + }) + }); + + let response = if response.error_code.is_some() { + Err(ErrorResponse { + code: response.error_code().to_owned(), + message: response.error_message().to_owned(), + reason: Some(response.error_message().to_owned()), + status_code: 500, //TODO: To be handled once UCS sends proper status codes + attempt_status: Some(status), + connector_transaction_id: connector_response_reference_id, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + }) + } else { + Ok(PaymentsResponseData::TransactionResponse { + resource_id: match connector_response_reference_id.as_ref() { + Some(connector_response_reference_id) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(connector_response_reference_id.clone()), + None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId, + }, + redirection_data: Box::new( + None + ), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: response.network_txn_id.clone(), + connector_response_reference_id, + incremental_authorization_allowed: None, + charges: None, + } + ) + }; + + Ok(response) + } +} + +impl ForeignTryFrom<payments_grpc::PaymentServiceRegisterResponse> + for Result<PaymentsResponseData, ErrorResponse> +{ + type Error = error_stack::Report<UnifiedConnectorServiceError>; + + fn foreign_try_from( + response: payments_grpc::PaymentServiceRegisterResponse, + ) -> Result<Self, Self::Error> { + let status = AttemptStatus::foreign_try_from(response.status())?; + + let connector_response_reference_id = + response.response_ref_id.as_ref().and_then(|identifier| { + identifier + .id_type + .clone() + .and_then(|id_type| match id_type { + payments_grpc::identifier::IdType::Id(id) => Some(id), + payments_grpc::identifier::IdType::EncodedData(encoded_data) => { + Some(encoded_data) + } + payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, + }) + }); + + let response = if response.error_code.is_some() { + Err(ErrorResponse { + code: response.error_code().to_owned(), + message: response.error_message().to_owned(), + reason: Some(response.error_message().to_owned()), + status_code: 500, //TODO: To be handled once UCS sends proper status codes + attempt_status: Some(status), + connector_transaction_id: connector_response_reference_id, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + }) + } else { + Ok(PaymentsResponseData::TransactionResponse { + resource_id: response.registration_id.as_ref().and_then(|identifier| { + identifier + .id_type + .clone() + .and_then(|id_type| match id_type { + payments_grpc::identifier::IdType::Id(id) => Some( + hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(id), + ), + payments_grpc::identifier::IdType::EncodedData(encoded_data) => Some( + hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(encoded_data), + ), + payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, + }) + }).unwrap_or(hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId), + redirection_data: Box::new( + response + .redirection_data + .clone() + .map(RedirectForm::foreign_try_from) + .transpose()? + ), + mandate_reference: Box::new( + response.mandate_reference.map(|grpc_mandate| { + hyperswitch_domain_models::router_response_types::MandateReference { + connector_mandate_id: grpc_mandate.mandate_id, + payment_method_id: None, + mandate_metadata: None, + connector_mandate_request_reference_id: None, + } + }) + ), + connector_metadata: None, + network_txn_id: response.network_txn_id, + connector_response_reference_id, + incremental_authorization_allowed: response.incremental_authorization_allowed, + charges: None, + }) + }; + + Ok(response) + } +} + +impl ForeignTryFrom<payments_grpc::PaymentServiceRepeatEverythingResponse> + for Result<PaymentsResponseData, ErrorResponse> +{ + type Error = error_stack::Report<UnifiedConnectorServiceError>; + + fn foreign_try_from( + response: payments_grpc::PaymentServiceRepeatEverythingResponse, + ) -> Result<Self, Self::Error> { + let status = AttemptStatus::foreign_try_from(response.status())?; + + let connector_response_reference_id = + response.response_ref_id.as_ref().and_then(|identifier| { + identifier + .id_type + .clone() + .and_then(|id_type| match id_type { + payments_grpc::identifier::IdType::Id(id) => Some(id), + payments_grpc::identifier::IdType::EncodedData(encoded_data) => { + Some(encoded_data) + } + payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, + }) + }); + + let transaction_id = response.transaction_id.as_ref().and_then(|id| { + id.id_type.clone().and_then(|id_type| match id_type { + payments_grpc::identifier::IdType::Id(id) => Some(id), + payments_grpc::identifier::IdType::EncodedData(encoded_data) => Some(encoded_data), + payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, + }) + }); + + let response = if response.error_code.is_some() { + Err(ErrorResponse { + code: response.error_code().to_owned(), + message: response.error_message().to_owned(), + reason: Some(response.error_message().to_owned()), + status_code: 500, //TODO: To be handled once UCS sends proper status codes + attempt_status: Some(status), + connector_transaction_id: transaction_id, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + }) + } else { + Ok(PaymentsResponseData::TransactionResponse { + resource_id: match transaction_id.as_ref() { + Some(transaction_id) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(transaction_id.clone()), + None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId, + }, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: response.network_txn_id.clone(), + connector_response_reference_id, + incremental_authorization_allowed: None, + charges: None, + }) + }; + + Ok(response) + } +} + impl ForeignTryFrom<common_enums::Currency> for payments_grpc::Currency { type Error = error_stack::Report<UnifiedConnectorServiceError>; @@ -480,3 +919,48 @@ impl ForeignTryFrom<payments_grpc::HttpMethod> for Method { } } } + +impl ForeignTryFrom<storage_enums::FutureUsage> for payments_grpc::FutureUsage { + type Error = error_stack::Report<UnifiedConnectorServiceError>; + + fn foreign_try_from(future_usage: storage_enums::FutureUsage) -> Result<Self, Self::Error> { + match future_usage { + storage_enums::FutureUsage::OnSession => Ok(Self::OnSession), + storage_enums::FutureUsage::OffSession => Ok(Self::OffSession), + } + } +} + +impl ForeignTryFrom<common_types::payments::CustomerAcceptance> + for payments_grpc::CustomerAcceptance +{ + type Error = error_stack::Report<UnifiedConnectorServiceError>; + + fn foreign_try_from( + customer_acceptance: common_types::payments::CustomerAcceptance, + ) -> Result<Self, Self::Error> { + let acceptance_type = match customer_acceptance.acceptance_type { + common_types::payments::AcceptanceType::Online => payments_grpc::AcceptanceType::Online, + common_types::payments::AcceptanceType::Offline => { + payments_grpc::AcceptanceType::Offline + } + }; + + let online_mandate_details = + customer_acceptance + .online + .map(|online| payments_grpc::OnlineMandate { + ip_address: online.ip_address.map(|ip| ip.peek().to_string()), + user_agent: online.user_agent, + }); + + Ok(Self { + acceptance_type: acceptance_type.into(), + accepted_at: customer_acceptance + .accepted_at + .map(|dt| dt.assume_utc().unix_timestamp()) + .unwrap_or_default(), + online_mandate_details, + }) + } +}
2025-07-23T14:43:28Z
## 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 implements UCS(Unified Connector Service) Integration for SetupMandate and RepeatEverything (recurring payment) flows. - Updated rust-grpc-client dependency to main branch - Added log for Successful UCS connection ### 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 Intent for Zero mandate ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: _' \ --data ' { "amount": 0, "confirm": false, "currency": "USD", "customer_id": "Customer123", "setup_future_usage": "off_session" }' ``` Confirm CIT (Authorisedotnet via UCS) ``` curl --location 'http://localhost:8080/payments/pay_YbaKZHAfIRvsnGpeuOcH/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: _' \ --data-raw '{ "confirm": true, "customer_id": "Customer123", "payment_type": "setup_mandate", "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" } }, "payment_method": "card", "payment_method_type": "credit", "email": "test@novalnet.de", "payment_method_data": { "card": { "card_number": "4349940199004549", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe", "card_cvc": "396", "card_network": "VISA" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IT", "first_name": "joseph", "last_name": "Doe" }, "email": "test@novalnet.de", "phone": { "number": "8056594427", "country_code": "+91" } } }, "all_keys_required": true }' ``` Response ``` { "payment_id": "pay_2d7OcbcSgKUrkt4ETxYP", "merchant_id": "merchant_1753280085", "status": "succeeded", "amount": 0, "net_amount": 0, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_2d7OcbcSgKUrkt4ETxYP_secret_fLFQbtHQWQGORcgUtr4l", "created": "2025-07-23T14:57:40.169Z", "currency": "USD", "customer_id": "Customer123", "customer": { "id": "Customer123", "name": null, "email": "test@novalnet.de", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "4549", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "434994", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": { "address": { "city": "San Fransico", "country": "IT", "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": "test@novalnet.de" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "test@novalnet.de", "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": "523966074", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_0UBAnCbAThEENJj9KfZ0", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_XVTNsN4D9kHGw3DxkEP0", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-23T15:12:40.168Z", "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_tSOU7aOBhgKLBE92628X", "payment_method_status": "active", "updated": "2025-07-23T14:58:20.071Z", "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": "523966074-536113445", "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` Card recurring payment (Authorizedotnet via UCS) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_dAANSmNFGJ0ppE3KkF0NaFYdWmHDQReivo4zXuzWPPvMae7TSIRPRus6hDyNDTGt' \ --data '{ "amount": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "Customer123", "off_session": true, "recurring_details": { "type": "payment_method_id", "data": "pm_Ca7e4nuk9S8z1S7ksaF6" } }' ``` Response ``` { "payment_id": "pay_YbaKZHAfIRvsnGpeuOcH", "merchant_id": "merchant_1753280085", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "authorizedotnet", "client_secret": "pay_YbaKZHAfIRvsnGpeuOcH_secret_hTmFPsa4amP6XdXG6g9d", "created": "2025-07-23T14:58:39.835Z", "currency": "USD", "customer_id": "Customer123", "customer": { "id": "Customer123", "name": null, "email": "test@novalnet.de", "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": "card", "payment_method_data": { "card": { "last4": "4549", "card_type": null, "card_network": "Visa", "card_issuer": null, "card_issuing_country": null, "card_isin": "434994", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "test@novalnet.de", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "Customer123", "created_at": 1753282719, "expires": 1753286319, "secret": "epk_fd17c36b38584f0488578d1335542cbe" }, "manual_retry_allowed": false, "connector_transaction_id": "80042797687", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_0UBAnCbAThEENJj9KfZ0", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_XVTNsN4D9kHGw3DxkEP0", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-23T15:13:39.835Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_Ca7e4nuk9S8z1S7ksaF6", "payment_method_status": "active", "updated": "2025-07-23T14:58:40.816Z", "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": "523965707-536113051", "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.115.0
6214aca5f0f5c617a68f65ef5bcfd700060acccf
6214aca5f0f5c617a68f65ef5bcfd700060acccf
juspay/hyperswitch
juspay__hyperswitch-8736
Bug: [CHORE] Bump Cypress Dependencies Current versions are outdated. <img width="469" height="327" alt="Image" src="https://github.com/user-attachments/assets/507dfa9e-754c-4cb5-9f86-41558769f513" />
2025-07-23T13:41:24Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [x] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR bumps Cypress and its dependencies to its latest versions. ### 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 #8736 ## 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 --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.115.0
20b37bdb7a25ec053e7671332d4837a0ad743983
20b37bdb7a25ec053e7671332d4837a0ad743983
juspay/hyperswitch
juspay__hyperswitch-8724
Bug: [REFACTOR] use REQUEST_TIME_OUT for outgoing webhooks instead of hardcoded 5-second timeout **Problem Statement** The current outgoing webhook timeout is hardcoded to 5 seconds, which is too restrictive and causes delivery failures for legacy systems which might take over 5 seconds to respond back. We should use the existing `REQUEST_TIME_OUT` constant (30s) for consistency with other external API calls. **Current Implementation** `const OUTGOING_WEBHOOK_TIMEOUT_SECS: u64 = 5;` **Proposed Solution** Remove `OUTGOING_WEBHOOK_TIMEOUT_SECS` and use the existing `REQUEST_TIME_OUT` constant (30s) for outgoing webhook requests. This keeps the timeout behavior of any outgoing APIs consistent.
diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs index cf7cbb8a2d8..baa5b4af583 100644 --- a/crates/router/src/core/webhooks/outgoing.rs +++ b/crates/router/src/core/webhooks/outgoing.rs @@ -45,8 +45,6 @@ use crate::{ workflows::outgoing_webhook_retry, }; -const OUTGOING_WEBHOOK_TIMEOUT_SECS: u64 = 5; - #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub(crate) async fn create_event_and_trigger_outgoing_webhook( @@ -338,7 +336,7 @@ async fn trigger_webhook_to_merchant( let response = state .api_client - .send_request(&state, request, Some(OUTGOING_WEBHOOK_TIMEOUT_SECS), false) + .send_request(&state, request, None, false) .await; metrics::WEBHOOK_OUTGOING_COUNT.add( diff --git a/crates/router/src/core/webhooks/outgoing_v2.rs b/crates/router/src/core/webhooks/outgoing_v2.rs index 0650bd2e8d9..07758817e68 100644 --- a/crates/router/src/core/webhooks/outgoing_v2.rs +++ b/crates/router/src/core/webhooks/outgoing_v2.rs @@ -396,12 +396,7 @@ async fn build_and_send_request( state .api_client - .send_request( - state, - request, - Some(types::OUTGOING_WEBHOOK_TIMEOUT_SECS), - false, - ) + .send_request(state, request, None, false) .await } diff --git a/crates/router/src/core/webhooks/types.rs b/crates/router/src/core/webhooks/types.rs index 90d637d894e..dcea7f9c16b 100644 --- a/crates/router/src/core/webhooks/types.rs +++ b/crates/router/src/core/webhooks/types.rs @@ -11,8 +11,6 @@ use crate::{ types::storage::{self, enums}, }; -pub const OUTGOING_WEBHOOK_TIMEOUT_SECS: u64 = 5; - #[derive(Debug)] pub enum ScheduleWebhookRetry { WithProcessTracker(Box<storage::ProcessTracker>),
2025-07-23T06:56:47Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Increased outgoing webhook timeout from 5 seconds to 30 seconds by replacing hardcoded `OUTGOING_WEBHOOK_TIMEOUT_SECS` with existing `REQUEST_TIME_OUT` constant for consistency. ### 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). --> 5-second hardcoded timeout causes webhook delivery failures for legacy systems that need more time to respond. Using 30-second timeout maintains consistency with other external API calls. ## 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)? --> <details> <summary>1. Create a simple server for delaying the response for 29seconds</summary> package.json { "name": "webhook-test-server", "version": "1.0.0", "description": "Test server for webhook timeout behavior - waits 30 seconds before responding", "main": "server.js", "scripts": { "start": "node server.js", "dev": "node server.js" }, "dependencies": { "express": "^4.18.2" }, "keywords": ["webhook", "test", "timeout"], "author": "", "license": "MIT" } server.js const express = require('express'); const app = express(); app.use(express.json()); app.post('/webhook', (req, res) => { console.log(`[${new Date().toISOString()}] Webhook received, waiting 29 seconds...`); setTimeout(() => { console.log(`[${new Date().toISOString()}] Responding after 29s delay`); res.json({ message: 'Success after 29s delay' }); }, 29000); }); app.listen(3000, () => { console.log('Webhook test server running on http://localhost:3000'); console.log('POST to /webhook - will wait 29 seconds before responding'); }); Run node server.js </details> <details> <summary>2. Set outgoing webhook endpoint during merchant account creation</summary> http://localhost:3000/webhook (use ngrok to expose this for testing in cloud env) </details> <details> <summary>3. Process a payment</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_9QPrburqsfeS7j2qoybLlIYt5oFfcrFHNxQqUDnlTOYe9s9dkC5cPVOyZaINnWX8' \ --data-raw '{"amount":4500,"currency":"EUR","confirm":true,"profile_id":"pro_jY5jJD5THGIwfuIqH3Nx","capture_method":"automatic","authentication_type":"three_ds","setup_future_usage":"on_session","customer_id":"cus_HXi1vEcMXQ74qsaNq57p","email":"abc@example.com","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4000000000002503","card_exp_month":"12","card_exp_year":"49","card_cvc":"123"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","zip":"94122","country":"SG","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"guest@example.com"},"metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.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"}},"session_expiry":60}' Response {"payment_id":"pay_2Fqjbw3vYGAX1TTGJHWB","merchant_id":"merchant_1753252820","status":"failed","amount":4500,"net_amount":4500,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":"adyen","client_secret":"pay_2Fqjbw3vYGAX1TTGJHWB_secret_b50rZahoz0n6ee4Zm3nr","created":"2025-07-23T06:44:10.822Z","currency":"EUR","customer_id":"cus_HXi1vEcMXQ74qsaNq57p","customer":{"id":"cus_HXi1vEcMXQ74qsaNq57p","name":null,"email":"abc@example.com","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":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"2503","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"49","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"SG","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":null,"first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"guest@example.com"},"order_details":null,"email":"abc@example.com","name":null,"phone":null,"return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":"2","error_message":"Refused","unified_code":"UE_9000","unified_message":"Something went wrong","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":"cus_HXi1vEcMXQ74qsaNq57p","created_at":1753253050,"expires":1753256650,"secret":"epk_63945dac0445483b80731065804a2d75"},"manual_retry_allowed":true,"connector_transaction_id":"F59RPCDCMR9X2F75","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_jY5jJD5THGIwfuIqH3Nx","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_vZ79u4WZFBzDP1O0fSLc","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-07-23T06:45:10.822Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2025-07-23T06:44:13.414Z","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":"This is not a testCard","is_iframe_redirection_enabled":null,"whole_connector_response":null} Observations - Outgoing webhook triggered from application - A response is triggered after 29seconds and the connection from HS is not dropped (Status received: 200) <img width="865" height="811" alt="Screenshot 2025-07-23 at 12 21 36β€―PM" src="https://github.com/user-attachments/assets/8c053b7e-4e39-464a-bfe6-62c5c3b2504a" /> </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.115.0
6214aca5f0f5c617a68f65ef5bcfd700060acccf
6214aca5f0f5c617a68f65ef5bcfd700060acccf
juspay/hyperswitch
juspay__hyperswitch-8734
Bug: feat(core): Implement UCS based upi for paytm and phonepe ## Feature Request: Implement UPI Intent and QR Code Payment Flows for UCS Integration ### Description Add support for UPI Intent and QR code payment methods through the Unified Connector Service (UCS) for Paytm and PhonePe payment gateways. ### Background UPI is a critical payment method in India. Currently, Hyperswitch lacks support for UPI Intent (for mobile apps) and QR code flows through the UCS integration. This limits merchants' ability to accept UPI payments through these popular payment gateways. ### Requirements - Add default implementations for Paytm and PhonePe connectors - Support UPI Intent payment method for mobile app integrations - Support QR code generation and payment flow for UPI - Route payment requests through UCS (actual payment processing handled by UCS) - Add necessary configuration entries for both connectors ### Technical Details - The implementation should follow the existing UCS architecture pattern - No direct API integration with Paytm/PhonePe required (handled by UCS) - Need to add routing logic and connector definitions - Should support standard payment operations: create, sync, refund ### Acceptance Criteria - Successfully create UPI Intent payments through Paytm and PhonePe via UCS - QR code generation works for UPI payments - Payment status sync operations function correctly - Configuration properly set up across all environments
diff --git a/Cargo.lock b/Cargo.lock index 4b51d433be0..3e1101fdbf4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3525,7 +3525,7 @@ dependencies = [ [[package]] name = "grpc-api-types" version = "0.1.0" -source = "git+https://github.com/juspay/connector-service?rev=a9f7cd96693fa034ea69d8e21125ea0f76182fae#a9f7cd96693fa034ea69d8e21125ea0f76182fae" +source = "git+https://github.com/juspay/connector-service?rev=0409f6aa1014dd1b9827fabfa4fa424e16d07ebc#0409f6aa1014dd1b9827fabfa4fa424e16d07ebc" dependencies = [ "axum 0.8.4", "error-stack 0.5.0", @@ -6899,7 +6899,7 @@ dependencies = [ [[package]] name = "rust-grpc-client" version = "0.1.0" -source = "git+https://github.com/juspay/connector-service?rev=a9f7cd96693fa034ea69d8e21125ea0f76182fae#a9f7cd96693fa034ea69d8e21125ea0f76182fae" +source = "git+https://github.com/juspay/connector-service?rev=0409f6aa1014dd1b9827fabfa4fa424e16d07ebc#0409f6aa1014dd1b9827fabfa4fa424e16d07ebc" dependencies = [ "grpc-api-types", ] diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index e38d2cfa965..7591fb65fba 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -11734,7 +11734,9 @@ "payone", "paypal", "paystack", + "paytm", "payu", + "phonepe", "placetopay", "powertranz", "prophetpay", @@ -29246,7 +29248,9 @@ "payone", "paypal", "paystack", + "paytm", "payu", + "phonepe", "placetopay", "powertranz", "prophetpay", diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 8347355c128..6602d2e2814 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -8296,7 +8296,9 @@ "payone", "paypal", "paystack", + "paytm", "payu", + "phonepe", "placetopay", "powertranz", "prophetpay", @@ -23099,7 +23101,9 @@ "payone", "paypal", "paystack", + "paytm", "payu", + "phonepe", "placetopay", "powertranz", "prophetpay", diff --git a/config/config.example.toml b/config/config.example.toml index d4c23a6b529..0ca3cbdc5bf 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -276,7 +276,9 @@ 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" +paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" +phonepe.base_url = "https://api.phonepe.com/apis/hermes/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" powertranz.base_url = "https://staging.ptranz.com/api/" @@ -646,6 +648,14 @@ open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,M [pm_filters.razorpay] upi_collect = { country = "IN", currency = "INR" } +[pm_filters.phonepe] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } + +[pm_filters.paytm] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } + [pm_filters.plaid] open_banking_pis = {currency = "EUR,GBP"} diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 4bad9058da7..453dd680445 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -113,7 +113,9 @@ 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" +paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" +phonepe.base_url = "https://api.phonepe.com/apis/hermes/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" powertranz.base_url = "https://staging.ptranz.com/api/" @@ -556,6 +558,14 @@ open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT [pm_filters.razorpay] upi_collect = {country = "IN", currency = "INR"} +[pm_filters.phonepe] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } + +[pm_filters.paytm] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } + [pm_filters.redsys] credit = { currency = "AUD,BGN,CAD,CHF,COP,CZK,DKK,EUR,GBP,HRK,HUF,ILS,INR,JPY,MYR,NOK,NZD,PEN,PLN,RUB,SAR,SEK,SGD,THB,USD,ZAR", country="ES" } debit = { currency = "AUD,BGN,CAD,CHF,COP,CZK,DKK,EUR,GBP,HRK,HUF,ILS,INR,JPY,MYR,NOK,NZD,PEN,PLN,RUB,SAR,SEK,SGD,THB,USD,ZAR", country="ES" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 90fd7d058b7..2a78a2d6f76 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -117,7 +117,9 @@ 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" +paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.payu.com/api/" +phonepe.base_url = "https://api.phonepe.com/apis/hermes/" placetopay.base_url = "https://checkout.placetopay.com/rest/gateway" plaid.base_url = "https://production.plaid.com" powertranz.base_url = "https://staging.ptranz.com/api/" @@ -597,6 +599,14 @@ open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT [pm_filters.razorpay] upi_collect = {country = "IN", currency = "INR"} +[pm_filters.phonepe] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } + +[pm_filters.paytm] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } + [pm_filters.redsys] credit = { currency = "AUD,BGN,CAD,CHF,COP,CZK,DKK,EUR,GBP,HRK,HUF,ILS,INR,JPY,MYR,NOK,NZD,PEN,PLN,RUB,SAR,SEK,SGD,THB,USD,ZAR", country="ES" } debit = { currency = "AUD,BGN,CAD,CHF,COP,CZK,DKK,EUR,GBP,HRK,HUF,ILS,INR,JPY,MYR,NOK,NZD,PEN,PLN,RUB,SAR,SEK,SGD,THB,USD,ZAR", country="ES" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 00e387cb0b4..71926937b9e 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -117,7 +117,9 @@ 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" +paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" +phonepe.base_url = "https://api.phonepe.com/apis/hermes/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" powertranz.base_url = "https://staging.ptranz.com/api/" @@ -605,6 +607,14 @@ open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,M [pm_filters.razorpay] upi_collect = {country = "IN", currency = "INR"} +[pm_filters.phonepe] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } + +[pm_filters.paytm] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } + [pm_filters.redsys] credit = { currency = "AUD,BGN,CAD,CHF,COP,CZK,DKK,EUR,GBP,HRK,HUF,ILS,INR,JPY,MYR,NOK,NZD,PEN,PLN,RUB,SAR,SEK,SGD,THB,USD,ZAR", country="ES" } debit = { currency = "AUD,BGN,CAD,CHF,COP,CZK,DKK,EUR,GBP,HRK,HUF,ILS,INR,JPY,MYR,NOK,NZD,PEN,PLN,RUB,SAR,SEK,SGD,THB,USD,ZAR", country="ES" } diff --git a/config/development.toml b/config/development.toml index 047afe11795..04472252af4 100644 --- a/config/development.toml +++ b/config/development.toml @@ -315,7 +315,9 @@ 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" +paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" +phonepe.base_url = "https://api.phonepe.com/apis/hermes/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" powertranz.base_url = "https://staging.ptranz.com/api/" @@ -460,6 +462,14 @@ open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,M [pm_filters.razorpay] upi_collect = { country = "IN", currency = "INR" } +[pm_filters.phonepe] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } + +[pm_filters.paytm] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } + [pm_filters.plaid] open_banking_pis = { currency = "EUR,GBP" } @@ -1235,6 +1245,12 @@ url = "http://localhost:8080" host = "localhost" port = 8000 connection_timeout = 10 +ucs_only_connectors = [ + "razorpay", + "phonepe", + "paytm", + "cashfree", +] [revenue_recovery] monitoring_threshold_in_seconds = 2592000 diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 770bf0fdea0..85208bd157d 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -202,7 +202,9 @@ 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" +paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" +phonepe.base_url = "https://api.phonepe.com/apis/hermes/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" powertranz.base_url = "https://staging.ptranz.com/api/" @@ -561,6 +563,14 @@ open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,M [pm_filters.razorpay] upi_collect = { country = "IN", currency = "INR" } +[pm_filters.phonepe] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } + +[pm_filters.paytm] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } + [pm_filters.payu] debit = { country = "AE, AF, AL, AM, CW, AO, AR, AU, AW, AZ, BA, BB, BG, BH, BI, BM, BN, BO, BR, BS, BW, BY, BZ, CA, CD, LI, CL, CN, CO, CR, CV, CZ, DJ, DK, DO, DZ, EG, ET, AD, FJ, FK, GG, GE, GH, GI, GM, GN, GT, GY, HK, HN, HR, HT, HU, ID, IL, IQ, IS, JM, JO, JP, KG, KH, KM, KR, KW, KY, KZ, LA, LB, LR, LS, MA, MD, MG, MK, MN, MO, MR, MV, MW, MX, MY, MZ, NA, NG, NI, BV, CK, OM, PA, PE, PG, PL, PY, QA, RO, RS, RW, SA, SB, SC, SE, SG, SH, SO, SR, SV, SZ, TH, TJ, TM, TN, TO, TR, TT, TW, TZ, UG, AS, UY, UZ, VE, VN, VU, WS, CM, AI, BJ, PF, YE, ZA, ZM, ZW", currency = "AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BWP, BYN, BZD, CAD, CDF, CHF, CLP, CNY, COP, CRC, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, IQD, ISK, JMD, JOD, JPY, KGS, KHR, KMF, KRW, KWD, KYD, KZT, LAK, LBP, LRD, LSL, MAD, MDL, MGA, MKD, MNT, MOP, MRU, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NZD, OMR, PAB, PEN, PGK, PLN, PYG, QAR, RON, RSD, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SOS, SRD, SVC, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL" } credit = { country = "AE, AF, AL, AM, CW, AO, AR, AU, AW, AZ, BA, BB, BG, BH, BI, BM, BN, BO, BR, BS, BW, BY, BZ, CA, CD, LI, CL, CN, CO, CR, CV, CZ, DJ, DK, DO, DZ, EG, ET, AD, FJ, FK, GG, GE, GH, GI, GM, GN, GT, GY, HK, HN, HR, HT, HU, ID, IL, IQ, IS, JM, JO, JP, KG, KH, KM, KR, KW, KY, KZ, LA, LB, LR, LS, MA, MD, MG, MK, MN, MO, MR, MV, MW, MX, MY, MZ, NA, NG, NI, BV, CK, OM, PA, PE, PG, PL, PY, QA, RO, RS, RW, SA, SB, SC, SE, SG, SH, SO, SR, SV, SZ, TH, TJ, TM, TN, TO, TR, TT, TW, TZ, UG, AS, UY, UZ, VE, VN, VU, WS, CM, AI, BJ, PF, YE, ZA, ZM, ZW", currency = "AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BWP, BYN, BZD, CAD, CDF, CHF, CLP, CNY, COP, CRC, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, IQD, ISK, JMD, JOD, JPY, KGS, KHR, KMF, KRW, KWD, KYD, KZT, LAK, LBP, LRD, LSL, MAD, MDL, MGA, MKD, MNT, MOP, MRU, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NZD, OMR, PAB, PEN, PGK, PLN, PYG, QAR, RON, RSD, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SOS, SRD, SVC, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL" } diff --git a/config/payment_required_fields_v2.toml b/config/payment_required_fields_v2.toml index fe1e6e050d2..35483873f35 100644 --- a/config/payment_required_fields_v2.toml +++ b/config/payment_required_fields_v2.toml @@ -2114,6 +2114,26 @@ common = [ mandate = [] non_mandate = [] +[required_fields.upi.upi_collect.fields.Phonepe] +common = [ + { required_field = "payment_method_data.upi.vpa_id", display_name = "vpa_id", field_type = "text" }, + { required_field = "payment_method_data.billing.email", display_name = "email", field_type = "user_email_address" }, + { required_field = "payment_method_data.billing.phone.number", display_name = "phone", field_type = "user_phone_number" }, + { required_field = "payment_method_data.billing.phone.country_code", display_name = "dialing_code", field_type = "user_phone_number_country_code" } +] +mandate = [] +non_mandate = [] + +[required_fields.upi.upi_collect.fields.Paytm] +common = [ + { required_field = "payment_method_data.upi.vpa_id", display_name = "vpa_id", field_type = "text" }, + { required_field = "payment_method_data.billing.email", display_name = "email", field_type = "user_email_address" }, + { required_field = "payment_method_data.billing.phone.number", display_name = "phone", field_type = "user_phone_number" }, + { required_field = "payment_method_data.billing.phone.country_code", display_name = "dialing_code", field_type = "user_phone_number_country_code" } +] +mandate = [] +non_mandate = [] + # BankDebit # Payment method type: Ach [required_fields.bank_debit.ach.fields.Stripe] diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 8d5b737b8b3..c3741e0f5ea 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -131,7 +131,9 @@ pub enum RoutableConnectors { Payone, Paypal, Paystack, + Paytm, Payu, + Phonepe, Placetopay, Powertranz, Prophetpay, @@ -301,7 +303,9 @@ pub enum Connector { Payone, Paypal, Paystack, + Paytm, Payu, + Phonepe, Placetopay, Powertranz, Prophetpay, @@ -523,7 +527,9 @@ impl Connector { | Self::Noon | Self::Tokenio | Self::Stripe - | Self::Datatrans => false, + | Self::Datatrans + | Self::Paytm + | Self::Phonepe => false, Self::Checkout | Self::Nmi |Self::Cybersource | Self::Archipel => true, } } @@ -684,6 +690,8 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Inespay => Self::Inespay, RoutableConnectors::Coingate => Self::Coingate, RoutableConnectors::Hipay => Self::Hipay, + RoutableConnectors::Paytm => Self::Paytm, + RoutableConnectors::Phonepe => Self::Phonepe, } } } @@ -810,6 +818,8 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Hipay => Ok(Self::Hipay), Connector::Inespay => Ok(Self::Inespay), Connector::Redsys => Ok(Self::Redsys), + Connector::Paytm => Ok(Self::Paytm), + Connector::Phonepe => Ok(Self::Phonepe), Connector::CtpMastercard | Connector::Gpayments | Connector::HyperswitchVault diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index f0dc8dbf626..84e7398f61c 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -257,7 +257,9 @@ pub struct ConnectorConfig { #[cfg(feature = "payouts")] pub paypal_payout: Option<ConnectorTomlConfig>, pub paystack: Option<ConnectorTomlConfig>, + pub paytm: Option<ConnectorTomlConfig>, pub payu: Option<ConnectorTomlConfig>, + pub phonepe: Option<ConnectorTomlConfig>, pub placetopay: Option<ConnectorTomlConfig>, pub plaid: Option<ConnectorTomlConfig>, pub powertranz: Option<ConnectorTomlConfig>, @@ -499,6 +501,8 @@ impl ConnectorConfig { Connector::Netcetera => Ok(connector_data.netcetera), Connector::CtpMastercard => Ok(connector_data.ctp_mastercard), Connector::Xendit => Ok(connector_data.xendit), + Connector::Paytm => Ok(connector_data.paytm), + Connector::Phonepe => Ok(connector_data.phonepe), } } } diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 99434751194..238e336c3cd 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -6463,6 +6463,25 @@ payment_experience = "redirect_to_url" [mpgs.connector_auth.HeaderKey] api_key = "API Key" +[phonepe] +[[phonepe.upi]] +payment_method_type = "upi_collect" +[[phonepe.upi]] +payment_method_type = "upi_intent" +[phonepe.connector_auth.SignatureKey] +api_key="merchant_id" +api_secret="key_index" +key1="salt_key" + +[paytm] +[[paytm.upi]] +payment_method_type = "upi_collect" +[[paytm.upi]] +payment_method_type = "upi_intent" +[paytm.connector_auth.SignatureKey] +api_key="Signing key" +api_secret="website name" +key1="merchant_id" [bluecode] [bluecode.connector_auth.HeaderKey] api_key = "API Key" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index d4cb52daed3..509ea1608a1 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -5080,6 +5080,26 @@ key1 = "API Secret" payment_method_type = "breadpay" payment_experience = "redirect_to_url" +[phonepe] +[[phonepe.upi]] +payment_method_type = "upi_collect" +[[phonepe.upi]] +payment_method_type = "upi_intent" +[phonepe.connector_auth.SignatureKey] +api_key="merchant_id" +api_secret="key_index" +key1="salt_key" + +[paytm] +[[paytm.upi]] +payment_method_type = "upi_collect" +[[paytm.upi]] +payment_method_type = "upi_intent" +[paytm.connector_auth.SignatureKey] +api_key="Signing key" +api_secret="website name" +key1="merchant_id" + [mpgs] [mpgs.connector_auth.HeaderKey] api_key = "API Key" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 6ef9c0be1a5..ff6a076ae37 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -6444,6 +6444,25 @@ payment_experience = "redirect_to_url" [mpgs.connector_auth.HeaderKey] api_key = "API Key" +[phonepe] +[[phonepe.upi]] +payment_method_type = "upi_collect" +[[phonepe.upi]] +payment_method_type = "upi_intent" +[phonepe.connector_auth.SignatureKey] +api_key="merchant_id" +api_secret="key_index" +key1="salt_key" + +[paytm] +[[paytm.upi]] +payment_method_type = "upi_collect" +[[paytm.upi]] +payment_method_type = "upi_intent" +[paytm.connector_auth.SignatureKey] +api_key="Signing key" +api_secret="website name" +key1="merchant_id" [bluecode] [bluecode.connector_auth.HeaderKey] api_key = "API Key" diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index d7fa5897526..bfa0a8b6132 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -53,7 +53,7 @@ reqwest = { version = "0.11.27", features = ["rustls-tls"] } http = "0.2.12" url = { version = "2.5.4", features = ["serde"] } quick-xml = { version = "0.31.0", features = ["serialize"] } -unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "a9f7cd96693fa034ea69d8e21125ea0f76182fae", package = "rust-grpc-client" } +unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "0409f6aa1014dd1b9827fabfa4fa424e16d07ebc", package = "rust-grpc-client" } # First party crates diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs index bac66a3bb50..7ca74cdda3b 100644 --- a/crates/external_services/src/grpc_client/unified_connector_service.rs +++ b/crates/external_services/src/grpc_client/unified_connector_service.rs @@ -118,6 +118,10 @@ pub struct UnifiedConnectorServiceClientConfig { /// Contains the connection timeout duration in seconds pub connection_timeout: u64, + + /// List of connectors to use with the unified connector service + #[serde(default)] + pub ucs_only_connectors: Vec<String>, } /// Contains the Connector Auth Type and related authentication data. diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index acf048d45d8..e2b648e75e5 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -83,7 +83,9 @@ pub mod payme; pub mod payone; pub mod paypal; pub mod paystack; +pub mod paytm; pub mod payu; +pub mod phonepe; pub mod placetopay; pub mod plaid; pub mod powertranz; @@ -143,13 +145,13 @@ pub use self::{ multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nexixpay::Nexixpay, nmi::Nmi, nomupay::Nomupay, noon::Noon, nordea::Nordea, novalnet::Novalnet, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payload::Payload, - payme::Payme, payone::Payone, paypal::Paypal, paystack::Paystack, payu::Payu, - placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz, prophetpay::Prophetpay, - rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, riskified::Riskified, - santander::Santander, shift4::Shift4, signifyd::Signifyd, silverflow::Silverflow, - square::Square, stax::Stax, stripe::Stripe, stripebilling::Stripebilling, taxjar::Taxjar, - threedsecureio::Threedsecureio, thunes::Thunes, tokenio::Tokenio, trustpay::Trustpay, - trustpayments::Trustpayments, tsys::Tsys, + payme::Payme, payone::Payone, paypal::Paypal, paystack::Paystack, paytm::Paytm, payu::Payu, + phonepe::Phonepe, placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz, + prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, + riskified::Riskified, santander::Santander, shift4::Shift4, signifyd::Signifyd, + silverflow::Silverflow, square::Square, stax::Stax, stripe::Stripe, + stripebilling::Stripebilling, taxjar::Taxjar, threedsecureio::Threedsecureio, thunes::Thunes, + tokenio::Tokenio, trustpay::Trustpay, trustpayments::Trustpayments, tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, vgs::Vgs, volt::Volt, wellsfargo::Wellsfargo, wellsfargopayout::Wellsfargopayout, wise::Wise, worldline::Worldline, worldpay::Worldpay, worldpayvantiv::Worldpayvantiv, worldpayxml::Worldpayxml, xendit::Xendit, diff --git a/crates/hyperswitch_connectors/src/connectors/paytm.rs b/crates/hyperswitch_connectors/src/connectors/paytm.rs new file mode 100644 index 00000000000..4a72fa88575 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/paytm.rs @@ -0,0 +1,614 @@ +pub mod transformers; + +use std::sync::LazyLock; + +use common_enums::enums; +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::{ + payment_method_data::PaymentMethodData, + 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::{ + ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, + }, + 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 transformers as paytm; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Paytm { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Paytm { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Paytm {} +impl api::PaymentSession for Paytm {} +impl api::ConnectorAccessToken for Paytm {} +impl api::MandateSetup for Paytm {} +impl api::PaymentAuthorize for Paytm {} +impl api::PaymentSync for Paytm {} +impl api::PaymentCapture for Paytm {} +impl api::PaymentVoid for Paytm {} +impl api::Refund for Paytm {} +impl api::RefundExecute for Paytm {} +impl api::RefundSync for Paytm {} +impl api::PaymentToken for Paytm {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Paytm +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paytm +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 Paytm { + fn id(&self) -> &'static str { + "paytm" + } + + 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.paytm.base_url.as_ref() + } + + fn get_auth_header( + &self, + _auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + // This method is not implemented for Paytm, as it will always call the UCS service which has the logic to create headers. + Err(errors::ConnectorError::NotImplemented("get_auth_header method".to_string()).into()) + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: paytm::PaytmErrorResponse = + res.response + .parse_struct("PaytmErrorResponse") + .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, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) + } +} + +impl ConnectorValidation for Paytm { + fn validate_mandate_payment( + &self, + _pm_type: Option<enums::PaymentMethodType>, + pm_data: PaymentMethodData, + ) -> CustomResult<(), errors::ConnectorError> { + match pm_data { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "validate_mandate_payment does not support cards".to_string(), + ) + .into()), + _ => Ok(()), + } + } + + fn validate_psync_reference_id( + &self, + _data: &PaymentsSyncData, + _is_three_ds: bool, + _status: enums::AttemptStatus, + _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, + ) -> CustomResult<(), errors::ConnectorError> { + Ok(()) + } +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Paytm { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Paytm {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Paytm {} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paytm { + 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 = paytm::PaytmRouterData::from((amount, req)); + let connector_req = paytm::PaytmPaymentsRequest::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: paytm::PaytmPaymentsResponse = res + .response + .parse_struct("Paytm 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 Paytm { + 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: paytm::PaytmPaymentsResponse = res + .response + .parse_struct("paytm 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 Paytm { + 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: paytm::PaytmPaymentsResponse = res + .response + .parse_struct("Paytm 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 Paytm {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paytm { + 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 = paytm::PaytmRouterData::from((refund_amount, req)); + let connector_req = paytm::PaytmRefundRequest::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: paytm::RefundResponse = res + .response + .parse_struct("paytm 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 Paytm { + 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: paytm::RefundResponse = res + .response + .parse_struct("paytm 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 Paytm { + 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)) + } +} + +static PAYTM_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(SupportedPaymentMethods::new); + +static PAYTM_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Paytm", + description: "Paytm connector", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; + +static PAYTM_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Paytm { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&PAYTM_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*PAYTM_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&PAYTM_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/paytm/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paytm/transformers.rs new file mode 100644 index 00000000000..67fe017e609 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/paytm/transformers.rs @@ -0,0 +1,225 @@ +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}; + +//TODO: Fill the struct with respective fields +pub struct PaytmRouterData<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 PaytmRouterData<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 PaytmPaymentsRequest { + amount: StringMinorUnit, + card: PaytmCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct PaytmCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&PaytmRouterData<&PaymentsAuthorizeRouterData>> for PaytmPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &PaytmRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "Card payment method not implemented".to_string(), + ) + .into()), + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct PaytmAuthType { + pub merchant_id: Secret<String>, + pub merchant_key: Secret<String>, + pub website: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for PaytmAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } => Ok(Self { + merchant_id: key1.to_owned(), // merchant_id + merchant_key: api_key.to_owned(), // signing key + website: api_secret.to_owned(), // website name + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} +// PaymentsResponse +//TODO: Append the remaining status flags +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum PaytmPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<PaytmPaymentStatus> for common_enums::AttemptStatus { + fn from(item: PaytmPaymentStatus) -> Self { + match item { + PaytmPaymentStatus::Succeeded => Self::Charged, + PaytmPaymentStatus::Failed => Self::Failure, + PaytmPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PaytmPaymentsResponse { + status: PaytmPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, PaytmPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, PaytmPaymentsResponse, 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 PaytmRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&PaytmRouterData<&RefundsRouterData<F>>> for PaytmRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &PaytmRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Copy, 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 PaytmErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, + pub network_advice_code: Option<String>, + pub network_decline_code: Option<String>, + pub network_error_message: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/connectors/phonepe.rs b/crates/hyperswitch_connectors/src/connectors/phonepe.rs new file mode 100644 index 00000000000..43ea9538fde --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/phonepe.rs @@ -0,0 +1,614 @@ +pub mod transformers; + +use std::sync::LazyLock; + +use common_enums::enums; +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::{ + payment_method_data::PaymentMethodData, + 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::{ + ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, + }, + 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 transformers as phonepe; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Phonepe { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Phonepe { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Phonepe {} +impl api::PaymentSession for Phonepe {} +impl api::ConnectorAccessToken for Phonepe {} +impl api::MandateSetup for Phonepe {} +impl api::PaymentAuthorize for Phonepe {} +impl api::PaymentSync for Phonepe {} +impl api::PaymentCapture for Phonepe {} +impl api::PaymentVoid for Phonepe {} +impl api::Refund for Phonepe {} +impl api::RefundExecute for Phonepe {} +impl api::RefundSync for Phonepe {} +impl api::PaymentToken for Phonepe {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Phonepe +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Phonepe +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 Phonepe { + fn id(&self) -> &'static str { + "phonepe" + } + + 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.phonepe.base_url.as_ref() + } + + fn get_auth_header( + &self, + _auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + // This method is not implemented for Phonepe, as it will always call the UCS service which has the logic to create headers. + Err(errors::ConnectorError::NotImplemented("get_auth_header method".to_string()).into()) + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: phonepe::PhonepeErrorResponse = res + .response + .parse_struct("PhonepeErrorResponse") + .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, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) + } +} + +impl ConnectorValidation for Phonepe { + fn validate_mandate_payment( + &self, + _pm_type: Option<enums::PaymentMethodType>, + pm_data: PaymentMethodData, + ) -> CustomResult<(), errors::ConnectorError> { + match pm_data { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "validate_mandate_payment does not support cards".to_string(), + ) + .into()), + _ => Ok(()), + } + } + + fn validate_psync_reference_id( + &self, + _data: &PaymentsSyncData, + _is_three_ds: bool, + _status: enums::AttemptStatus, + _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, + ) -> CustomResult<(), errors::ConnectorError> { + Ok(()) + } +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Phonepe { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Phonepe {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Phonepe {} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Phonepe { + 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 = phonepe::PhonepeRouterData::from((amount, req)); + let connector_req = phonepe::PhonepePaymentsRequest::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: phonepe::PhonepePaymentsResponse = res + .response + .parse_struct("Phonepe 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 Phonepe { + 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: phonepe::PhonepePaymentsResponse = res + .response + .parse_struct("phonepe 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 Phonepe { + 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: phonepe::PhonepePaymentsResponse = res + .response + .parse_struct("Phonepe 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 Phonepe {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Phonepe { + 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 = phonepe::PhonepeRouterData::from((refund_amount, req)); + let connector_req = phonepe::PhonepeRefundRequest::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: phonepe::RefundResponse = res + .response + .parse_struct("phonepe 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 Phonepe { + 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: phonepe::RefundResponse = res + .response + .parse_struct("phonepe 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 Phonepe { + 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)) + } +} + +static PHONEPE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(SupportedPaymentMethods::new); + +static PHONEPE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Phonepe", + description: "Phonepe connector", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; + +static PHONEPE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Phonepe { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&PHONEPE_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*PHONEPE_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&PHONEPE_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/phonepe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/phonepe/transformers.rs new file mode 100644 index 00000000000..9741218004d --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/phonepe/transformers.rs @@ -0,0 +1,227 @@ +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::{PeekInterface, Secret}; +use serde::{Deserialize, Serialize}; + +use crate::types::{RefundsResponseRouterData, ResponseRouterData}; + +//TODO: Fill the struct with respective fields +pub struct PhonepeRouterData<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 PhonepeRouterData<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 PhonepePaymentsRequest { + amount: StringMinorUnit, + card: PhonepeCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct PhonepeCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&PhonepeRouterData<&PaymentsAuthorizeRouterData>> for PhonepePaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &PhonepeRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( + "Card payment method not implemented".to_string(), + ) + .into()), + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct PhonepeAuthType { + pub merchant_id: Secret<String>, + pub salt_key: Secret<String>, + pub key_index: String, +} + +impl TryFrom<&ConnectorAuthType> for PhonepeAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } => Ok(Self { + merchant_id: api_key.clone(), + salt_key: key1.clone(), + key_index: api_secret.peek().clone(), // Use api_secret for key index + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} +// PaymentsResponse +//TODO: Append the remaining status flags +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum PhonepePaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<PhonepePaymentStatus> for common_enums::AttemptStatus { + fn from(item: PhonepePaymentStatus) -> Self { + match item { + PhonepePaymentStatus::Succeeded => Self::Charged, + PhonepePaymentStatus::Failed => Self::Failure, + PhonepePaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PhonepePaymentsResponse { + status: PhonepePaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, PhonepePaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, PhonepePaymentsResponse, 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 PhonepeRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&PhonepeRouterData<&RefundsRouterData<F>>> for PhonepeRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &PhonepeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Copy, 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 PhonepeErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, + pub network_advice_code: Option<String>, + pub network_decline_code: Option<String>, + pub network_error_message: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 05fe9d06ad6..67821e66d72 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -218,7 +218,9 @@ default_imp_for_authorize_session_token!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -360,7 +362,9 @@ default_imp_for_calculate_tax!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -502,7 +506,9 @@ default_imp_for_session_update!( connectors::Payme, connectors::Payone, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::UnifiedAuthenticationService, @@ -639,7 +645,9 @@ default_imp_for_post_session_tokens!( connectors::Payme, connectors::Payone, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Fiuu, @@ -775,7 +783,9 @@ default_imp_for_create_order!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Fiuu, @@ -910,7 +920,9 @@ default_imp_for_update_metadata!( connectors::Payload, connectors::Payme, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Payone, @@ -1031,7 +1043,9 @@ default_imp_for_complete_authorize!( connectors::Payload, connectors::Payone, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Rapyd, @@ -1156,7 +1170,9 @@ default_imp_for_incremental_authorization!( connectors::Payme, connectors::Payone, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -1296,7 +1312,9 @@ default_imp_for_create_customer!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -1417,8 +1435,10 @@ default_imp_for_connector_redirect_response!( connectors::Payeezy, connectors::Payload, connectors::Paystack, + connectors::Paytm, connectors::Payone, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -1538,8 +1558,10 @@ default_imp_for_pre_processing_steps!( connectors::Payeezy, connectors::Payload, connectors::Paystack, + connectors::Paytm, connectors::Payone, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -1672,7 +1694,9 @@ default_imp_for_post_processing_steps!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Powertranz, connectors::Prophetpay, @@ -1809,8 +1833,10 @@ default_imp_for_approve!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payone, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -1949,7 +1975,9 @@ default_imp_for_reject!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -2087,7 +2115,9 @@ default_imp_for_webhook_source_verification!( connectors::Payload, connectors::Payme, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -2225,7 +2255,9 @@ default_imp_for_accept_dispute!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -2362,7 +2394,9 @@ default_imp_for_submit_evidence!( connectors::Paypal, connectors::Payone, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -2498,7 +2532,9 @@ default_imp_for_defend_dispute!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -2644,7 +2680,9 @@ default_imp_for_file_upload!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -2773,7 +2811,9 @@ default_imp_for_payouts!( connectors::Payload, connectors::Payme, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -2902,7 +2942,9 @@ default_imp_for_payouts_create!( connectors::Payme, connectors::Payone, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -3038,7 +3080,9 @@ default_imp_for_payouts_retrieve!( connectors::Payload, connectors::Payme, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Payone, connectors::Placetopay, connectors::Plaid, @@ -3176,8 +3220,10 @@ default_imp_for_payouts_eligibility!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payone, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -3310,7 +3356,9 @@ default_imp_for_payouts_fulfill!( connectors::Payload, connectors::Payme, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -3445,8 +3493,10 @@ default_imp_for_payouts_cancel!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payone, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -3583,7 +3633,9 @@ default_imp_for_payouts_quote!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -3721,7 +3773,9 @@ default_imp_for_payouts_recipient!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -3859,7 +3913,9 @@ default_imp_for_payouts_recipient_account!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -3999,7 +4055,9 @@ default_imp_for_frm_sale!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -4138,7 +4196,9 @@ default_imp_for_frm_checkout!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -4277,7 +4337,9 @@ default_imp_for_frm_transaction!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -4416,7 +4478,9 @@ default_imp_for_frm_fulfillment!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -4555,7 +4619,9 @@ default_imp_for_frm_record_return!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -4688,7 +4754,9 @@ default_imp_for_revoking_mandates!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -4824,7 +4892,9 @@ default_imp_for_uas_pre_authentication!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -4960,7 +5030,9 @@ default_imp_for_uas_post_authentication!( connectors::Payone, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, connectors::Plaid, @@ -5096,7 +5168,9 @@ default_imp_for_uas_authentication_confirmation!( connectors::Payme, connectors::Payone, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -5222,7 +5296,9 @@ default_imp_for_connector_request_id!( connectors::Payeezy, connectors::Payload, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Payme, connectors::Payone, connectors::Paypal, @@ -5354,8 +5430,10 @@ default_imp_for_fraud_check!( connectors::Payeezy, connectors::Payload, connectors::Paystack, + connectors::Paytm, connectors::Paypal, connectors::Payu, + connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -5514,7 +5592,9 @@ default_imp_for_connector_authentication!( connectors::Payeezy, connectors::Payload, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Payone, connectors::Powertranz, connectors::Prophetpay, @@ -5647,7 +5727,9 @@ default_imp_for_uas_authentication!( connectors::Payload, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -5779,7 +5861,9 @@ default_imp_for_revenue_recovery!( connectors::Payeezy, connectors::Payload, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Paypal, connectors::Powertranz, connectors::Prophetpay, @@ -5919,7 +6003,9 @@ default_imp_for_billing_connector_payment_sync!( connectors::Payeezy, connectors::Payload, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Paypal, connectors::Powertranz, connectors::Prophetpay, @@ -6057,7 +6143,9 @@ default_imp_for_revenue_recovery_record_back!( connectors::Payeezy, connectors::Payload, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Paypal, connectors::Powertranz, connectors::Prophetpay, @@ -6195,7 +6283,9 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Payeezy, connectors::Payload, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Paypal, connectors::Powertranz, connectors::Prophetpay, @@ -6327,7 +6417,9 @@ default_imp_for_external_vault!( connectors::Payeezy, connectors::Payload, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Paypal, connectors::Plaid, connectors::Powertranz, @@ -6465,7 +6557,9 @@ default_imp_for_external_vault_insert!( connectors::Payeezy, connectors::Payload, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Paypal, connectors::Plaid, connectors::Powertranz, @@ -6603,7 +6697,9 @@ default_imp_for_external_vault_retrieve!( connectors::Payeezy, connectors::Payload, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Paypal, connectors::Plaid, connectors::Powertranz, @@ -6741,7 +6837,9 @@ default_imp_for_external_vault_delete!( connectors::Payeezy, connectors::Payload, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Paypal, connectors::Plaid, connectors::Powertranz, @@ -6878,7 +6976,9 @@ default_imp_for_external_vault_create!( connectors::Payeezy, connectors::Payload, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Paypal, connectors::Plaid, connectors::Powertranz, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 754d3f72f55..72cb5a3cf3b 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -325,7 +325,9 @@ default_imp_for_new_connector_integration_payment!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -464,7 +466,9 @@ default_imp_for_new_connector_integration_refund!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -598,7 +602,9 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -737,7 +743,9 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -875,7 +883,9 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -1014,7 +1024,9 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -1163,7 +1175,9 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -1304,7 +1318,9 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -1445,7 +1461,9 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -1586,7 +1604,9 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -1727,7 +1747,9 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -1868,7 +1890,9 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -2009,7 +2033,9 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -2150,7 +2176,9 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -2291,7 +2319,9 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -2430,7 +2460,9 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -2571,7 +2603,9 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -2712,7 +2746,9 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -2853,7 +2889,9 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -2994,7 +3032,9 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -3135,7 +3175,9 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -3272,7 +3314,9 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Payload, connectors::Payme, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -3329,6 +3373,7 @@ macro_rules! default_imp_for_new_connector_integration_frm { default_imp_for_new_connector_integration_frm!( connectors::Trustpayments, connectors::Affirm, + connectors::Paytm, connectors::Vgs, connectors::Airwallex, connectors::Amazonpay, @@ -3386,6 +3431,7 @@ default_imp_for_new_connector_integration_frm!( connectors::Payeezy, connectors::Payload, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -3467,6 +3513,7 @@ macro_rules! default_imp_for_new_connector_integration_connector_authentication default_imp_for_new_connector_integration_connector_authentication!( connectors::Trustpayments, connectors::Affirm, + connectors::Paytm, connectors::Vgs, connectors::Airwallex, connectors::Amazonpay, @@ -3522,6 +3569,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Payeezy, connectors::Payload, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -3594,6 +3642,7 @@ macro_rules! default_imp_for_new_connector_integration_revenue_recovery { default_imp_for_new_connector_integration_revenue_recovery!( connectors::Trustpayments, connectors::Affirm, + connectors::Paytm, connectors::Vgs, connectors::Airwallex, connectors::Amazonpay, @@ -3651,6 +3700,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Payeezy, connectors::Payload, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Plaid, connectors::Powertranz, @@ -3807,7 +3857,9 @@ default_imp_for_new_connector_integration_external_vault!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Paytm, connectors::Payu, + connectors::Phonepe, connectors::Placetopay, connectors::Powertranz, connectors::Prophetpay, diff --git a/crates/hyperswitch_domain_models/src/connector_endpoints.rs b/crates/hyperswitch_domain_models/src/connector_endpoints.rs index 779ca1e906d..ad80bdb9ea9 100644 --- a/crates/hyperswitch_domain_models/src/connector_endpoints.rs +++ b/crates/hyperswitch_domain_models/src/connector_endpoints.rs @@ -98,7 +98,9 @@ pub struct Connectors { pub payone: ConnectorParams, pub paypal: ConnectorParams, pub paystack: ConnectorParams, + pub paytm: ConnectorParams, pub payu: ConnectorParams, + pub phonepe: ConnectorParams, pub placetopay: ConnectorParams, pub plaid: ConnectorParams, pub powertranz: ConnectorParams, diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs index 801b02c920b..469b27baf8c 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -1071,19 +1071,47 @@ impl Default for RequiredFields { enums::PaymentMethod::Upi, PaymentMethodType(HashMap::from([( enums::PaymentMethodType::UpiCollect, - connectors(vec![( - Connector::Razorpay, - fields( - vec![], - vec![], - vec![ - RequiredField::UpiCollectVpaId, - RequiredField::BillingEmail, - RequiredField::BillingPhone, - RequiredField::BillingPhoneCountryCode, - ], + connectors(vec![ + ( + Connector::Razorpay, + fields( + vec![], + vec![], + vec![ + RequiredField::UpiCollectVpaId, + RequiredField::BillingEmail, + RequiredField::BillingPhone, + RequiredField::BillingPhoneCountryCode, + ], + ), ), - )]), + ( + Connector::Phonepe, + fields( + vec![], + vec![], + vec![ + RequiredField::UpiCollectVpaId, + RequiredField::BillingEmail, + RequiredField::BillingPhone, + RequiredField::BillingPhoneCountryCode, + ], + ), + ), + ( + Connector::Paytm, + fields( + vec![], + vec![], + vec![ + RequiredField::UpiCollectVpaId, + RequiredField::BillingEmail, + RequiredField::BillingPhone, + RequiredField::BillingPhoneCountryCode, + ], + ), + ), + ]), )])), ), ( diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 9399c0d3b3a..6f70c428d8a 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -88,7 +88,7 @@ reqwest = { version = "0.11.27", features = ["json", "rustls-tls", "gzip", "mult ring = "0.17.14" rust_decimal = { version = "1.37.1", features = ["serde-with-float", "serde-with-str"] } rust-i18n = { git = "https://github.com/kashif-m/rust-i18n", rev = "f2d8096aaaff7a87a847c35a5394c269f75e077a" } -unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "a9f7cd96693fa034ea69d8e21125ea0f76182fae", package = "rust-grpc-client" } +unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "0409f6aa1014dd1b9827fabfa4fa424e16d07ebc", package = "rust-grpc-client" } rustc-hash = "1.1.0" rustls = "0.22" rustls-pemfile = "2" diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 2e7303ba93b..a54c1e48401 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -32,18 +32,18 @@ pub use hyperswitch_connectors::connectors::{ novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payload, payload::Payload, payme, payme::Payme, payone, payone::Payone, paypal, paypal::Paypal, paystack, paystack::Paystack, - payu, payu::Payu, placetopay, placetopay::Placetopay, plaid, plaid::Plaid, powertranz, - powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, - razorpay::Razorpay, recurly, recurly::Recurly, redsys, redsys::Redsys, riskified, - riskified::Riskified, santander, santander::Santander, shift4, shift4::Shift4, signifyd, - signifyd::Signifyd, silverflow, silverflow::Silverflow, square, square::Square, stax, - stax::Stax, stripe, stripe::Stripe, stripebilling, stripebilling::Stripebilling, taxjar, - taxjar::Taxjar, threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, - tokenio, tokenio::Tokenio, trustpay, trustpay::Trustpay, trustpayments, - trustpayments::Trustpayments, tsys, tsys::Tsys, unified_authentication_service, - unified_authentication_service::UnifiedAuthenticationService, vgs, vgs::Vgs, volt, volt::Volt, - wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, wellsfargopayout::Wellsfargopayout, wise, - wise::Wise, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, worldpayvantiv, - worldpayvantiv::Worldpayvantiv, worldpayxml, worldpayxml::Worldpayxml, xendit, xendit::Xendit, - zen, zen::Zen, zsl, zsl::Zsl, + paytm, paytm::Paytm, payu, payu::Payu, phonepe, phonepe::Phonepe, placetopay, + placetopay::Placetopay, plaid, plaid::Plaid, powertranz, powertranz::Powertranz, prophetpay, + prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, + recurly::Recurly, redsys, redsys::Redsys, riskified, riskified::Riskified, santander, + santander::Santander, shift4, shift4::Shift4, signifyd, signifyd::Signifyd, silverflow, + silverflow::Silverflow, square, square::Square, stax, stax::Stax, stripe, stripe::Stripe, + stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, threedsecureio, + threedsecureio::Threedsecureio, thunes, thunes::Thunes, tokenio, tokenio::Tokenio, trustpay, + trustpay::Trustpay, trustpayments, trustpayments::Trustpayments, tsys, tsys::Tsys, + unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, + vgs, vgs::Vgs, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, + wellsfargopayout::Wellsfargopayout, wise, wise::Wise, worldline, worldline::Worldline, + worldpay, worldpay::Worldpay, worldpayvantiv, worldpayvantiv::Worldpayvantiv, worldpayxml, + worldpayxml::Worldpayxml, xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, }; diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rs index ccf9ee5e9d8..99b873af1dc 100644 --- a/crates/router/src/core/connector_validation.rs +++ b/crates/router/src/core/connector_validation.rs @@ -522,6 +522,14 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { threedsecureio::transformers::ThreedsecureioAuthType::try_from(self.auth_type)?; Ok(()) } + api_enums::Connector::Phonepe => { + phonepe::transformers::PhonepeAuthType::try_from(self.auth_type)?; + Ok(()) + } + api_enums::Connector::Paytm => { + paytm::transformers::PaytmAuthType::try_from(self.auth_type)?; + Ok(()) + } } } } diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs index 7d19975052b..79dd1cc7013 100644 --- a/crates/router/src/core/unified_connector_service.rs +++ b/crates/router/src/core/unified_connector_service.rs @@ -57,6 +57,16 @@ pub async fn should_call_unified_connector_service<F: Clone, T>( let payment_method = router_data.payment_method.to_string(); let flow_name = get_flow_name::<F>()?; + let is_ucs_only_connector = state + .conf + .grpc_client + .unified_connector_service + .as_ref() + .is_some_and(|config| config.ucs_only_connectors.contains(&connector_name)); + + if is_ucs_only_connector { + return Ok(true); + } let config_key = format!( "{}_{}_{}_{}_{}", consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX, @@ -135,11 +145,9 @@ pub fn build_unified_connector_service_payment_method( let upi_details = payments_grpc::UpiCollect { vpa_id }; PaymentMethod::UpiCollect(upi_details) } - _ => { - return Err(UnifiedConnectorServiceError::NotImplemented(format!( - "Unimplemented payment method subtype: {payment_method_type:?}" - )) - .into()); + hyperswitch_domain_models::payment_method_data::UpiData::UpiIntent(_) => { + let upi_details = payments_grpc::UpiIntent {}; + PaymentMethod::UpiIntent(upi_details) } }; @@ -238,6 +246,112 @@ pub fn handle_unified_connector_service_response_for_payment_authorize( > { let status = AttemptStatus::foreign_try_from(response.status())?; + // <<<<<<< HEAD + // let connector_response_reference_id = + // response.response_ref_id.as_ref().and_then(|identifier| { + // identifier + // .id_type + // .clone() + // .and_then(|id_type| match id_type { + // payments_grpc::identifier::IdType::Id(id) => Some(id), + // payments_grpc::identifier::IdType::EncodedData(encoded_data) => { + // Some(encoded_data) + // } + // payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, + // }) + // }); + + // let transaction_id = response.transaction_id.as_ref().and_then(|id| { + // id.id_type.clone().and_then(|id_type| match id_type { + // payments_grpc::identifier::IdType::Id(id) => Some(id), + // payments_grpc::identifier::IdType::EncodedData(encoded_data) => Some(encoded_data), + // payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None, + // }) + // }); + + // let (connector_metadata, redirection_data) = match response.redirection_data.clone() { + // Some(redirection_data) => match redirection_data.form_type { + // Some(ref form_type) => match form_type { + // payments_grpc::redirect_form::FormType::Uri(uri) => { + // let image_data = QrImage::new_from_data(uri.uri.clone()) + // .change_context(UnifiedConnectorServiceError::ParsingFailed)?; + // let image_data_url = Url::parse(image_data.data.clone().as_str()) + // .change_context(UnifiedConnectorServiceError::ParsingFailed)?; + // let qr_code_info = QrCodeInformation::QrDataUrl { + // image_data_url, + // display_to_timestamp: None, + // }; + // ( + // Some(qr_code_info.encode_to_value()) + // .transpose() + // .change_context(UnifiedConnectorServiceError::ParsingFailed)?, + // None, + // ) + // } + // _ => ( + // None, + // Some(RedirectForm::foreign_try_from(redirection_data)).transpose()?, + // ), + // }, + // None => (None, None), + // }, + // None => (None, None), + // }; + + // let router_data_response = match status { + // AttemptStatus::Charged | + // AttemptStatus::Authorized | + // AttemptStatus::AuthenticationPending | + // AttemptStatus::DeviceDataCollectionPending | + // AttemptStatus::Started | + // AttemptStatus::AuthenticationSuccessful | + // AttemptStatus::Authorizing | + // AttemptStatus::ConfirmationAwaited | + // AttemptStatus::Pending => Ok(PaymentsResponseData::TransactionResponse { + // resource_id: match transaction_id.as_ref() { + // Some(transaction_id) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(transaction_id.clone()), + // None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId, + // }, + // redirection_data: Box::new( + // redirection_data + // ), + // mandate_reference: Box::new(None), + // connector_metadata, + // network_txn_id: response.network_txn_id.clone(), + // connector_response_reference_id, + // incremental_authorization_allowed: response.incremental_authorization_allowed, + // charges: None, + // }), + // AttemptStatus::AuthenticationFailed + // | AttemptStatus::AuthorizationFailed + // | AttemptStatus::Unresolved + // | AttemptStatus::Failure => Err(ErrorResponse { + // code: response.error_code().to_owned(), + // message: response.error_message().to_owned(), + // reason: Some(response.error_message().to_owned()), + // status_code: 500, + // attempt_status: Some(status), + // connector_transaction_id: connector_response_reference_id, + // network_decline_code: None, + // network_advice_code: None, + // network_error_message: None, + // }), + // AttemptStatus::RouterDeclined | + // AttemptStatus::CodInitiated | + // AttemptStatus::Voided | + // AttemptStatus::VoidInitiated | + // AttemptStatus::CaptureInitiated | + // AttemptStatus::VoidFailed | + // AttemptStatus::AutoRefunded | + // AttemptStatus::PartialCharged | + // AttemptStatus::PartialChargedAndChargeable | + // AttemptStatus::PaymentMethodAwaited | + // AttemptStatus::CaptureFailed | + // AttemptStatus::IntegrityFailure => return Err(UnifiedConnectorServiceError::NotImplemented(format!( + // "AttemptStatus {status:?} is not implemented for Unified Connector Service" + // )).into()), + // }; + // ======= let router_data_response = Result::<PaymentsResponseData, ErrorResponse>::foreign_try_from(response)?; diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs index 719b82ffd12..267896ce8ea 100644 --- a/crates/router/src/core/unified_connector_service/transformers.rs +++ b/crates/router/src/core/unified_connector_service/transformers.rs @@ -1,10 +1,12 @@ use std::collections::HashMap; +use api_models::payments::QrCodeInformation; use common_enums::{AttemptStatus, AuthenticationType}; -use common_utils::request::Method; +use common_utils::{ext_traits::Encode, request::Method}; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use external_services::grpc_client::unified_connector_service::UnifiedConnectorServiceError; +use hyperswitch_connectors::utils::QrImage; use hyperswitch_domain_models::{ router_data::{ErrorResponse, RouterData}, router_flow_types::payments::{Authorize, PSync, SetupMandate}, @@ -14,7 +16,9 @@ use hyperswitch_domain_models::{ router_response_types::{PaymentsResponseData, RedirectForm}, }; use masking::{ExposeInterface, PeekInterface}; +use router_env::tracing; use unified_connector_service_client::payments::{self as payments_grpc, Identifier}; +use url::Url; use crate::{ core::unified_connector_service::build_unified_connector_service_payment_method, @@ -364,6 +368,35 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse> }) }); + let (connector_metadata, redirection_data) = match response.redirection_data.clone() { + Some(redirection_data) => match redirection_data.form_type { + Some(ref form_type) => match form_type { + payments_grpc::redirect_form::FormType::Uri(uri) => { + let image_data = QrImage::new_from_data(uri.uri.clone()) + .change_context(UnifiedConnectorServiceError::ParsingFailed)?; + let image_data_url = Url::parse(image_data.data.clone().as_str()) + .change_context(UnifiedConnectorServiceError::ParsingFailed)?; + let qr_code_info = QrCodeInformation::QrDataUrl { + image_data_url, + display_to_timestamp: None, + }; + ( + Some(qr_code_info.encode_to_value()) + .transpose() + .change_context(UnifiedConnectorServiceError::ParsingFailed)?, + None, + ) + } + _ => ( + None, + Some(RedirectForm::foreign_try_from(redirection_data)).transpose()?, + ), + }, + None => (None, None), + }, + None => (None, None), + }; + let response = if response.error_code.is_some() { Err(ErrorResponse { code: response.error_code().to_owned(), @@ -383,14 +416,10 @@ impl ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse> None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId, }, redirection_data: Box::new( - response - .redirection_data - .clone() - .map(RedirectForm::foreign_try_from) - .transpose()? + redirection_data ), mandate_reference: Box::new(None), - connector_metadata: None, + connector_metadata, network_txn_id: response.network_txn_id.clone(), connector_response_reference_id, incremental_authorization_allowed: response.incremental_authorization_allowed, @@ -907,6 +936,7 @@ impl ForeignTryFrom<payments_grpc::HttpMethod> for Method { type Error = error_stack::Report<UnifiedConnectorServiceError>; fn foreign_try_from(value: payments_grpc::HttpMethod) -> Result<Self, Self::Error> { + tracing::debug!("Converting gRPC HttpMethod: {:?}", value); match value { payments_grpc::HttpMethod::Get => Ok(Self::Get), payments_grpc::HttpMethod::Post => Ok(Self::Post), diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs index 06094e6d865..c4a1f187dd9 100644 --- a/crates/router/src/types/api/connector_mapping.rs +++ b/crates/router/src/types/api/connector_mapping.rs @@ -1,6 +1,7 @@ use std::str::FromStr; use error_stack::{report, ResultExt}; +use hyperswitch_connectors::connectors::{Paytm, Phonepe}; use crate::{ configs::settings::Connectors, @@ -442,6 +443,8 @@ impl ConnectorData { .attach_printable(format!("invalid connector name: {connector_name}"))) .change_context(errors::ApiErrorResponse::InternalServerError) } + enums::Connector::Phonepe => Ok(ConnectorEnum::Old(Box::new(Phonepe::new()))), + enums::Connector::Paytm => Ok(ConnectorEnum::Old(Box::new(Paytm::new()))), }, Err(_) => Err(report!(errors::ConnectorError::InvalidConnectorName) .attach_printable(format!("invalid connector name: {connector_name}"))) diff --git a/crates/router/src/types/connector_transformers.rs b/crates/router/src/types/connector_transformers.rs index 52479a4f031..2563f87191c 100644 --- a/crates/router/src/types/connector_transformers.rs +++ b/crates/router/src/types/connector_transformers.rs @@ -187,6 +187,8 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { message: "Taxjar is not a routable connector".to_string(), })? } + api_enums::Connector::Phonepe => Self::Phonepe, + api_enums::Connector::Paytm => Self::Paytm, }) } } diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index f8a19cad0a6..5189e4cc017 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -87,7 +87,9 @@ mod payme; mod payone; mod paypal; mod paystack; +mod paytm; mod payu; +mod phonepe; mod placetopay; mod plaid; mod powertranz; diff --git a/crates/router/tests/connectors/paytm.rs b/crates/router/tests/connectors/paytm.rs new file mode 100644 index 00000000000..9dc1798a031 --- /dev/null +++ b/crates/router/tests/connectors/paytm.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 PaytmTest; +impl ConnectorActions for PaytmTest {} +impl utils::Connector for PaytmTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Paytm; + utils::construct_connector_data_old( + Box::new(Paytm::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .paytm + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "paytm".to_string() + } +} + +static CONNECTOR: PaytmTest = PaytmTest {}; + +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/phonepe.rs b/crates/router/tests/connectors/phonepe.rs new file mode 100644 index 00000000000..9a4c7f28f1e --- /dev/null +++ b/crates/router/tests/connectors/phonepe.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 PhonepeTest; +impl ConnectorActions for PhonepeTest {} +impl utils::Connector for PhonepeTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Phonepe; + utils::construct_connector_data_old( + Box::new(Phonepe::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .phonepe + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "phonepe".to_string() + } +} + +static CONNECTOR: PhonepeTest = PhonepeTest {}; + +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/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index c8a2dffbe6c..b14a190bd67 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -94,7 +94,9 @@ pub struct ConnectorAuthentication { pub payone: Option<HeaderKey>, pub paypal: Option<BodyKey>, pub paystack: Option<HeaderKey>, + pub paytm: Option<HeaderKey>, pub payu: Option<BodyKey>, + pub phonepe: Option<HeaderKey>, pub placetopay: Option<BodyKey>, pub plaid: Option<BodyKey>, pub powertranz: Option<BodyKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 62959cf3aff..197469b68f5 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -169,7 +169,9 @@ 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" +paytm.base_url = "https://securegw-stage.paytm.in/" payu.base_url = "https://secure.snd.payu.com/" +phonepe.base_url = "https://api.phonepe.com/apis/hermes/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" powertranz.base_url = "https://staging.ptranz.com/api/" @@ -397,6 +399,14 @@ sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,GB", currency = "E [pm_filters.razorpay] upi_collect = { country = "IN", currency = "INR" } +[pm_filters.phonepe] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } + +[pm_filters.paytm] +upi_collect = { country = "IN", currency = "INR" } +upi_intent = { country = "IN", currency = "INR" } + [pm_filters.adyen] boleto = { country = "BR", currency = "BRL" } sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR" } diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index eef377ec117..2f56916090b 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 affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay fiserv fiservemea fiuu flexiti forte getnet globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paystack payu placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 silverflow square stax stripe stripebilling taxjar threedsecureio thunes tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") + connectors=(aci adyen adyenplatform affirm airwallex amazonpay applepay archipel authipay authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay blackhawknetwork bluecode bluesnap boku braintree breadpay cashtocode celero chargebee checkbook checkout coinbase cryptopay ctp_visa custombilling cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector dwolla ebanx elavon facilitapay fiserv fiservemea fiuu flexiti forte getnet globalpay globepay gocardless gpayments helcim hipay hyperswitch_vault iatapay inespay itaubank jpmorgan juspaythreedsserver katapult klarna mifinity mollie moneris mpgs multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payload payme payone paypal paystack paytm payu phonepe placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys santander shift4 silverflow square stax stripe stripebilling taxjar threedsecureio thunes tokenio trustpay trustpayments tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayvantiv worldpayxml xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
2025-07-23T12:23:55Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Fixed #8734 ## Description <!-- Describe your changes in detail --> This PR implements UPI Intent and QR code payment flows for the Unified Connector Service (UCS) integration, adding default implementations for Paytm and PhonePe connectors. ### Key Changes: - **Default Connector Implementations**: Added default implementations for Paytm and PhonePe connectors (the actual payment processing integration is handled by UCS) - **UPI Intent Flow**: Implemented UPI Intent payment method support for mobile app integrations through UCS - **QR Code Flow**: Added QR code generation and payment flow support for UPI payments via UCS - **UCS Enhancement**: Extended the Unified Connector Service to route UPI Intent and QR code payment requests - **Configuration**: Added necessary configuration entries for both connectors across all environments - **Testing**: Included test suites for the default implementations **Note**: This PR does not implement direct integrations with Paytm or PhonePe APIs. The actual payment processing and API communication is handled by the Unified Connector Service (UCS). This PR provides the necessary scaffolding and routing logic to support these payment methods through UCS. ### Additional Changes - [x] 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` --> **Configuration changes can be found in:** - `config/development.toml` - `config/deployments/production.toml` - `config/deployments/sandbox.toml` - `config/deployments/integration_test.toml` - `crates/connector_configs/toml/*.toml` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This change enables merchants to accept UPI payments through Paytm and PhonePe payment gateways using the Unified Connector Service. UPI is a crucial payment method in India, and supporting Intent and QR code flows allows for seamless integration across mobile apps and web platforms. The implementation leverages the UCS architecture where: - Hyperswitch provides the routing and orchestration layer - UCS handles the actual integration with Paytm and PhonePe APIs - This PR adds the necessary connector definitions and routing logic to support these payment methods ## 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)? --> ### Automated Tests - Added integration tests for both Paytm and PhonePe default implementations in `crates/router/tests/connectors/` - Tests verify: - Proper routing of payment requests to UCS - UPI Intent payment method handling - QR code flow support - Status sync operations - Refund request routing - Webhook handling - All tests pass successfully with the new implementations ### Manual Testing 1. **Enable UCS configuration:** ```bash curl --location 'http://localhost:8080/configs/' \ --header 'Content-Type: application/json' \ --header 'api-key: [REDACTED]' \ --header 'x-tenant-id: public' \ --data '{ "key": "ucs_enabled", "value": "true" }' ``` 2. **Create a UPI Intent payment request:** ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: [REDACTED]' \ --data-raw '{ "amount": 1000, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "IatapayCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "upi", "payment_method_type": "upi_intent", "payment_method_data": { "upi": { "upi_intent": {} }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "Swangi", "last_name": "Kumari" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" }, "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": "swangi.kumari@juspay.in" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "all_keys_required": true }' ``` 3. **Successful payment response received:** ```json { "payment_id": "pay_XzkwJ5pFVTmuGGAXBy3G", "merchant_id": "merchant_1753180563", "status": "processing", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "phonepe", "client_secret": "[REDACTED]", "created": "2025-07-23T08:36:35.265Z", "currency": "INR", "customer_id": "IatapayCustomer", "customer": { "id": "IatapayCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "upi", "payment_method_data": { "upi": { "upi_intent": {} }, "billing": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "Swangi", "last_name": "Kumari" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" } }, "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": "swangi.kumari@juspay.in" }, "billing": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "swangi.kumari@juspay.in" }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "qr_code_information", "image_data_url": "[REDACTED BASE64 QR CODE DATA]", "display_to_timestamp": null, "qr_code_url": null, "display_text": null, "border_color": null }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "upi_intent", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "IatapayCustomer", "created_at": 1753259795, "expires": 1753263395, "secret": "[REDACTED]" }, "manual_retry_allowed": false, "connector_transaction_id": "pay_XzkwJ5pFVTmuGGAXBy3G_1", "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_XzkwJ5pFVTmuGGAXBy3G_1", "payment_link": null, "profile_id": "pro_aDyARAw6YQZAPr6sqHgi", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_fTVznSS9dGiTX3QEXrg3", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-23T08:51:35.265Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-07-23T08:36:35.797Z", "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, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": "{\"success\":true,\"code\":\"PAYMENT_INITIATED\",\"message\":\"Payment initiated\",\"data\":{\"merchantId\":\"JUSPAONLINE\",\"merchantTransactionId\":\"pay_XzkwJ5pFVTmuGGAXBy3G_1\",\"instrumentResponse\":{\"type\":\"UPI_INTENT\",\"intentUrl\":\"upi://pay?pa=JUSPAONLINE@ybl&pn=Juspay&am=10.00&mam=10.00&tr=OM2507231406356135400588&tn=Payment%20for%20pay_XzkwJ5pFVTmuGGAXBy3G_1&mc=6051&mode=04&purpose=00&utm_campaign=B2B_PG&utm_medium=JUSPAONLINE&utm_source=OM2507231406356135400588\"}}}" } ``` The response shows successful routing through UCS with QR code generation (when invoked from sdk) for UPI payment. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible
v1.115.0
c6e4e7209f2bff0b72e6616f6b02c9996384413c
c6e4e7209f2bff0b72e6616f6b02c9996384413c
juspay/hyperswitch
juspay__hyperswitch-8733
Bug: [BUG] worldpay DDC submission race conditions ### Bug Description Race condition in Worldpay 3DS DDC flow causes `bodyDoesNotMatchSchema` errors. 8-second timeout in `WorldpayDDCForm` JS fires before legitimate DDC completion, sending `collectionReference` to wrong endpoint (`/3dsChallenges` vs `/3dsDeviceData`). ### Expected Behavior DDC `collectionReference` sent to `/3dsDeviceData` endpoint only. Payment state transitions: `DeviceDataCollectionPending` β†’ `AuthenticationPending` β†’ `Charged`. ### Actual Behavior Timeout fires β†’ empty redirect β†’ state advances to `AuthenticationPending` β†’ late `collectionReference` sent to `/3dsChallenges` β†’ Worldpay rejects with `$.collectionReference` validation error. ### Steps To Reproduce 1. Trigger Worldpay 3DS payment with DDC delay >8s 2. Observe timeout in `api.rs:build_redirection_form()` 3. Check logs for missing `PaymentsStart` between redirects 4. Verify `bodyDoesNotMatchSchema` error ### Context For The Bug **File:** `crates/router/src/services/api.rs` **Line:** `window.setTimeout(submitCollectionReference, 8000);` in `WorldpayDDCForm` **Impact:** Intermittent 3DS failures when DDC >8s **Log Evidence:** 11.6s gap between DDC form serve and timeout redirect proves race condition. ### Environment Worldpay connector, 3DS flow with DDC ### 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! --- **Fix Plan:** **Client-side (`api.rs`):** 1. Increase timeout: `8000` β†’ `10000` 2. Add `ddcProcessed` flag to prevent multiple submissions 3. Handle 3 cases: DDC within 10s (normal), DDC never returns (empty submission), DDC after 10s (ignore) **Server-side (`worldpay.rs`):** 1. Accept empty `collectionReference` in `DeviceDataCollectionPending` state 2. Ignore late DDC submissions when already in `AuthenticationPending` state 3. Add validation to prevent sending `collectionReference` to `/3dsChallenges` endpoint
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay.rs b/crates/hyperswitch_connectors/src/connectors/worldpay.rs index 009a02f7ef5..fcb582830b2 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay.rs @@ -798,7 +798,16 @@ impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResp .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?; let stage = match req.status { enums::AttemptStatus::DeviceDataCollectionPending => "3dsDeviceData".to_string(), - _ => "3dsChallenges".to_string(), + enums::AttemptStatus::AuthenticationPending => "3dsChallenges".to_string(), + _ => { + return Err( + errors::ConnectorError::RequestEncodingFailedWithReason(format!( + "Invalid payment status for complete authorize: {:?}", + req.status + )) + .into(), + ); + } }; Ok(format!( "{}api/payments/{connector_payment_id}/{stage}", diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs index 14bcd0afaf5..3a2fe91b231 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs @@ -883,7 +883,29 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for WorldpayCompleteAu .as_ref() .and_then(|redirect_response| redirect_response.params.as_ref()) .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; - serde_urlencoded::from_str::<Self>(params.peek()) - .change_context(errors::ConnectorError::ResponseDeserializationFailed) + + let parsed_request = serde_urlencoded::from_str::<Self>(params.peek()) + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + match item.status { + enums::AttemptStatus::DeviceDataCollectionPending => Ok(parsed_request), + enums::AttemptStatus::AuthenticationPending => { + if parsed_request.collection_reference.is_some() { + return Err(errors::ConnectorError::InvalidDataFormat { + field_name: + "collection_reference not allowed in AuthenticationPending state", + } + .into()); + } + Ok(parsed_request) + } + _ => Err( + errors::ConnectorError::RequestEncodingFailedWithReason(format!( + "Invalid payment status for complete authorize: {:?}", + item.status + )) + .into(), + ), + } } } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 9b6c091a577..f79e6d7f5e9 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1181,7 +1181,7 @@ pub fn build_redirection_form( #loader1 { width: 500px, } - @media max-width: 600px { + @media (max-width: 600px) { #loader1 { width: 200px } @@ -1748,7 +1748,7 @@ pub fn build_redirection_form( #loader1 { width: 500px; } - @media max-width: 600px { + @media (max-width: 600px) { #loader1 { width: 200px; } @@ -1777,7 +1777,21 @@ pub fn build_redirection_form( script { (PreEscaped(format!( r#" + var ddcProcessed = false; + var timeoutHandle = null; + function submitCollectionReference(collectionReference) {{ + if (ddcProcessed) {{ + console.log("DDC already processed, ignoring duplicate submission"); + return; + }} + ddcProcessed = true; + + if (timeoutHandle) {{ + clearTimeout(timeoutHandle); + timeoutHandle = null; + }} + var redirectPathname = window.location.pathname.replace(/payments\/redirect\/([^\/]+)\/([^\/]+)\/[^\/]+/, "payments/$1/$2/redirect/complete/worldpay"); var redirectUrl = window.location.origin + redirectPathname; try {{ @@ -1796,12 +1810,17 @@ pub fn build_redirection_form( window.location.replace(redirectUrl); }} }} catch (error) {{ + console.error("Error submitting DDC:", error); window.location.replace(redirectUrl); }} }} var allowedHost = "{}"; var collectionField = "{}"; window.addEventListener("message", function(event) {{ + if (ddcProcessed) {{ + console.log("DDC already processed, ignoring message event"); + return; + }} if (event.origin === allowedHost) {{ try {{ var data = JSON.parse(event.data); @@ -1821,8 +1840,13 @@ pub fn build_redirection_form( submitCollectionReference(""); }}); - // Redirect within 8 seconds if no collection reference is received - window.setTimeout(submitCollectionReference, 8000); + // Timeout after 10 seconds and will submit empty collection reference + timeoutHandle = window.setTimeout(function() {{ + if (!ddcProcessed) {{ + console.log("DDC timeout reached, submitting empty collection reference"); + submitCollectionReference(""); + }} + }}, 10000); "#, endpoint.host_str().map_or(endpoint.as_ref().split('/').take(3).collect::<Vec<&str>>().join("/"), |host| format!("{}://{}", endpoint.scheme(), host)), collection_id.clone().unwrap_or("".to_string())))
2025-07-24T06:33:20Z
## Type of Change - [x] Bugfix ## Description Fixes race condition in Worldpay 3DS Device Data Collection (DDC) flow causing `bodyDoesNotMatchSchema` errors. **Changes made:** - Extended DDC timeout from 8s to 10s in client-side JavaScript - Added `ddcProcessed` flag to prevent duplicate submissions on client-side - Reject `collectionReference` submissions when payment is in `AuthenticationPending` state - Fixed CSS media query syntax (`@media (max-width: 600px)`) - Added Cypress test case for both client and server-side race conditions for DDC submissions ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context Race condition caused intermittent 3DS payment failures when DDC took > 8 seconds. ## How did you test it? <details> <summary>1. DDC race case in isolation </summary> <img width="797" height="156" alt="Screenshot 2025-07-24 at 12 02 50β€―PM" src="https://github.com/user-attachments/assets/70d14add-9742-4ad3-b72f-da97dae5b197" /> </details> <details> <summary>2. All test cases for Worldpay</summary> <img width="461" height="873" alt="Screenshot 2025-07-25 at 12 52 56β€―AM" src="https://github.com/user-attachments/assets/7458a378-c413-4c8a-9b0d-4c09b2705a41" /> Note - PSync for WP fails due to 404 and WP sending back a HTML rather than a JSON response (https://github.com/juspay/hyperswitch/pull/8753) </details> ## Checklist - [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.115.0
63cc6ae2815c465f6f7ee975a6413d314b5df141
63cc6ae2815c465f6f7ee975a6413d314b5df141
juspay/hyperswitch
juspay__hyperswitch-8723
Bug: Create Authentication Types in Hyperswitch | new doc page I've noticed the community members have been confused by the admin-api and the difference with the hyperswitch api that's given from the control center. This doc explains overview of authentication types and authorization keys available in Hyperswitch.
diff --git a/api-reference/docs.json b/api-reference/docs.json index 9688afc3241..0a15af289c0 100644 --- a/api-reference/docs.json +++ b/api-reference/docs.json @@ -23,6 +23,7 @@ { "group": "Essentials", "pages": [ + "essentials/authentication", "essentials/error_codes", "essentials/rate_limit", "essentials/go-live" diff --git a/api-reference/essentials/authentication.mdx b/api-reference/essentials/authentication.mdx new file mode 100644 index 00000000000..e0e74752878 --- /dev/null +++ b/api-reference/essentials/authentication.mdx @@ -0,0 +1,110 @@ +--- +title: Authentication Types +description: Overview of authentication types and authorization keys available in Hyperswitch. +--- + +import Note from '@site/src/components/Note' +import Table from '@site/src/components/Table' +import Check from '@site/src/components/Check' + +Hyperswitch supports multiple API key types, each designed for different authentication and authorization use cases. + +<Note> +For security, **never expose secret or admin keys in client-side or mobile code**. Use publishable keys for public contexts. +</Note> + +## 1. API Key (Secret Key) + +- **Primary merchant authentication key for server-side API requests.** +- Environment-specific prefix (`snd_`, `prod_`, etc.). +- Used for server to server requests. +- This key can be **generated and managed from the [Hyperswitch dashboard (sandbox)](https://app.hyperswitch.io/developers?tabIndex=1)**. + +- **Never expose this key in public code.** + +## 2. Admin API Key + +- **Administrative key** with elevated privileges. +- Used for system-level operations such as creating merchant and connector accounts. +- Should only be used in secure, internal workflows. +- Some API calls require an admin API key. **Do not confuse this with a regular API Key.** +- The **admin API key is a configuration value that can be set at the time of deploying the Hyperswitch server**. +- **Admin API keys for the hosted Hyperswitch environments (sandbox/production) are managed by Juspay and are not provided publicly.** + +<Check> +You do **not** generate this key from the dashboard. +Instead, **set your Admin API Key in your deployment configuration**: + +**For Docker Compose:** +Update the value in your `docker_compose.toml` file: +</Check> + +```toml +# docker_compose.toml +admin_api_key = "your_admin_key_here" +``` +<Check> **For Helm Chart deployments:** Set the admin API key in your `values.yaml` file. </Check> + +```yaml +# values.yaml +adminApiKey: your_admin_key_here +``` +<Note> Do **not** expose your admin API key publicly. Only trusted entities and trusted applications should have access to this value. </Note> + +Check the Docker Compose example for extra clarity: +[See example in the Hyperswitch repository](https://github.com/juspay/hyperswitch/blob/main/config/docker_compose.toml) + + +## 3. Publishable Key + +- **Client-side key** with limited permissions. +- Safe for use in public client-side (web or mobile) code. +- Prefix: `pk_{environment}_{uuid}`. +- Generated during merchant account creation. + +## 4. Ephemeral Key + +- **Temporary key** for limited operations. +- Used for single or short-lived access (e.g., accessing a specific customer object). +- Validity is configurable (see `[eph_key] validity` in `development.toml`). + +## 5. JWT Key + +- **JWT Bearer Token** used for API authentication and session management. +- Required for certain JWT-protected endpoints and user authentication flows. +- Format: `Authorization: Bearer <jwt_token>` + +### When to Use + +JWT tokens are primarily used by the Hyperswitch Control Center front end to authenticate API requests. You generally do **not** need to manage or use JWTs unless: + +- You’re building a **custom front end** that replaces the Control Center, or +- You’re a developer **testing APIs directly** (e.g., using Postman or running the server without the UI). + +For most users interacting through the Control Center UI, JWTs are handled automatically and do not need to be generated or included manually. + +> **Note:** +> JWTs are **not provisioned via the Hyperswitch dashboard**. +> They are typically **issued during an authentication flow**, such as during login or session creation. + +```http +Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... +``` +<Note> Keep your JWT tokens secure. Do not expose them in client-side code unless specifically required for session management, and always use HTTPS when transmitting JWTs. </Note> + +## Reference Table + +<Table> +| Key Type | Example Prefix | Usage | Security | +|------------------|----------------------|------------------------------|-------------------------| +| Secret (API Key) | snd_c69***, prod_*** | Backend server API requests | Keep secret | +| Admin API Key | (admin-specific) | Admin operations | Highly confidential | +| Publishable Key | pk_snd_3b3*** | Client-side, public usage | Safe to expose | +| Ephemeral Key | (short-lived) | Temporary, limited access | Short validity, limited | +| JWT Key | (JWT Bearer) | Session/user authentication | Control center calls | +</Table> + +<Check> +Get your [API Key](https://app.hyperswitch.io/developers?tabIndex=1) and [Publishable Key](https://app.hyperswitch.io/home) from the Hyperswitch dashboard. +</Check> +--- \ No newline at end of file
2025-07-22T13:46:51Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [x] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. Doc update on admin apis If you don't have an issue, we'd recommend starting with 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 --> - [ ] 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.115.0
38c19f30fce7515869d800bd5cabf3a7dd804e55
38c19f30fce7515869d800bd5cabf3a7dd804e55
juspay/hyperswitch
juspay__hyperswitch-8722
Bug: Update add_connector contributing guide Enrich add_connector contributing guide so anyone can easily build a connector. Right now, details are opaque.
diff --git a/.typos.toml b/.typos.toml index 5fda4c2ad4b..9fb28adc855 100644 --- a/.typos.toml +++ b/.typos.toml @@ -18,6 +18,7 @@ hd = "hd" # animation data parameter HypoNoeLbFurNiederosterreichUWien = "HypoNoeLbFurNiederosterreichUWien" hypo_noe_lb_fur_niederosterreich_u_wien = "hypo_noe_lb_fur_niederosterreich_u_wien" IOT = "IOT" # British Indian Ocean Territory country code +IST = "IST" # Indian Standard Time klick = "klick" # Swedish word for clicks FPR = "FPR" # Fraud Prevention Rules LSO = "LSO" # Lesotho country code diff --git a/add_connector.md b/add_connector.md index 4ee8c895656..9c63f1d2380 100644 --- a/add_connector.md +++ b/add_connector.md @@ -2,98 +2,359 @@ ## Table of Contents -1. [Introduction](#introduction) -2. [Prerequisites](#prerequisites) -3. [Understanding Connectors and Payment Methods](#understanding-connectors-and-payment-methods) -4. [Integration Steps](#integration-steps) - - [Generate Template](#generate-template) - - [Implement Request & Response Types](#implement-request--response-types) - - [Implement transformers.rs](#implementing-transformersrs) - - [Handle Response Mapping](#handle-response-mapping) - - [Recommended Fields for Connector Request and Response](#recommended-fields-for-connector-request-and-response) - - [Error Handling](#error-handling) -5. [Implementing the Traits](#implementing-the-traits) - - [ConnectorCommon](#connectorcommon) - - [ConnectorIntegration](#connectorintegration) - - [ConnectorCommonExt](#connectorcommonext) - - [Other Traits](#othertraits) -6. [Set the Currency Unit](#set-the-currency-unit) -7. [Connector utility functions](#connector-utility-functions) -8. [Connector configs for control center](#connector-configs-for-control-center) -9. [Update `ConnectorTypes.res` and `ConnectorUtils.res`](#update-connectortypesres-and-connectorutilsres) -10. [Add Connector Icon](#add-connector-icon) -11. [Test the Connector](#test-the-connector) -12. [Build Payment Request and Response from JSON Schema](#build-payment-request-and-response-from-json-schema) +1. [Introduction](#introduction) +2. [Prerequisites](#prerequisites) +3. [Development Environment Setup & Configuration](#development-environment-setup--configuration) +4. [Create a Connector](#create-a-connector) +5. [Test the Connection](#test-the-connection) +6. [Folder Structure After Running the Script](#folder-structure-after-running-the-script) +7. [Common Payment Flow Types](#common-payment-flow-types) +8. [Integrate a New Connector](#integrate-a-new-connector) +9. [Code Walkthrough](#code-walkthrough) +10. [Error Handling in Hyperswitch Connectors](#error-handling-in-hyperswitch-connectors) +11. [Implementing the Connector Interface](#implementing-the-connector-interface) +12. [ConnectorCommon: The Foundation Trait](#connectorcommon-the-foundation-trait) +13. [ConnectorIntegration – The Payment Flow Orchestrator](#connectorintegration--the-payment-flow-orchestrator) +14. [Method-by-Method Breakdown](#method-by-method-breakdown) +15. [Connector Traits Overview](#connector-traits-overview) +16. [Derive Traits](#derive-traits) +17. [Connector Utility Functions](#connector-utility-functions) +18. [Connector Configuration for Control Center Integration](#connector-configuration-for-control-center-integration) +19. [Control Center Frontend Integration](#control-center-frontend-integration) +20. [Test the Connector Integration](#test-the-connector-integration) + ## Introduction -This guide provides instructions on integrating a new connector with Router, from setting up the environment to implementing API interactions. +This guide provides instructions on integrating a new connector with Router, from setting up the environment to implementing API interactions. In this document you’ll learn how to: + +* Scaffold a new connector template +* Define Rust request/response types directly from your PSP’s JSON schema +* Implement transformers and the `ConnectorIntegration` trait for both standard auth and tokenization-first flows +* Enforce PII best practices (Secret wrappers, common\_utils::pii types) and robust error-handling +* Update the Control-Center (ConnectorTypes.res, ConnectorUtils.res, icons) +* Validate your connector with end-to-end tests + +By the end, you’ll learn how to create a fully functional, production-ready connectorβ€”from blank slate to live in the Control-Center. ## Prerequisites -- Familiarity with the Connector API you’re integrating -- A locally set up and running Router repository -- API credentials for testing (sign up for sandbox/UAT credentials on the connector’s website). -- Rust nightly toolchain installed for code formatting: - ```bash - rustup toolchain install nightly - ``` +* Before you begin, ensure you’ve completed the initial setup in our [Hyperswitch Contributor Guide](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/docs/CONTRIBUTING.md?plain=1#L1), which covers cloning, tool installation, and access. +* You should also understanding [connectors and payment methods](https://hyperswitch.io/pm-list). +* Familiarity with the Connector API you’re integrating +* A locally set up and running Router repository +* API credentials for testing (sign up for sandbox/UAT credentials on the connector’s website). +* Need help? Join the [Hyperswitch Slack Channel](https://inviter.co/hyperswitch-slack). We also have weekly office hours every Thursday at 8:00 AM PT (11:00 AM ET, 4:00 PM BST, 5:00 PM CEST, and 8:30 PM IST). Link to office hours are shared in the **#general channel**. + +## Development Environment Setup & Configuration + +This guide will walk you through your environment setup and configuration. + +### Clone the Hyperswitch monorepo + +```bash +git clone git@github.com:juspay/hyperswitch.git +cd hyperswitch +``` + +### Rust Environment & Dependencies Setup + +Before running Hyperswitch locally, make sure your Rust environment and system dependencies are properly configured. + +**Follow the guide**: + +[Configure Rust and install required dependencies based on your OS](https://github.com/juspay/hyperswitch/blob/main/docs/try_local_system.md#set-up-a-rust-environment-and-other-dependencies) + +**Quick links by OS**: +* [Ubuntu-based systems](https://github.com/juspay/hyperswitch/blob/main/docs/try_local_system.md#set-up-dependencies-on-ubuntu-based-systems) +* [Windows (WSL2)](https://github.com/juspay/hyperswitch/blob/main/docs/try_local_system.md#set-up-dependencies-on-windows-ubuntu-on-wsl2) +* [Windows (native)](https://github.com/juspay/hyperswitch/blob/main/docs/try_local_system.md#set-up-dependencies-on-windows) +* [macOS](https://github.com/juspay/hyperswitch/blob/main/docs/try_local_system.md#set-up-dependencies-on-macos) + +**All OS Systems**: +* [Set up the database](https://github.com/juspay/hyperswitch/blob/main/docs/try_local_system.md#set-up-the-database) + +* Set up the Rust nightly toolchain installed for code formatting: + +```bash +rustup toolchain install nightly +``` + +* Install [Protobuf](https://protobuf.dev/installation/) + +Install cargo-generate for creating project templates: + +```bash +cargo install cargo-generate +``` + +If you've completed the setup, you should now have: + +* βœ… Rust & Cargo +* βœ… `cargo-generate` +* βœ… PostgreSQL (with a user and database created) +* βœ… Redis +* βœ… `diesel_cli` +* βœ… The `just` command runner +* βœ… Database migrations applied +* βœ… Set up the Rust nightly toolchain +* βœ… Installed Protobuf + +Compile and run the application using cargo: + +```bash +cargo run +``` + +## Create a Connector +From the root of the project, generate a new connector by running the following command. Use a single-word name for your `ConnectorName`: + +```bash +sh scripts/add_connector.sh <ConnectorName> <ConnectorBaseUrl> +``` + +When you run the script, you should see that some files were created + +```bash +# Done! New project created /absolute/path/hyperswitch/crates/hyperswitch_connectors/src/connectors/connectorname +``` + +> ⚠️ **Warning** +> Don’t be alarmed if you see test failures at this stage. +> Tests haven’t been implemented for your new connector yet, so failures are expected. +> You can safely ignore output like this: +> +> ```bash +> test result: FAILED. 0 passed; 20 failed; 0 ignored; 0 measured; 1759 filtered out; finished in 0.10s +> ``` +> You can also ignore GRPC errors too. + +## Test the connection +Once you've successfully created your connector using the `add_connector.sh` script, you can verify the integration by starting the Hyperswitch Router Service: + +```bash +cargo r +``` + +This launches the router application locally on `port 8080`, providing access to the complete Hyperswitch API. You can now test your connector implementation by making HTTP requests to the payment endpoints for operations like: + +- Payment authorization and capture +- Payment synchronization +- Refund processing +- Webhook handling + +Once your connector logic is implemented, this environment lets you ensure it behaves correctly within the Hyperswitch orchestration flowβ€”before moving to staging or production. + +### Verify Server Health -## Understanding Connectors and Payment Methods +Once the Hyperswitch Router Service is running, you can verify it's operational by checking the health endpoint in a separate terminal window: -A **Connector** processes payments (e.g., Stripe, Adyen) or manages fraud risk (e.g., Signifyd). A **Payment Method** is a specific way to transact (e.g., credit card, PayPal). See the [Hyperswitch Payment Matrix](https://hyperswitch.io/pm-list) for details. +```bash +curl --head --request GET 'http://localhost:8080/health' +``` +> **Action Item** +> After creating the connector, run a health check to ensure everything is working smoothly. + +### Folder Structure After Running the Script +When you run the script, it creates a specific folder structure for your new connector. Here's what gets generated: + +**Main Connector Files** + +The script creates the primary connector structure in the hyperswitch_connectors crate: + +crates/hyperswitch_connectors/src/connectors/ +β”œβ”€β”€ <connector_name>/ +β”‚ └── transformers.rs +└── <connector_name>.rs + +#### Test Files + +The script also generates test files in the router crate: + +crates/router/tests/connectors/ +└── <connector_name>.rs + +**What Each File Contains** + +- `<connector_name>.rs`: The main connector implementation file where you implement the connector traits +- `transformers.rs`: Contains data structures and conversion logic between Hyperswitch's internal format and your payment processor's API format +- **Test file**: [Contains boilerplate test cases for your connector](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/connector-template/test.rs#L1-L36). + +## Common Payment Flow Types + +As you build your connector, you’ll encounter different payment flow patterns. +This section gives you: + +- A quick reference table for all flows +- Examples of the two most common patterns: **Tokenization‑first** and **Direct Authorization** + +> For full details, see [Connector Payment Flow documentation](https://docs.hyperswitch.io/learn-more/hyperswitch-architecture/connector-payment-flows) or ask us in Slack. + +--- + +### 1. Flow Summary Table + +| Flow Name | Description | Implementation in Hyperswitch | +|---------------------|--------------------------------------------------|--------------------------------| +| **Access Token** | Obtain OAuth access token | [crates/hyperswitch_interfaces/src/types.rs#L7](https://github.com/juspay/hyperswitch/blob/06dc66c62e33c1c56c42aab18a7959e1648d6fae/crates/hyperswitch_interfaces/src/types.rs#L7) | +| **Tokenization** | Exchange credentials for a payment token | [crates/hyperswitch_interfaces/src/types.rs#L148](https://github.com/juspay/hyperswitch/blob/06dc66c62e33c1c56c42aab18a7959e1648d6fae/crates/hyperswitch_interfaces/src/types.rs#L148) | +| **Customer Creation** | Create or update customer records | [crates/router/src/types.rs#L40](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/router/src/types.rs#L40) | +| **Pre‑Processing** | Validation or enrichment before auth | [crates/router/src/types.rs#L41](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/router/src/types.rs#L41) | +| **Authorization** | Authorize and immediately capture payment | [crates/hyperswitch_interfaces/src/types.rs#L12](https://github.com/juspay/hyperswitch/blob/06dc66c62e33c1c56c42aab18a7959e1648d6fae/crates/hyperswitch_interfaces/src/types.rs#L12) | +| **Authorization‑Only**| Authorize payment for later capture | [crates/router/src/types.rs#L39](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/router/src/types.rs#L39) | +| **Capture** | Capture a previously authorized payment | [crates/router/src/types.rs#L39](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/router/src/types.rs#L39) | +| **Refund** | Issue a refund | [crates/router/src/types.rs#L44](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/router/src/types.rs#L44) | +| **Webhook Handling** | Process asynchronous events from PSP | [crates/router/src/types.rs#L45](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/router/src/types.rs#L45) | + +--- +### Flow Type Definitions + +Each flow type corresponds to specific request/response data structures and connector integration patterns. All flows follow a standardized pattern with associated: + +- **Request data types** (e.g., `PaymentsAuthorizeData`) +- **Response data types** (e.g., `PaymentsResponseData`) +- **Router data wrappers** for connector communication + +### 2. Pattern: Tokenization‑First + +Some PSPs require payment data to be tokenized before it can be authorized. +This is a **two‑step process**: + +1. **Tokenization** – e.g., Billwerk’s implementation: + - [Tokenization](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L178-L271) + - [Authorization](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L273-L366) -## Integration Steps +2. **Authorization** – Uses the returned token rather than raw payment details. + +> Most PSPs don’t require this; see the next section for direct authorization. + +--- + +### 3. Pattern: Direct Authorization + +Many connectors skip tokenization and send payment data directly in the authorization request. + +- **Authorize.net** – [code](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs#L401-L497) + Builds `CreateTransactionRequest` directly from payment data in `get_request_body()`. + +- **Helcim** – [code](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/helcim.rs#L295-L385) + Chooses purchase (auto‑capture) or preauth endpoint in `get_url()` and processes payment data directly. + +- **Deutsche Bank** – [code](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/deutschebank.rs#L330-L461) + Selects flow based on 3DS and payment type (card or direct debit). + +**Key differences from tokenization‑first:** +- Single API call – No separate token step +- No token storage – No token management required +- Immediate processing – `get_request_body()` handles payment data directly + +All implement the same `ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>` pattern. + +## Integrate a New Connector Integrating a connector is mainly an API integration task. You'll define request and response types and implement required traits. -This tutorial covers card payments via [Billwerk](https://optimize-docs.billwerk.com/). Review the API reference and test APIs before starting. +This section covers card payments via Billwerk. Review the API reference and test APIs before starting. You can leverage these examples for your connector of choice. -Follow these steps to integrate a new connector. +### 1. Build Payment Request and Response from JSON Schema -### Generate Template +To generate Rust types from your connector’s OpenAPI or JSON schema, you’ll need to install the [OpenAPI Generator](https://openapi-generator.tech/). -Run the following script to create the connector structure: +### Example (macOS using Homebrew): ```bash -sh scripts/add_connector.sh <connector-name> <connector-base-url> +brew install openapi-generator ``` +> πŸ’‘ **Note:** +> On **Linux**, you can install OpenAPI Generator using `apt`, `snap`, or by downloading the JAR from the [official site](https://openapi-generator.tech/docs/installation). +> On **Windows**, use [Scoop](https://scoop.sh/) or manually download the JAR file. + +### 2. **Download the OpenAPI Specification from your connector** -Example folder structure: +First, obtain the OpenAPI specification from your payment processor's developer documentation. Most processors provide these specifications at standardized endpoints. +```bash +curl -o <ConnectorName>-openapi.json <schema-url> ``` -hyperswitch_connectors/src/connectors -β”œβ”€β”€ billwerk -β”‚ └── transformers.rs -└── billwerk.rs -crates/router/tests/connectors -└── billwerk.rs +**Specific Example**: + +For Billwerk (using their sandbox environment): + +```bash +curl -o billwerk-openapi.json https://sandbox.billwerk.com/swagger/v1/swagger.json ``` +For other connectors, check their developer documentation for similar endpoints like: + +- `/swagger/v1/swagger.json` +- `/openapi.json` +- `/api-docs` + +After running the complete command, you'll have: + +`crates/hyperswitch_connectors/src/connectors/{CONNECTORNAME}/temp.rs ` + +This single file contains all the Rust structs and types generated from your payment processor's OpenAPI specification. + +The generated `temp.rs` file typically contains: + +- **Request structs**: Data structures for API requests +- **Response structs**: Data structures for API responses +- **Enum types**: Status codes, payment methods, error types +- **Nested objects**: Complex data structures used within requests/responses +- **Serde annotations**: Serialization/deserialization attributes. + +Otherwise, you can manually define it and create the `crates/hyperswitch_connectors/src/connectors/{CONNECTOR_NAME}/temp.rs ` file. We highly recommend using the `openapi-generator` for ease. + +#### Usage in Connector Development + +You can then copy and adapt these generated structs into your connector's `transformers.rs` file, following the pattern shown in the connector integration documentation. The generated code serves as a starting point that you customize for your specific connector implementation needs. -**Note:** move the file `crates/hyperswitch_connectors/src/connectors/connector_name/test.rs` to `crates/router/tests/connectors/connector_name.rs` +### 3. **Configure Required Environment Variables** +Set up the necessary environment variables for the OpenAPI generation process: -Define API request/response types and conversions in `hyperswitch_connectors/src/connector/billwerk/transformers.rs` +#### Connector name (must match the name used in add_connector.sh script) -Implement connector traits in `hyperswitch_connectors/src/connector/billwerk.rs` +```bash +export CONNECTOR_NAME="ConnectorName" +``` + +#### Path to the downloaded OpenAPI specification +```bash +export SCHEMA_PATH="/absolute/path/to/your/connector-openapi.json" +``` -Write basic payment flow tests in `crates/router/tests/connectors/billwerk.rs` +## Code Walkthrough -Boilerplate code with todo!() is providedβ€”follow the guide and complete the necessary implementations. +We'll walk through the `transformer.rs` file, and what needs to be implemented. -### Implement Request & Response Types +### 1. **Converts Hyperswitch's internal payment data into your connector's API request format** + This part of the code takes your internal representation of a payment request, pulls out the token, gathers all the customer and payment fields, and packages them into a clean, JSON-serializable struct ready to send to your connector of choice (in this case Billwerk). You'll have to implement the customer and payment fields, as necessary. -Integrating a new connector involves transforming Router's core data into the connector's API format. Since the Connector module is stateless, Router handles data persistence. + The code below extracts customer data and constructs a payment request: -#### Implementing transformers.rs +```rust +//TODO: Fill the struct with respective fields +// Auth Struct -Design request/response structures based on the connector's API spec. +impl TryFrom<&ConnectorAuthType> for NadinebillwerkAuthType { + 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()), + } + } +} -Define request format in `transformers.rs`: +``` +Here's an implementation example with the Billwerk connector: ```rust #[derive(Debug, Serialize)] -pub struct BillwerkCustomerObject { +pub struct NadinebillwerkCustomerObject { handle: Option<id_type::CustomerId>, email: Option<Email>, address: Option<Secret<String>>, @@ -104,35 +365,22 @@ pub struct BillwerkCustomerObject { last_name: Option<Secret<String>>, } -#[derive(Debug, Serialize)] -pub struct BillwerkPaymentsRequest { - handle: String, - amount: MinorUnit, - source: Secret<String>, - currency: common_enums::Currency, - customer: BillwerkCustomerObject, - metadata: Option<SecretSerdeValue>, - settle: bool, -} -``` - -Since Router is connector agnostic, only minimal data is sent to connector and optional fields may be ignored. - -We transform our `PaymentsAuthorizeRouterData` into Billwerk's `PaymentsRequest` structure by employing the `try_from` function. - -```rust -impl TryFrom<&BillwerkRouterData<&types::PaymentsAuthorizeRouterData>> for BillwerkPaymentsRequest { +impl TryFrom<&NadinebillwerkRouterData<&PaymentsAuthorizeRouterData>> + for NadinebillwerkPaymentsRequest +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: &BillwerkRouterData<&types::PaymentsAuthorizeRouterData>, + item: &NadinebillwerkRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { + if item.router_data.is_three_ds() { return Err(errors::ConnectorError::NotImplemented( "Three_ds payments through Billwerk".to_string(), ) .into()); }; - let source = match item.router_data.get_payment_method_token()? { + + let source = match item.router_data.get_payment_method_token()? { PaymentMethodToken::Token(pm_token) => Ok(pm_token), _ => Err(errors::ConnectorError::MissingRequiredField { field_name: "payment_method_token", @@ -143,7 +391,7 @@ impl TryFrom<&BillwerkRouterData<&types::PaymentsAuthorizeRouterData>> for Billw amount: item.amount, source, currency: item.router_data.request.currency, - customer: BillwerkCustomerObject { + customer: NadinebillwerkCustomerObject { handle: item.router_data.customer_id.clone(), email: item.router_data.request.email.clone(), address: item.router_data.get_optional_billing_line1(), @@ -160,9 +408,13 @@ impl TryFrom<&BillwerkRouterData<&types::PaymentsAuthorizeRouterData>> for Billw } ``` -### Handle Response Mapping +2. **Handle Response Mapping** + +Response mapping is a critical component of connector implementation that translates payment processor–specific statuses into Hyperswitch’s standardized internal representation. This ensures consistent payment state management across all integrated payment processors. + +**Define Payment Status Enum** -When implementing the response type, the key enum to define for each connector is `PaymentStatus`. It represents the different status types returned by the connector, as specified in its API spec. Below is the definition for Billwerk. +Create an enum that represents all possible payment statuses returned by your payment processor’s API. This enum should match the exact status values specified in your connector’s API documentation. ```rust #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -175,6 +427,24 @@ pub enum BillwerkPaymentState { Failed, Cancelled, } +``` +The enum uses `#[serde(rename_all = "lowercase")]` to automatically handle JSON serialization/deserialization in the connector’s expected format. + +**Implement Status Conversion** + +Implement From <ConnectorStatus> for Hyperswitch’s `AttemptStatus` enum. Below is an example implementation: + +```rs +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum BillwerkPaymentState { + Created, + Authorized, + Pending, + Settled, + Failed, + Cancelled, +} impl From<BillwerkPaymentState> for enums::AttemptStatus { fn from(item: BillwerkPaymentState) -> Self { @@ -187,22 +457,26 @@ impl From<BillwerkPaymentState> for enums::AttemptStatus { } } } + ``` -Here are common payment attempt statuses: +| Connector Status | Hyperswitch Status | Description | +|------------------------|-------------------------------|--------------------------------------| +| `Created`, `Pending` | `AttemptStatus::Pending` | Payment is being processed | +| `Authorized` | `AttemptStatus::Authorized` | Payment authorized, awaiting capture | +| `Settled` | `AttemptStatus::Charged` | Payment successfully completed | +| `Failed` | `AttemptStatus::Failure` | Payment failed or was declined | +| `Cancelled` | `AttemptStatus::Voided` | Payment was cancelled/voided | -- **Charged:** Payment succeeded. -- **Pending:** Payment is processing. -- **Failure:** Payment failed. -- **Authorized:** Payment authorized; can be voided, captured, or partially captured. -- **AuthenticationPending:** Customer action required. -- **Voided:** Payment voided, funds returned to the customer. +> **Note:** Default status should be `Pending`. Only explicit success or failure from the connector should mark the payment as `Charged` or `Failure`. -**Note:** Default status should be `Pending`. Only explicit success or failure from the connector should mark the payment as `Charged` or `Failure`. +3. **Mapping Billwerk API Responses (or any PSPs) to Hyperswitch Internal Specification** -Define response format in `transformers.rs`: +Billwerk, like most payment service providers (PSPs), has its own proprietary API response format with custom fields, naming conventions, and nested structures. However, Hyperswitch is designed to be connector-agnostic: it expects all connectors to normalize external data into a consistent internal format, so it can process payments uniformly across all supported PSPs. -```rust +The response struct acts as the translator between these two systems. This process ensures that regardless of which connector you're using, Hyperswitch can process payment responses consistently. + +```rs #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct BillwerkPaymentsResponse { state: BillwerkPaymentState, @@ -211,10 +485,16 @@ pub struct BillwerkPaymentsResponse { error_state: Option<String>, } ``` +**Key Fields Explained**: -We transform our `ResponseRouterData` into `PaymentsResponseData` by employing the `try_from` function. +- **state**: Payment status using the enum we defined earlier +- **handle**: Billwerk's unique transaction identifier +- **error & error_state**: Optional error information for failure scenarios -```rust + +The `try_from` function converts connector-specific, like Billwerk, response data into Hyperswitch's standardized format: + +```rs impl<F, T> TryFrom<ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { @@ -260,111 +540,100 @@ impl<F, T> TryFrom<ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsRe } } ``` +### Transformation Logic: -### Recommended Fields for Connector Request and Response +- **Error Handling**: Checks for error conditions first and creates appropriate error responses +- **Status Mapping**: Converts BillwerkPaymentState to standardized AttemptStatus using our enum mapping +- **Data Extraction**: Maps PSP-specific fields to Hyperswitch's PaymentsResponseData structure +- **Metadata Preservation**: Ensures important transaction details are retained -- **connector_request_reference_id:** Merchant's reference ID in the payment request (e.g., `reference` in Checkout). +#### Critical Response Fields -```rust - reference: item.router_data.connector_request_reference_id.clone(), -``` -- **connector_response_reference_id:** ID used for transaction identification in the connector dashboard, linked to merchant_reference or connector_transaction_id. +The transformation populates these essential Hyperswitch fields: -```rust - connector_response_reference_id: item.response.reference.or(Some(item.response.id)), -``` +- **resource_id**: Maps to connector transaction ID for future operations +- **connector_response_reference_id**: Preserves PSP's reference for dashboard linking +- **status**: Standardized payment status for consistent processing +- **redirection_data**: Handles 3DS or other redirect flows +- **network_txn_id**: Captures network-level transaction identifiers -- **resource_id:** The connector's connector_transaction_id is used as the resource_id. If unavailable, set to NoResponseId. -```rust - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), -``` +### Field Mapping Patterns: -- **redirection_data:** For redirection flows (e.g., 3D Secure), assign the redirection link. +Each critical response field requires specific implementation patterns to ensure consistent behavior across all Hyperswitch connectors. -```rust - let redirection_data = item.response.links.redirect.map(|href| { - services::RedirectForm::from((href.redirection_url, services::Method::Get)) - }); +- **connector_request_reference_id**: This field carries the merchant’s reference ID and is populated during request construction. It is sent to the PSP to support end-to-end transaction traceability. + +```rs +reference: item.router_data.connector_request_reference_id.clone(), ``` -### Error Handling +- **connector_response_reference_id**: Stores the payment processor’s transaction reference and is used for downstream reconciliation and dashboard visibility. Prefer the PSP's designated reference field if available; otherwise, fall back to the transaction ID. This ensures accurate linkage across merchant dashboards, support tools, and internal systems. -Define error responses: -```rust -#[derive(Debug, Serialize, Deserialize)] -pub struct BillwerkErrorResponse { - pub code: Option<i32>, - pub error: String, - pub message: Option<String>, -} +```rs +connector_response_reference_id: item.response.reference.or(Some(item.response.id)), ``` -By following these steps, you can integrate a new connector efficiently while ensuring compatibility with Router's architecture. +- **resource_id**: Defines the primary resource identifier used for subsequent operations such as captures, refunds, and syncs. Typically sourced from the connector’s transaction ID. If the transaction ID is unavailable, use ResponseId::NoResponseId as a fallback to preserve type safety. -## Implementing the Traits - -The `mod.rs` file contains trait implementations using connector types in transformers. A struct with the connector name holds these implementations. Below are the mandatory traits: +```rs +`resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), +``` -### ConnectorCommon -Contains common description of the connector, like the base endpoint, content-type, error response handling, id, currency unit. +- **redirection_data**: Captures redirection details required for authentication flows such as 3DS. If the connector provides a redirect URL, populate this field accordingly. For advanced flows involving form submissions, construct a `RedirectForm::Form` using the target endpoint, HTTP method, and form fields. -Within the `ConnectorCommon` trait, you'll find the following methods : +```rs +let redirection_data = item.response.links.redirect.map(|href| { + services::RedirectForm::from((href.redirection_url, services::Method::Get)) +}); +``` -- `id` method corresponds directly to the connector name. +- **network_txn_id**: Stores the transaction identifier issued by the underlying payment network (e.g., Visa, Mastercard). This field is optional but highly useful for advanced reconciliation, chargeback handling, and network-level dispute resolutionβ€”especially when the network ID differs from the PSP’s transaction ID. -```rust - fn id(&self) -> &'static str { - "Billwerk" - } +```rs +network_txn_id: item.response.network_transaction_id.clone(), ``` -- `get_currency_unit` method anticipates you to [specify the accepted currency unit](#set-the-currency-unit) for the connector. +4. **Error Handling in Hyperswitch Connectors** -```rust - fn get_currency_unit(&self) -> api::CurrencyUnit { - api::CurrencyUnit::Minor - } -``` +Hyperswitch connectors implement a structured error-handling mechanism that categorizes HTTP error responses by type. By distinguishing between client-side errors (4xx) and server-side errors (5xx), the system enables more precise handling strategies tailored to the source of the failure. -- `common_get_content_type` method requires you to provide the accepted content type for the connector API. +**Error Response Structure** -```rust - fn common_get_content_type(&self) -> &'static str { - "application/json" - } +Billwerk defines its error response format to capture failure information from API calls. You can find this in the `transformer.rs file`: + +```rs +#[derive(Debug, Serialize, Deserialize)] +pub struct BillwerkErrorResponse { + pub code: Option<i32>, + pub error: String, + pub message: Option<String>, +} ``` -- `get_auth_header` method accepts common HTTP Authorization headers that are accepted in all `ConnectorIntegration` flows. +- **code**: Optional integer error code from Billwerk +- **error**: Required string describing the error +- **message**: Optional additional error messagecode: Optional integer error code from Billwerk +- **error**: Required string describing the error +message: Optional additional error message -```rust - fn get_auth_header( - &self, - auth_type: &ConnectorAuthType, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - let auth = BillwerkAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - let encoded_api_key = BASE64_ENGINE.encode(format!("{}:", auth.api_key.peek())); - Ok(vec![( - headers::AUTHORIZATION.to_string(), - format!("Basic {encoded_api_key}").into_masked(), - )]) - } -``` +**Error Handling Methods** -- `base_url` method is for fetching the base URL of connector's API. Base url needs to be consumed from configs. +Hyperswitch uses separate methods for different HTTP error types: -```rust - fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { - connectors.billwerk.base_url.as_ref() - } -``` +- **4xx Client Errors**: [`get_error_response`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L692) handles authentication failures, validation errors, and malformed requests. +- **5xx Server Errors**: +[`get_5xx_error_response`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L700) handles internal server errors with potential retry logic. -- `build_error_response` method is common error response handling for a connector if it is same in all cases +Both methods delegate to [`build_error_response`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L136) for consistent processing. -```rust - fn build_error_response( +**Error Processing Flow** + +The [`build_error_response`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L136) struct serves as the intermediate data structure that bridges Billwerk's API error format and Hyperswitch's standardized error format by taking the `BillwerkErrorResponse` struct as input: + +```rs +fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, @@ -386,335 +655,602 @@ Within the `ConnectorCommon` trait, you'll find the following methods : reason: Some(response.error), attempt_status: None, connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, }) } +} ``` +The method performs these key operations: -### ConnectorIntegration -For every api endpoint contains the url, using request transform and response transform and headers. -Within the `ConnectorIntegration` trait, you'll find the following methods implemented(below mentioned is example for authorized flow): +- Parses the HTTP response - Deserializes the raw HTTP response into a BillwerkErrorResponse struct using `parse_struct("BillwerkErrorResponse")` -- `get_url` method defines endpoint for authorize flow, base url is consumed from `ConnectorCommon` trait. +- Logs the response - Records the connector response for debugging via `event_builder` and `router_env::logger::info!` -```rust - fn get_url( - &self, - _req: &TokenizationRouterData, - connectors: &Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - let base_url = connectors - .billwerk - .secondary_base_url - .as_ref() - .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?; - Ok(format!("{base_url}v1/token")) - } +- Transforms error format - Maps Billwerk's error fields to Hyperswitch's standardized `ErrorResponse` structure with appropriate fallbacks: +- - Uses `response.code` maps to `code` (with `NO_ERROR_CODE fallback`) +- - Uses `response.message` maps to `message` (with `NO_ERROR_MESSAGE fallback`) +- - Maps `response.error` to the `reason` field + +> [!NOTE] +> When the connector provides only a single error message field, populate both the `message` and `reason` fields in the `ErrorResponse` with the same value. The `message` field is used for smart retries logic, while the `reason` field is displayed on the Hyperswitch dashboard. + + +### Automatic Error Routing + +Hyperswitch's core API automatically routes errors based on HTTP status codes. You can find the details here: [`crates/router/src/services/api.rs`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/router/src/services/api.rs#L1). + +- 4xx β†’ [`get_error_response`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L256) +- 5xx β†’ [`get_5xx_error_response`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L264) +- 2xx β†’ [`handle_response`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L332) + + +### Integration Pattern + +The `BillwerkErrorResponse` struct serves as the intermediate data structure that bridges Billwerk's API error format and Hyperswitch's internal error representation. The method essentially consumes the struct and produces Hyperswitch's standardized error format. All connectors implement a similar pattern to ensure uniform error handling. + +## Implementing the Connector Interface +The connector interface implementation follows an architectural pattern that separates concerns between data transformation and interface compliance. + + +- `transformers.rs` - This file is generated from `add_connector.sh` and defines the data structures and conversion logic for PSP-specific formats. This is where most of your custom connector implementation work happens. + +- `mod.rs` - This file implements the standardized Hyperswitch connector interface using the transformers. + +### The `mod.rs` Implementation Pattern +The file creates the bridge between the data transformation logic (defined in `transformers.rs`) and the connector interface requirements. It serves as the main connector implementation file that brings together all the components defined in the transformers module and implements all the required traits for payment processing. Looking at the connector template structure [`connector-template/mod.rs:54-67`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/connector-template/mod.rs#L54-L67), you can see how it: + +- **Imports the transformers module** - Brings in your PSP-specific types and conversion logic +```rs +use transformers as {{project-name | downcase}}; ``` -- `get_headers` method accepts HTTP headers that are accepted for authorize flow. In this context, it is utilized from the `ConnectorCommonExt` trait, as the connector adheres to common headers across various flows. +- **Creates the main connector struct** - A struct named after your connector that holds the implementation +```rs +#[derive(Clone)] +pub struct {{project-name | downcase | pascal_case}} { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync) +} -```rust - fn get_headers( - &self, - req: &TokenizationRouterData, - connectors: &Connectors, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) +impl {{project-name | downcase | pascal_case}} { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector + } } +} ``` -- `get_request_body` method uses transformers to convert the Hyperswitch payment request to the connector's format. If successful, it returns the request as `RequestContent::Json`, supporting formats like JSON, form-urlencoded, XML, and raw bytes. +- **Implements required traits** - Provides the standardized methods Hyperswitch expects +```rs +impl ConnectorCommon for {{project-name | downcase | pascal_case}} { + fn id(&self) -> &'static str { + "{{project-name | downcase}}" + } -```rust - fn get_request_body( - &self, - req: &TokenizationRouterData, - _connectors: &Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = BillwerkTokenRequest::try_from(req)?; - Ok(RequestContent::Json(Box::new(connector_req))) + fn get_currency_unit(&self) -> api::CurrencyUnit { + todo!() + + // TODO! Check connector documentation, on which unit they are processing the currency. + // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, + // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base } -``` -- `build_request` method assembles the API request by providing the method, URL, headers, and request body as parameters. + fn common_get_content_type(&self) -> &'static str { + "application/json" + } -```rust - fn build_request( - &self, - req: &TokenizationRouterData, - connectors: &Connectors, - ) -> CustomResult<Option<Request>, errors::ConnectorError> { - Ok(Some( - RequestBuilder::new() - .method(Method::Post) - .url(&types::TokenizationType::get_url(self, req, connectors)?) - .attach_default_headers() - .headers(types::TokenizationType::get_headers(self, req, connectors)?) - .set_body(types::TokenizationType::get_request_body( - self, req, connectors, - )?) - .build(), - )) + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.{{project-name}}.base_url.as_ref() } -``` -- `handle_response` method calls transformers where connector response data is transformed into hyperswitch response. + fn get_auth_header(&self, auth_type:&ConnectorAuthType)-> CustomResult<Vec<(String,masking::Maskable<String>)>,errors::ConnectorError> { + let auth = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}AuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key.expose().into_masked())]) + } -```rust - fn handle_response( + fn build_error_response( &self, - data: &TokenizationRouterData, - event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<TokenizationRouterData, errors::ConnectorError> - where - PaymentsResponseData: Clone, - { - let response: BillwerkTokenResponse = res + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: {{project-name | downcase}}::{{project-name | downcase | pascal_case}}ErrorResponse = res .response - .parse_struct("BillwerkTokenResponse") + .parse_struct("{{project-name | downcase | pascal_case}}ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - RouterData::try_from(ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, + + Ok(ErrorResponse { + status_code: res.status_code, + code: response.code, + message: response.message, + reason: response.reason, + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) } +} ``` -- `get_error_response` method to manage error responses. As the handling of checkout errors remains consistent across various flows, we've incorporated it from the `build_error_response` method within the `ConnectorCommon` trait. +## ConnectorCommon: The Foundation Trait +The `ConnectorCommon` trait defines the standardized interface required by Hyperswitch (as outlined in [`crates/hyperswitch_interfaces/src/api.rs`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_interfaces/src/api.rs#L326-L374) and acts as the bridge to your PSP-specific logic in `transformers.rs`. The `connector-template/mod.rs` file implements this trait using the data types and transformation functions from `transformers.rs`. This allows Hyperswitch to interact with your connector in a consistent, processor-agnostic manner. Every connector must implement the `ConnectorCommon` trait, which provides essential connector properties: -```rust - fn get_error_response( +### Core Methods You'll Implement + +- `id()` - Your connector's unique identifier +```rs +fn id(&self) -> &'static str { + "Billwerk" + } +``` + +- `get_currency_unit()` - Whether you handle amounts in base units (dollars) or minor units (cents). +```rs + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + } + ``` + +- `base_url()` - This fetches your PSP's API endpoint +```rs + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.billwerk.base_url.as_ref() + } +``` + +- `get_auth_header()` - How to authenticate with your PSP +```rs + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = BillwerkAuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let encoded_api_key = BASE64_ENGINE.encode(format!("{}:", auth.api_key.peek())); + Ok(vec![( + headers::AUTHORIZATION.to_string(), + format!("Basic {encoded_api_key}").into_masked(), + )]) + } +``` + +- `build_error_response()` - How to transform your PSP's errors into Hyperswitch's format +```rs +fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -``` + let response: BillwerkErrorResponse = res + .response + .parse_struct("BillwerkErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; -### ConnectorCommonExt -Adds functions with a generic type, including the `build_headers` method. This method constructs both common headers and Authorization headers (from `get_auth_header`), returning them as a vector. + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); -```rust - impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Billwerk - 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) - } + Ok(ErrorResponse { + status_code: res.status_code, + code: response + .code + .map_or(NO_ERROR_CODE.to_string(), |code| code.to_string()), + message: response.message.unwrap_or(NO_ERROR_MESSAGE.to_string()), + reason: Some(response.error), + attempt_status: None, + connector_transaction_id: None, + }) } ``` -### OtherTraits -**Payment :** This trait includes several other traits and is meant to represent the functionality related to payments. +## `ConnectorIntegration` - The Payment Flow Orchestrator +The `ConnectorIntegration` trait serves as the central coordinator that bridges three key files in Hyperswitch's connector architecture: -**PaymentAuthorize :** This trait extends the `api::ConnectorIntegration `trait with specific types related to payment authorization. +- **Defined in `api.rs`** + [`crates/hyperswitch_interfaces/src/api.rs:150–153`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_interfaces/src/api.rs#L156-%23L159) + Provides the standardized interface contracts for connector integration. -**PaymentCapture :** This trait extends the `api::ConnectorIntegration `trait with specific types related to manual payment capture. +- **Implemented in `mod.rs`** + Each connector’s main file (`mod.rs`) implements the trait methods for specific payment flows like authorize, capture, refund, etc. You can see how the Tsys connector implements [ConnectorIntegration](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/tsys.rs#L219) -**PaymentSync :** This trait extends the `api::ConnectorIntegration `trait with specific types related to payment retrieve. +- **Uses types from `transformers.rs`** + Contains PSP-specific request/response structs and `TryFrom` implementations that convert between Hyperswitch's internal `RouterData` format and the PSP's API format. This is where most connector-specific logic lives. -**Refund :** This trait includes several other traits and is meant to represent the functionality related to Refunds. +This orchestration enables seamless translation between Hyperswitch’s internal data structures and each payment service provider’s unique API requirements. -**RefundExecute :** This trait extends the `api::ConnectorIntegration `trait with specific types related to refunds create. +## Method-by-Method Breakdown -**RefundSync :** This trait extends the `api::ConnectorIntegration `trait with specific types related to refunds retrieve. +### Request/Response Flow +These methods work together in sequence: +1. `get_url()` and `get_headers()` prepare the endpoint and authentication +2. `get_request_body()` transforms Hyperswitch data using transformers.rs +3. `build_request()` assembles the complete HTTP request +4. `handle_response()` processes the PSP response back to Hyperswitch format +5. `get_error_response()` handles any error conditions -And the below derive traits +Here are more examples around these methods in the Billwerk connector: +- **`get_url()`** + Constructs API endpoints by combining base URLs (from `ConnectorCommon`) with specific paths. In the Billwerk connector, it reads the connector’s base URL from config and appends the tokenization path. [Here's 1 example](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L193-L204). -- **Debug** -- **Clone** -- **Copy** +- **`get_headers()`** + Here's an example of [get_headers](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L618). It delegates to [`build_headers()`](https://github.com/juspay/hyperswitch/blob/06dc66c62e33c1c56c42aab18a7959e1648d6fae/crates/hyperswitch_interfaces/src/api.rs#L422-L430) across all connector implementations. -### **Set the currency Unit** +- **`get_request_body()`** + Uses the `TryFrom` implementations in [billwerk.rs](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L206-L213). It creates the connector request via `BillwerkTokenRequest::try_from(req)?` to transform the tokenization router data and it +returns as `RequestContent:` by wrapping it in a JSON via `RequestContent::Json(Box::new(connector_req))` -Part of the `ConnectorCommon` trait, it allows connectors to specify their accepted currency unit as either `Base` or `Minor`. For example, PayPal uses the base unit (e.g., USD), while Hyperswitch uses the minor unit (e.g., cents). Conversion is required if the connector uses the base unit. +- **`build_request()`** + Orchestrates `get_url()`, `get_headers()`, and `get_request_body()` to assemble the complete HTTP request via a `RequestBuilder`. For example, you can review the Billwerk connector's [`build_request()`](https://github.com/juspay/hyperswitch/blob/b133c534fb1ce40bd6cca27fac4f2d58b0863e30/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L215-L231) implementation. -```rust -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for PaypalRouterData<T> -{ - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), - ) -> Result<Self, Self::Error> { - let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; - Ok(Self { - amount, - router_data: item, - }) - } -} -``` +- **`handle_response()`** + You can see an example of this here: [`billwerk.rs`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L332). In this example, it parses the raw response into `BillwerkTokenResponse` using `res.response.parse_struct()`, logs the response with an `event_builder.map(|i| i.set_response_body(&response))`, finally it +transforms back to `RouterData` using `RouterData::try_from(ResponseRouterData {...}) `. -### **Connector utility functions** +- **`get_error_response()`** + Here's an example of [get_error_response](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L256) in `billewerk.rs`. It delegates to [`build_error_response()`](https://github.com/juspay/hyperswitch/blob/b133c534fb1ce40bd6cca27fac4f2d58b0863e30/crates/hyperswitch_connectors/src/connectors/billwerk.rs#L136-L162) from the `ConnectorCommon` trait, providing uniform handling for all connector 4xx errors. -Contains utility functions for constructing connector requests and responses. Use these helpers for retrieving fields like `get_billing_country`, `get_browser_info`, and `get_expiry_date_as_yyyymm`, as well as for validations like `is_three_ds` and `is_auto_capture`. -```rust - let json_wallet_data: CheckoutGooglePayData = wallet_data.get_wallet_token_as_json()?; +### `ConnectorCommonExt` - Generic Helper Methods +The [`ConnectorCommonExt`](https://github.com/juspay/hyperswitch/blob/06dc66c6/crates/hyperswitch_interfaces/src/api.rs#L418-L441) trait serves as an extension layer for the core `ConnectorCommon` trait, providing generic methods that work across different payment flows. It'requires both ConnectorCommon and ConnectorIntegration to be implemented. + +## Connector Traits Overview + +### `Payment` +Includes several sub-traits and represents general payment functionality. +- **Defined in:** [`crates/hyperswitch_interfaces/src/types.rs:11-16`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_interfaces/src/types.rs#L11-L16) +- **Example implementation:** [`crates/hyperswitch_connectors/src/connectors/novalnet.rs:70`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/novalnet.rs#L70) + +### `PaymentAuthorize` +Extends the `api::ConnectorIntegration` trait with types for payment authorization. +- **Flow type defined in:** [`crates/router/src/types.rs:39`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/router/src/types.rs#L39) +- **Example implementation:** [`crates/hyperswitch_connectors/src/connectors/novalnet.rs:74`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/novalnet.rs#L74) + +### `PaymentCapture` +Extends the `api::ConnectorIntegration` trait with types for manual capture of a previously authorized payment. +- **Flow type defined in:** [`crates/router/src/types.rs:39`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/router/src/types.rs#L39) +- **Example implementation:** [`crates/hyperswitch_connectors/src/connectors/novalnet.rs:76`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/novalnet.rs#L76) + +### `PaymentSync` +Extends the `api::ConnectorIntegration` trait with types for retrieving or synchronizing payment status. +- **Flow type defined in:** [`crates/router/src/types.rs:41`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/router/src/types.rs#L41) +- **Example implementation:** [`crates/hyperswitch_connectors/src/connectors/novalnet.rs:75`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/novalnet.rs#L75) + +### `Refund` +Includes several sub-traits and represents general refund functionality. +- **Defined in:** [`crates/hyperswitch_interfaces/src/types.rs:17`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_interfaces/src/types.rs#L17) +- **Example implementation:** [`crates/hyperswitch_connectors/src/connectors/novalnet.rs:78`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/novalnet.rs#L78) + +### `RefundExecute` +Extends the `api::ConnectorIntegration` trait with types for creating a refund. +- **Flow type defined in:** [`crates/router/src/types.rs:44`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/router/src/types.rs#L44) +- **Example implementation:** [`crates/hyperswitch_connectors/src/connectors/novalnet.rs:79`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/novalnet.rs#L79) + +### `RefundSync` +Extends the `api::ConnectorIntegration` trait with types for retrieving or synchronizing a refund. +- **Flow type defined in:** [`crates/router/src/types.rs:44`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/router/src/types.rs#L44) +- **Example implementation:** [`crates/hyperswitch_connectors/src/connectors/novalnet.rs:80`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/novalnet.rs#L80) + +## Connector Required Fields Configuration + +The file [`crates/payment_methods/src/configs/payment_connector_required_fields.rs`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/payment_methods/src/configs/payment_connector_required_fields.rs#L1) is the central configuration file that defines required fields for each connector and payment-method combination. + +### Example: Billwerk Required Fields + +Based on the required-fields configuration, Billwerk requires only basic card details for card payments. Please see [`payment_connector_required_fields.rs:1271`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/payment_methods/src/configs/payment_connector_required_fields.rs#L1271). + +Specifically, Billwerk requires: +- Card number +- Card expiry month +- Card expiry year +- Card CVC + +This is defined using the `card_basic()` helper (see [`payment_connector_required_fields.rs:876–884`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/payment_methods/src/configs/payment_connector_required_fields.rs#L876-L884)), which specifies these four essential card fields as `RequiredField` enum variants. + +### Comparison with Other Connectors + +Billwerk has relatively minimal requirements compared to other connectors. For example: + +- **Bank of America** requires card details plus email, full name, and complete billing address (see [`payment_connector_required_fields.rs:1256–1262`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/payment_methods/src/configs/payment_connector_required_fields.rs#L1256-L1262)). +- **Cybersource** requires card details, billing email, full name, and billing address (see [`payment_connector_required_fields.rs:1288–1294`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/payment_methods/src/configs/payment_connector_required_fields.rs#L1288-L1294)). + +Please review the file for your specific connector requirements. + +## Derive Traits + +The derive traits are standard Rust traits that are automatically implemented: + +- **Debug**: Standard Rust trait for debug formatting. It's automatically derived on connector structs like [`crates/hyperswitch_connectors/src/connectors/coinbase.rs:52`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/coinbase.rs#L52) +- **Clone**: Standard Rust trait for cloning. It's implemented on connector structs like [`crates/hyperswitch_connectors/src/connectors/novalnet.rs:57`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/connectors/novalnet.rs#L58) +- **Copy**: Standard Rust trait for copy semantics. It's used where applicable for simple data structures + +These traits work together to provide a complete payment processing interface, with each trait extending `ConnectorIntegration` with specific type parameters for different operations. + +## Connector utility functions +Hyperswitch provides a set of standardized utility functions to streamline data extraction, validation, and formatting across all payment connectors. These are primarily defined in: + +- [`crates/hyperswitch_connectors/src/utils.rs`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/hyperswitch_connectors/src/utils.rs#L1) +- [`crates/router/src/connector/utils.rs`](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/router/src/connector/utils.rs#L1) + +### Key Utilities and Traits + +#### `RouterData` Trait +Provides helper methods to extract billing and browser data: + +- `get_billing_country()` – Retrieves the billing country +- `get_billing_email()` – Gets the customer email from billing data +- `get_billing_full_name()` – Extracts full name +- `get_browser_info()` – Parses browser details for 3DS +- `is_three_ds()` – Checks if 3DS is required +- `is_auto_capture()` – Determines if auto-capture is enabled + +--- + +#### `CardData` Trait +Handles card-specific formatting and parsing: + +- `get_expiry_date_as_yyyymm()` – Formats expiry as YYYYMM +- `get_expiry_date_as_mmyyyy()` – Formats expiry as MMYYYY +- `get_card_expiry_year_2_digit()` – Gets 2-digit expiry year +- `get_card_issuer()` – Returns card brand (Visa, Mastercard, etc.) +- `get_cardholder_name()` – Extracts name on card + +--- + +#### Wallet Data +Utility for processing digital wallet tokens: + +```rs +let json_wallet_data: CheckoutGooglePayData = wallet_data.get_wallet_token_as_json()?; ``` +### Real-World Usage Examples +- PayPal Connector: `get_expiry_date_as_yyyymm()` is used for tokenization and authorization -### **Connector configs for control center** +- Bambora Connector: `get_browser_info()` is used to enables 3DS and `is_auto_capture()` is used to check capture behavior -This section is for developers using the [Hyperswitch Control Center](https://github.com/juspay/hyperswitch-control-center). Update the connector configuration in development.toml and run the wasm-pack build command. Replace placeholders with actual paths. +- Trustpay Connector: Uses extensive browser info usage for 3DS validation flows -1. Install wasm-pack: -```bash +### Error Handling & Validation +- `missing_field_err()` – Commonly used across connectors for standardized error reporting + +## Connector Configuration for Control Center Integration +This guide helps developers integrate custom connectors with the Hyperswitch Control Center by configuring connector settings and building the required WebAssembly components. + +## Prerequisites + +Install the WebAssembly build tool: + +```bash cargo install wasm-pack ``` +### Step 1: Configure Your Connector +Add your connector configuration to the [development environment file](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/connector_configs/toml/development.toml) + +The connector configuration system does support multiple environments as you mentioned. The system automatically selects the appropriate configuration file based on feature flags: + +- Production: [crates/connector_configs/toml/production.toml](https://github.com/juspay/hyperswitch/blob/06dc66c62e33c1c56c42aab18a7959e1648d6fae/crates/connector_configs/toml/production.toml) +- Sandbox: [crates/connector_configs/toml/sandbox.toml](https://github.com/juspay/hyperswitch/blob/06dc66c62e33c1c56c42aab18a7959e1648d6fae/crates/connector_configs/toml/sandbox.toml) +- Development: [crates/connector_configs/toml/development.toml (default)](https://github.com/juspay/hyperswitch/blob/06dc66c62e33c1c56c42aab18a7959e1648d6fae/crates/connector_configs/toml/development.toml) + +```rs +# Example: Adding a new connector configuration +[your_connector_name] +[your_connector_name.connector_auth.HeaderKey] +api_key = "Your_API_Key_Here" + +# Optional: Add additional connector-specific settings +[your_connector_name.connector_webhook_details] +merchant_secret = "webhook_secret" +``` +### Step 2: Build WebAssembly Components +The Control Center requires WebAssembly files for connector integration. Build them using: + +```bash +wasm-pack build \ + --target web \ + --out-dir /path/to/hyperswitch-control-center/public/hyperswitch/wasm \ + --out-name euclid \ + /path/to/hyperswitch/crates/euclid_wasm \ + -- --features dummy_connector +``` +- Replace `/path/to/hyperswitch-control-center` with your Control Center installation directory -2. Add connector configuration: +- Replace `/path/to/hyperswitch` with your Hyperswitch repository root - Open the development.toml file located at crates/connector_configs/toml/development.toml in your Hyperswitch project. - Find the [stripe] section and add the configuration for example_connector. Example: +The build process uses the [`euclid_wasm` crate](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/euclid_wasm/Cargo.toml#L1-L44), which provides WebAssembly bindings for connector configuration and routing logic. - ```toml - # crates/connector_configs/toml/development.toml +### Step 3: Verify Integration +The WebAssembly build includes [connector configuration functions](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/crates/euclid_wasm/src/lib.rs#L376-L382) that the Control Center uses to retrieve connector settings dynamically. - # Other connector configurations... +You can also use the Makefile target for convenience: - [stripe] - [stripe.connector_auth.HeaderKey] - api_key="Secret Key" +```bash +make euclid-wasm +``` + +This target is defined in the [Makefile:86-87](https://github.com/juspay/hyperswitch/blob/2309c5311cb9a01ef371f3a3ef7c62c88a043696/Makefile#L86-L87) and handles the build process with appropriate feature flags. - # Add any other Stripe-specific configuration here +### Configuration Features +The connector configuration system supports: - [example_connector] - # Your specific connector configuration for reference - # ... +- **Environment-specific configs**: [Development, sandbox, and production configurations](https://github.com/juspay/hyperswitch/blob/06dc66c6/crates/connector_configs/src/connector.rs#L323-L337) - ``` +- **Authentication methods**: HeaderKey, BodyKey, SignatureKey, etc. -3. Update paths: - Replace /absolute/path/to/hyperswitch-control-center and /absolute/path/to/hyperswitch with actual paths. +- **Webhook configuration**: For handling asynchronous payment notifications -4. Run `wasm-pack` build: - wasm-pack build --target web --out-dir /absolute/path/to/hyperswitch-control-center/public/hyperswitch/wasm --out-name euclid /absolute/path/to/hyperswitch/crates/euclid_wasm -- --features dummy_connector +- **Payment method support**: Defining which payment methods your connector supports -By following these steps, you should be able to update the connector configuration and build the WebAssembly files successfully. +### Troubleshooting +If the build fails, ensure: -### Update `ConnectorTypes.res` and `ConnectorUtils.res` +- Your connector is properly registered in the connector enum +- **The WebAssembly target is installed: `rustup target add wasm32-unknown-unknown`** +- All required features are enabled in your connector's `Cargo.toml` +- The configuration system automatically loads the appropriate environment settings based on compile-time features, ensuring your connector works correctly across different deployment environments. -1. **Update `ConnectorTypes.res`**: - - Open `src/screens/HyperSwitch/Connectors/ConnectorTypes.res`. - - Add your connector to the `connectorName` enum: - ```reason - type connectorName = - | Stripe - | DummyConnector - | YourNewConnector - ``` - - Save the file. +## Control Center Frontend Integration +This section covers integrating your new connector with the Hyperswitch Control Center's frontend interface, enabling merchants to configure and manage your connector through the dashboard. -2. **Update `ConnectorUtils.res`**: - - Open `src/screens/HyperSwitch/Connectors/ConnectorUtils.res`. - - Update functions with your connector: - ```reason - let connectorList : array<connectorName> = [Stripe, YourNewConnector] +### Update Frontend Connector Configuration +1. Add Connector to Type Definitions - let getConnectorNameString = (connectorName: connectorName) => - switch connectorName { - | Stripe => "Stripe" - | YourNewConnector => "Your New Connector" - }; +Update the connector enum in the [Control Center's type definitions](https://github.com/juspay/hyperswitch-control-center/blob/e984254b68511728b6b37890fd0c7c7e90c22f57/src/screens/Connectors/ConnectorTypes.res#L29) + +```rs +type processorTypes = + | BREADPAY + | BLUECODE + | YourNewConnector // Add your connector here at the bottom +``` +### Update Connector Utilities +Modify the [connector utilities](https://github.com/juspay/hyperswitch-control-center/blob/e984254b68511728b6b37890fd0c7c7e90c22f57/src/screens/Connectors/ConnectorUtils.res#L46) to include your new connector. + +```js +// Add to connector list at the bottom +let connectorList: array<connectorTypes> = [ +.... + Processors(BREADPAY), + Processors(BLUECODE), + Processors(YourNewConnector) +] + +// Add display name mapping at the bottom +let getConnectorNameString = (connectorName: connectorName) => + switch connectorName { + | BREADPAY => "breadpay" + | BLUECODE => "bluecode" + | YourNewConnector => "Your New Connector" + } + +// Add connector description at the bottom +let getProcessorInfo = (connector: ConnectorTypes.processorTypes) => { + switch connectorName { + | BREADPAY => breadpayInfo + | BLUECODE => bluecodeInfo + | YourNewConnector => YourNewConnectorInfo + } +``` +After [`bluecodeinfo`](https://github.com/juspay/hyperswitch-control-center/blob/e984254b68511728b6b37890fd0c7c7e90c22f57/src/screens/Connectors/ConnectorUtils.res#L693) definition, add the definition of your connector in a similar format: - let getConnectorInfo = (connectorName: connectorName) => - switch connectorName { - | Stripe => "Stripe description." - | YourNewConnector => "Your New Connector description." - }; - ``` - - Save the file. +```js +let YourNewConnectorInfo = { + description: "Info for the connector.", +} +``` ### Add Connector Icon +1. Prepare Icon Asset +- Create an SVG icon for your connector +- Name it in uppercase format: YOURCONNECTOR.SVG +- Ensure the icon follows the design guidelines (typically 24x24px or 32x32px) +2. Add to Assets Directory +Place your icon in the Control Center's gateway assets folder: + +```text +public/ +└── hyperswitch/ + └── Gateway/ + └── YOURCONNECTOR.SVG +``` +The icon will be automatically loaded by the frontend based on the connector name mapping. + +--- +## Test the Connector Integration +After successfully creating your connector using the `add_connector.sh` script, you need to configure authentication credentials and test the integration. This section covers the complete testing setup process. + +### Authentication Setup +1. **Obtain PSP Credentials** -1. **Prepare the Icon**: - Name your connector icon in uppercase (e.g., `YOURCONNECTOR.SVG`). +First, obtain sandbox/UAT API credentials from your payment service provider. These are typically available through their developer portal or dashboard. -2. **Add the Icon**: - Navigate to `public/hyperswitch/Gateway` and copy your SVG icon file there. +2. **Create Authentication File** -3. **Verify Structure**: - Ensure the file is correctly placed in `public/hyperswitch/Gateway`: +Copy the sample authentication template and create your credentials file: - ``` - public - └── hyperswitch - └── Gateway - └── YOURCONNECTOR.SVG - ``` - Save the changes made to the `Gateway` folder. +```bash +cp crates/router/tests/connectors/sample_auth.toml auth.toml +``` + +The sample file `crates/router/tests/connectors/sample_auth.toml` contains templates for all supported connectors. Edit your `auth.toml` file to include your connector's credentials: -### **Test the Connector** +**Example for the Billwerk connector** -1. **Template Code** +```text +[billewerk] +api_key = "sk_test_your_actual_billwerk_test_key_here" +``` - The template script generates a test file with 20 sanity tests. Implement these tests when adding a new connector. +3. **Configure Environment Variables** - Example test: - ```rust - #[serial_test::serial] - #[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); - } - ``` +Set the path to your authentication file: + +```bash +export CONNECTOR_AUTH_FILE_PATH="/absolute/path/to/your/auth.toml" +``` + +4. **Use `direnv` for Environment Management (recommended)** + +For better environment variable management, use `direnv` with a `.envrc` file in the `cypress-tests` directory. + +5. **Create `.envrc` in the `cypress-tests` directory** + +```bash +cd cypress-tests +``` +**Create a `.envrc` file with the following content**: + +```bash +export CONNECTOR_AUTH_FILE_PATH="/absolute/path/to/your/auth.toml" +export CYPRESS_CONNECTOR="your_connector_name" +export CYPRESS_BASEURL="http://localhost:8080" +export CYPRESS_ADMINAPIKEY="test_admin" +export DEBUG=cypress:cli +``` + +6. **Allow `direnv` to load the variables inside the `cypress-tests` directory**: -2. **Utility Functions** +``` bash +direnv allow +``` + +### Test the Connector Integration + +1. **Start the Hyperswitch Router Service locally**: + +```bash +cargo r +``` - Helper functions for tests are available in `tests/connector/utils`, making test writing easier. +2. **Verify Server Health** -3. **Set API Keys** +```bash +curl --head --request GET 'http://localhost:8080/health' +``` + +**Detailed health check** - Before running tests, configure API keys in sample_auth.toml and set the environment variable: +```bash +curl --request GET 'http://localhost:8080/health/ready' +``` - ```bash - export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml" - cargo test --package router --test connectors -- checkout --test-threads=1 - ``` +3. **Run Connector Tests for Your Connector** -### **Build Payment Request and Response from JSON Schema** +```bash +cargo test --package router --test connectors -- your_connector_name --test-threads=1 +``` -1. **Install OpenAPI Generator:** - ```bash - brew install openapi-generator - ``` +The authentication system will load your credentials from the specified path and use them for testing. -2. **Generate Rust Code:** - ```bash - export CONNECTOR_NAME="<CONNECTOR-NAME>" - export SCHEMA_PATH="<PATH-TO-SCHEMA>" - openapi-generator generate -g rust -i ${SCHEMA_PATH} -o temp && cat temp/src/models/* > crates/router/src/connector/${CONNECTOR_NAME}/temp.rs && rm -rf temp && sed -i'' -r "s/^pub use.*//;s/^pub mod.*//;s/^\/.*//;s/^.\*.*//;s/crate::models:://g;" crates/router/src/connector/${CONNECTOR_NAME}/temp.rs && cargo +nightly fmt - ``` \ No newline at end of file +> **⚠️ Important Notes** +> +> * **Never commit `auth.toml`** – It contains sensitive credentials and should never be added to version control +> * **Use absolute paths** – This avoids issues when running tests from different directories +> * **Populate with real test credentials** – Replace the placeholder values from the sample file with actual sandbox/UAT credentials from your payment processors. Please don't use production credentials. +> * **Rotate credentials regularly** – Update test keys periodically for security. \ No newline at end of file
2025-07-24T01:48:29Z
## 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 --> Updating the connector documentation ### 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). --> Make it easier for developers to contribute ## 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.116.0
b133c534fb1ce40bd6cca27fac4f2d58b0863e30
b133c534fb1ce40bd6cca27fac4f2d58b0863e30
juspay/hyperswitch
juspay__hyperswitch-8710
Bug: feat(routing): Add new endpoints for evaluate, feedback, and rule-evaluate Adds api refs for routing APIs
diff --git a/api-reference/docs.json b/api-reference/docs.json index f46b0f2e07d..17050ceb9fc 100644 --- a/api-reference/docs.json +++ b/api-reference/docs.json @@ -220,7 +220,10 @@ "v1/routing/routing--retrieve-default-for-profile", "v1/routing/routing--update-default-for-profile", "v1/routing/routing--retrieve", - "v1/routing/routing--activate-config" + "v1/routing/routing--activate-config", + "v1/routing/routing--evaluate", + "v1/routing/routing--feedback", + "v1/routing/routing--rule-evaluate" ] }, { diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 13e93cc88f7..e784eae6801 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -5174,6 +5174,162 @@ ] } }, + "/routing/evaluate": { + "post": { + "tags": [ + "Routing" + ], + "summary": "Routing - Evaluate", + "description": "Evaluate routing rules", + "operationId": "Evaluate routing rules", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OpenRouterDecideGatewayRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Routing rules evaluated successfully", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DecideGatewayResponse" + } + } + } + }, + "400": { + "description": "Request body is malformed" + }, + "403": { + "description": "Forbidden" + }, + "404": { + "description": "Resource missing" + }, + "422": { + "description": "Unprocessable request" + }, + "500": { + "description": "Internal server error" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/routing/feedback": { + "post": { + "tags": [ + "Routing" + ], + "summary": "Routing - Feedback", + "description": "Update gateway scores for dynamic routing", + "operationId": "Update gateway scores", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateScorePayload" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Gateway score updated successfully", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateScoreResponse" + } + } + } + }, + "400": { + "description": "Request body is malformed" + }, + "403": { + "description": "Forbidden" + }, + "404": { + "description": "Resource missing" + }, + "422": { + "description": "Unprocessable request" + }, + "500": { + "description": "Internal server error" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/routing/rule/evaluate": { + "post": { + "tags": [ + "Routing" + ], + "summary": "Routing - Rule Evaluate", + "description": "Evaluate routing rules", + "operationId": "Evaluate routing rules (alternative)", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RoutingEvaluateRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Routing rules evaluated successfully", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RoutingEvaluateResponse" + } + } + } + }, + "400": { + "description": "Request body is malformed" + }, + "403": { + "description": "Forbidden" + }, + "404": { + "description": "Resource missing" + }, + "422": { + "description": "Unprocessable request" + }, + "500": { + "description": "Internal server error" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, "/blocklist": { "delete": { "tags": [ @@ -13366,6 +13522,80 @@ } } }, + "DeRoutableConnectorChoice": { + "type": "object", + "description": "Routable Connector chosen for a payment", + "required": [ + "gateway_name", + "gateway_id" + ], + "properties": { + "gateway_name": { + "$ref": "#/components/schemas/RoutableConnectors" + }, + "gateway_id": { + "type": "string" + } + } + }, + "DecideGatewayResponse": { + "type": "object", + "properties": { + "decided_gateway": { + "type": "string", + "nullable": true + }, + "gateway_priority_map": { + "nullable": true + }, + "filter_wise_gateways": { + "nullable": true + }, + "priority_logic_tag": { + "type": "string", + "nullable": true + }, + "routing_approach": { + "type": "string", + "nullable": true + }, + "gateway_before_evaluation": { + "type": "string", + "nullable": true + }, + "priority_logic_output": { + "allOf": [ + { + "$ref": "#/components/schemas/PriorityLogicOutput" + } + ], + "nullable": true + }, + "reset_approach": { + "type": "string", + "nullable": true + }, + "routing_dimension": { + "type": "string", + "nullable": true + }, + "routing_dimension_level": { + "type": "string", + "nullable": true + }, + "is_scheduled_outage": { + "type": "boolean", + "nullable": true + }, + "is_dynamic_mga_enabled": { + "type": "boolean", + "nullable": true + }, + "gateway_mga_id_map": { + "nullable": true + } + } + }, "DecisionEngineEliminationData": { "type": "object", "required": [ @@ -18682,6 +18912,40 @@ } } }, + "OpenRouterDecideGatewayRequest": { + "type": "object", + "required": [ + "paymentInfo", + "merchantId" + ], + "properties": { + "paymentInfo": { + "$ref": "#/components/schemas/PaymentInfo" + }, + "merchantId": { + "type": "string" + }, + "eligibleGatewayList": { + "type": "array", + "items": { + "type": "string" + }, + "nullable": true + }, + "rankingAlgorithm": { + "allOf": [ + { + "$ref": "#/components/schemas/RankingAlgorithm" + } + ], + "nullable": true + }, + "eliminationEnabled": { + "type": "boolean", + "nullable": true + } + } + }, "OrderDetailsWithAmount": { "type": "object", "required": [ @@ -19524,6 +19788,49 @@ } } }, + "PaymentId": { + "type": "string", + "description": "A type for payment_id that can be used for payment ids" + }, + "PaymentInfo": { + "type": "object", + "required": [ + "paymentId", + "amount", + "currency", + "paymentType", + "paymentMethodType", + "paymentMethod" + ], + "properties": { + "paymentId": { + "type": "string" + }, + "amount": { + "$ref": "#/components/schemas/MinorUnit" + }, + "currency": { + "$ref": "#/components/schemas/Currency" + }, + "paymentType": { + "type": "string" + }, + "metadata": { + "type": "string", + "nullable": true + }, + "paymentMethodType": { + "type": "string" + }, + "paymentMethod": { + "$ref": "#/components/schemas/PaymentMethod" + }, + "cardIsin": { + "type": "string", + "nullable": true + } + } + }, "PaymentLinkBackgroundImageConfig": { "type": "object", "required": [ @@ -26541,6 +26848,66 @@ }, "additionalProperties": false }, + "PriorityLogicData": { + "type": "object", + "properties": { + "name": { + "type": "string", + "nullable": true + }, + "status": { + "type": "string", + "nullable": true + }, + "failure_reason": { + "type": "string", + "nullable": true + } + } + }, + "PriorityLogicOutput": { + "type": "object", + "properties": { + "isEnforcement": { + "type": "boolean", + "nullable": true + }, + "gws": { + "type": "array", + "items": { + "type": "string" + }, + "nullable": true + }, + "priorityLogicTag": { + "type": "string", + "nullable": true + }, + "gatewayReferenceIds": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "nullable": true + }, + "primaryLogic": { + "allOf": [ + { + "$ref": "#/components/schemas/PriorityLogicData" + } + ], + "nullable": true + }, + "fallbackLogic": { + "allOf": [ + { + "$ref": "#/components/schemas/PriorityLogicData" + } + ], + "nullable": true + } + } + }, "ProcessorPaymentToken": { "type": "object", "description": "Processor payment token for MIT payments where payment_method_data is not available", @@ -26986,6 +27353,10 @@ } } }, + "ProfileId": { + "type": "string", + "description": "A type for profile_id that can be used for business profile ids" + }, "ProfileResponse": { "type": "object", "required": [ @@ -27322,6 +27693,14 @@ } } }, + "RankingAlgorithm": { + "type": "string", + "enum": [ + "SR_BASED_ROUTING", + "PL_BASED_ROUTING", + "NTW_BASED_ROUTING" + ] + }, "RealTimePaymentData": { "oneOf": [ { @@ -28663,6 +29042,56 @@ } } }, + "RoutingEvaluateRequest": { + "type": "object", + "required": [ + "created_by", + "parameters", + "fallback_output" + ], + "properties": { + "created_by": { + "type": "string" + }, + "parameters": { + "type": "object", + "description": "Parameters that can be used in the routing evaluate request.\neg: {\"parameters\": {\n\"payment_method\": {\"type\": \"enum_variant\", \"value\": \"card\"},\n\"payment_method_type\": {\"type\": \"enum_variant\", \"value\": \"credit\"},\n\"amount\": {\"type\": \"number\", \"value\": 10},\n\"currency\": {\"type\": \"str_value\", \"value\": \"INR\"},\n\"authentication_type\": {\"type\": \"enum_variant\", \"value\": \"three_ds\"},\n\"card_bin\": {\"type\": \"str_value\", \"value\": \"424242\"},\n\"capture_method\": {\"type\": \"enum_variant\", \"value\": \"scheduled\"},\n\"business_country\": {\"type\": \"str_value\", \"value\": \"IN\"},\n\"billing_country\": {\"type\": \"str_value\", \"value\": \"IN\"},\n\"business_label\": {\"type\": \"str_value\", \"value\": \"business_label\"},\n\"setup_future_usage\": {\"type\": \"enum_variant\", \"value\": \"off_session\"},\n\"card_network\": {\"type\": \"enum_variant\", \"value\": \"visa\"},\n\"payment_type\": {\"type\": \"enum_variant\", \"value\": \"recurring_mandate\"},\n\"mandate_type\": {\"type\": \"enum_variant\", \"value\": \"single_use\"},\n\"mandate_acceptance_type\": {\"type\": \"enum_variant\", \"value\": \"online\"},\n\"metadata\":{\"type\": \"metadata_variant\", \"value\": {\"key\": \"key1\", \"value\": \"value1\"}}\n}}" + }, + "fallback_output": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DeRoutableConnectorChoice" + } + } + } + }, + "RoutingEvaluateResponse": { + "type": "object", + "required": [ + "status", + "output", + "evaluated_output", + "eligible_connectors" + ], + "properties": { + "status": { + "type": "string" + }, + "output": {}, + "evaluated_output": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RoutableConnectorChoice" + } + }, + "eligible_connectors": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RoutableConnectorChoice" + } + } + } + }, "RoutingKind": { "oneOf": [ { @@ -30526,6 +30955,33 @@ "external" ] }, + "TxnStatus": { + "type": "string", + "enum": [ + "STARTED", + "AUTHENTICATION_FAILED", + "JUSPAY_DECLINED", + "PENDING_VBV", + "V_B_V_SUCCESSFUL", + "AUTHORIZED", + "AUTHORIZATION_FAILED", + "CHARGED", + "AUTHORIZING", + "C_O_D_INITIATED", + "VOIDED", + "VOID_INITIATED", + "NOP", + "CAPTURE_INITIATED", + "CAPTURE_FAILED", + "VOID_FAILED", + "AUTO_REFUNDED", + "PARTIAL_CHARGED", + "TO_BE_CHARGED", + "PENDING", + "FAILURE", + "DECLINED" + ] + }, "UIWidgetFormLayout": { "type": "string", "enum": [ @@ -30562,6 +31018,40 @@ }, "additionalProperties": false }, + "UpdateScorePayload": { + "type": "object", + "required": [ + "merchantId", + "gateway", + "status", + "paymentId" + ], + "properties": { + "merchantId": { + "type": "string" + }, + "gateway": { + "type": "string" + }, + "status": { + "$ref": "#/components/schemas/TxnStatus" + }, + "paymentId": { + "type": "string" + } + } + }, + "UpdateScoreResponse": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + }, "UpiAdditionalData": { "oneOf": [ { @@ -30669,7 +31159,10 @@ ] }, "value": { - "$ref": "#/components/schemas/MinorUnit" + "type": "integer", + "format": "int64", + "description": "Represents a number literal", + "minimum": 0 } } }, @@ -30729,6 +31222,25 @@ } } }, + { + "type": "object", + "required": [ + "type", + "value" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "global_ref" + ] + }, + "value": { + "type": "string", + "description": "Represents a global reference, which is a reference to a global variable" + } + } + }, { "type": "object", "required": [ @@ -30745,7 +31257,9 @@ "value": { "type": "array", "items": { - "$ref": "#/components/schemas/MinorUnit" + "type": "integer", + "format": "int64", + "minimum": 0 }, "description": "Represents an array of numbers. This is basically used for\n\"one of the given numbers\" operations\neg: payment.method.amount = (1, 2, 3)" } diff --git a/api-reference/v1/routing/routing--evaluate.mdx b/api-reference/v1/routing/routing--evaluate.mdx new file mode 100644 index 00000000000..d4fe1046283 --- /dev/null +++ b/api-reference/v1/routing/routing--evaluate.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /routing/evaluate +--- diff --git a/api-reference/v1/routing/routing--feedback.mdx b/api-reference/v1/routing/routing--feedback.mdx new file mode 100644 index 00000000000..60fb7cde6db --- /dev/null +++ b/api-reference/v1/routing/routing--feedback.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /routing/feedback +--- diff --git a/api-reference/v1/routing/routing--rule-evaluate.mdx b/api-reference/v1/routing/routing--rule-evaluate.mdx new file mode 100644 index 00000000000..8715b56d5c6 --- /dev/null +++ b/api-reference/v1/routing/routing--rule-evaluate.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /routing/rule/evaluate +--- diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index aefbd3eb211..02ded9713f6 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -16,17 +16,18 @@ use crate::{ payment_methods, }; -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct OpenRouterDecideGatewayRequest { pub payment_info: PaymentInfo, + #[schema(value_type = String)] pub merchant_id: id_type::ProfileId, pub eligible_gateway_list: Option<Vec<String>>, pub ranking_algorithm: Option<RankingAlgorithm>, pub elimination_enabled: Option<bool>, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct DecideGatewayResponse { pub decided_gateway: Option<String>, pub gateway_priority_map: Option<serde_json::Value>, @@ -43,7 +44,7 @@ pub struct DecideGatewayResponse { pub gateway_mga_id_map: Option<serde_json::Value>, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct PriorityLogicOutput { pub is_enforcement: Option<bool>, @@ -54,14 +55,14 @@ pub struct PriorityLogicOutput { pub fallback_logic: Option<PriorityLogicData>, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PriorityLogicData { pub name: Option<String>, pub status: Option<String>, pub failure_reason: Option<String>, } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RankingAlgorithm { SrBasedRouting, @@ -69,9 +70,10 @@ pub enum RankingAlgorithm { NtwBasedRouting, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct PaymentInfo { + #[schema(value_type = String)] pub payment_id: id_type::PaymentId, pub amount: MinorUnit, pub currency: Currency, @@ -189,21 +191,23 @@ pub struct UnifiedError { pub developer_message: String, } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)] #[serde(rename_all = "camelCase")] pub struct UpdateScorePayload { + #[schema(value_type = String)] pub merchant_id: id_type::ProfileId, pub gateway: String, pub status: TxnStatus, + #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } -#[derive(Debug, Serialize, Deserialize, Clone)] +#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] pub struct UpdateScoreResponse { pub message: String, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum TxnStatus { Started, diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index a900d841501..ef5a9422e20 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -1444,3 +1444,122 @@ pub enum RoutingResultSource { /// Inbuilt Hyperswitch Routing Engine HyperswitchRouting, } +//TODO: temporary change will be refactored afterwards +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, ToSchema)] +pub struct RoutingEvaluateRequest { + pub created_by: String, + #[schema(value_type = Object)] + ///Parameters that can be used in the routing evaluate request. + ///eg: {"parameters": { + /// "payment_method": {"type": "enum_variant", "value": "card"}, + /// "payment_method_type": {"type": "enum_variant", "value": "credit"}, + /// "amount": {"type": "number", "value": 10}, + /// "currency": {"type": "str_value", "value": "INR"}, + /// "authentication_type": {"type": "enum_variant", "value": "three_ds"}, + /// "card_bin": {"type": "str_value", "value": "424242"}, + /// "capture_method": {"type": "enum_variant", "value": "scheduled"}, + /// "business_country": {"type": "str_value", "value": "IN"}, + /// "billing_country": {"type": "str_value", "value": "IN"}, + /// "business_label": {"type": "str_value", "value": "business_label"}, + /// "setup_future_usage": {"type": "enum_variant", "value": "off_session"}, + /// "card_network": {"type": "enum_variant", "value": "visa"}, + /// "payment_type": {"type": "enum_variant", "value": "recurring_mandate"}, + /// "mandate_type": {"type": "enum_variant", "value": "single_use"}, + /// "mandate_acceptance_type": {"type": "enum_variant", "value": "online"}, + /// "metadata":{"type": "metadata_variant", "value": {"key": "key1", "value": "value1"}} + /// }} + pub parameters: std::collections::HashMap<String, Option<ValueType>>, + pub fallback_output: Vec<DeRoutableConnectorChoice>, +} +impl common_utils::events::ApiEventMetric for RoutingEvaluateRequest {} + +#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] +pub struct RoutingEvaluateResponse { + pub status: String, + pub output: serde_json::Value, + #[serde(deserialize_with = "deserialize_connector_choices")] + pub evaluated_output: Vec<RoutableConnectorChoice>, + #[serde(deserialize_with = "deserialize_connector_choices")] + pub eligible_connectors: Vec<RoutableConnectorChoice>, +} +impl common_utils::events::ApiEventMetric for RoutingEvaluateResponse {} + +fn deserialize_connector_choices<'de, D>( + deserializer: D, +) -> Result<Vec<RoutableConnectorChoice>, D::Error> +where + D: serde::Deserializer<'de>, +{ + let infos = Vec::<DeRoutableConnectorChoice>::deserialize(deserializer)?; + Ok(infos + .into_iter() + .map(RoutableConnectorChoice::from) + .collect()) +} + +impl From<DeRoutableConnectorChoice> for RoutableConnectorChoice { + fn from(choice: DeRoutableConnectorChoice) -> Self { + Self { + choice_kind: RoutableChoiceKind::FullStruct, + connector: choice.gateway_name, + merchant_connector_id: choice.gateway_id, + } + } +} + +/// Routable Connector chosen for a payment +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct DeRoutableConnectorChoice { + pub gateway_name: RoutableConnectors, + #[schema(value_type = String)] + pub gateway_id: Option<common_utils::id_type::MerchantConnectorAccountId>, +} +/// Represents a value in the DSL +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)] +#[serde(tag = "type", content = "value", rename_all = "snake_case")] +pub enum ValueType { + /// Represents a number literal + Number(u64), + /// Represents an enum variant + EnumVariant(String), + /// Represents a Metadata variant + MetadataVariant(MetadataValue), + /// Represents a arbitrary String value + StrValue(String), + /// Represents a global reference, which is a reference to a global variable + GlobalRef(String), + /// Represents an array of numbers. This is basically used for + /// "one of the given numbers" operations + /// eg: payment.method.amount = (1, 2, 3) + NumberArray(Vec<u64>), + /// Similar to NumberArray but for enum variants + /// eg: payment.method.cardtype = (debit, credit) + EnumVariantArray(Vec<String>), + /// Like a number array but can include comparisons. Useful for + /// conditions like "500 < amount < 1000" + /// eg: payment.amount = (> 500, < 1000) + NumberComparisonArray(Vec<NumberComparison>), +} +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)] +pub struct MetadataValue { + pub key: String, + pub value: String, +} +/// Represents a number comparison for "NumberComparisonArrayValue" +#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub struct NumberComparison { + pub comparison_type: ComparisonType, + pub number: u64, +} +/// Conditional comparison type +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum ComparisonType { + Equal, + NotEqual, + LessThan, + LessThanEqual, + GreaterThan, + GreaterThanEqual, +} diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index a5e0a6d95c6..d9f525f39fd 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -170,6 +170,9 @@ Never share your secret api keys. Keep them guarded and secure. routes::routing::toggle_elimination_routing, routes::routing::contract_based_routing_setup_config, routes::routing::contract_based_routing_update_configs, + routes::routing::call_decide_gateway_open_router, + routes::routing::call_update_gateway_score_open_router, + routes::routing::evaluate_routing_rule, // Routes for blocklist routes::blocklist::remove_entry_from_blocklist, @@ -809,6 +812,22 @@ Never share your secret api keys. Keep them guarded and secure. api_models::authentication::ThreeDsData, api_models::authentication::AuthenticationEligibilityRequest, api_models::authentication::AuthenticationEligibilityResponse, + api_models::open_router::OpenRouterDecideGatewayRequest, + api_models::open_router::DecideGatewayResponse, + api_models::open_router::UpdateScorePayload, + api_models::open_router::UpdateScoreResponse, + api_models::routing::RoutingEvaluateRequest, + api_models::routing::RoutingEvaluateResponse, + api_models::routing::ValueType, + api_models::routing::DeRoutableConnectorChoice, + api_models::routing::RoutableConnectorChoice, + api_models::open_router::PaymentInfo, + common_utils::id_type::PaymentId, + common_utils::id_type::ProfileId, + api_models::open_router::RankingAlgorithm, + api_models::open_router::TxnStatus, + api_models::open_router::PriorityLogicOutput, + api_models::open_router::PriorityLogicData, api_models::user::PlatformAccountCreateRequest, api_models::user::PlatformAccountCreateResponse, )), diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs index 78f4c8b187c..234508de37b 100644 --- a/crates/openapi/src/routes/routing.rs +++ b/crates/openapi/src/routes/routing.rs @@ -386,3 +386,69 @@ pub async fn contract_based_routing_setup_config() {} security(("api_key" = []), ("jwt_key" = [])) )] pub async fn contract_based_routing_update_configs() {} + +#[cfg(feature = "v1")] +/// Routing - Evaluate +/// +/// Evaluate routing rules +#[utoipa::path( + post, + path = "/routing/evaluate", + request_body = OpenRouterDecideGatewayRequest, + responses( + (status = 200, description = "Routing rules evaluated successfully", body = DecideGatewayResponse), + (status = 400, description = "Request body is malformed"), + (status = 500, description = "Internal server error"), + (status = 404, description = "Resource missing"), + (status = 422, description = "Unprocessable request"), + (status = 403, description = "Forbidden"), + ), + tag = "Routing", + operation_id = "Evaluate routing rules", + security(("api_key" = [])) +)] +pub async fn call_decide_gateway_open_router() {} + +#[cfg(feature = "v1")] +/// Routing - Feedback +/// +/// Update gateway scores for dynamic routing +#[utoipa::path( + post, + path = "/routing/feedback", + request_body = UpdateScorePayload, + responses( + (status = 200, description = "Gateway score updated successfully", body = UpdateScoreResponse), + (status = 400, description = "Request body is malformed"), + (status = 500, description = "Internal server error"), + (status = 404, description = "Resource missing"), + (status = 422, description = "Unprocessable request"), + (status = 403, description = "Forbidden"), + ), + tag = "Routing", + operation_id = "Update gateway scores", + security(("api_key" = [])) +)] +pub async fn call_update_gateway_score_open_router() {} + +#[cfg(feature = "v1")] +/// Routing - Rule Evaluate +/// +/// Evaluate routing rules +#[utoipa::path( + post, + path = "/routing/rule/evaluate", + request_body = RoutingEvaluateRequest, + responses( + (status = 200, description = "Routing rules evaluated successfully", body = RoutingEvaluateResponse), + (status = 400, description = "Request body is malformed"), + (status = 500, description = "Internal server error"), + (status = 404, description = "Resource missing"), + (status = 422, description = "Unprocessable request"), + (status = 403, description = "Forbidden"), + ), + tag = "Routing", + operation_id = "Evaluate routing rules (alternative)", + security(("api_key" = [])) +)] +pub async fn evaluate_routing_rule() {} diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rs index 5eb929a92d0..d9d5ed1de26 100644 --- a/crates/router/src/core/payments/routing/utils.rs +++ b/crates/router/src/core/payments/routing/utils.rs @@ -3,7 +3,9 @@ use std::collections::{HashMap, HashSet}; use api_models::{ open_router as or_types, routing::{ - self as api_routing, ConnectorSelection, ConnectorVolumeSplit, RoutableConnectorChoice, + self as api_routing, ComparisonType, ConnectorSelection, ConnectorVolumeSplit, + DeRoutableConnectorChoice, MetadataValue, NumberComparison, RoutableConnectorChoice, + RoutingEvaluateRequest, RoutingEvaluateResponse, ValueType, }, }; use async_trait::async_trait; @@ -683,99 +685,6 @@ impl DecisionEngineErrorsInterface for or_types::ErrorResponse { } } -//TODO: temporary change will be refactored afterwards -#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq)] -pub struct RoutingEvaluateRequest { - pub created_by: String, - pub parameters: HashMap<String, Option<ValueType>>, - pub fallback_output: Vec<DeRoutableConnectorChoice>, -} -impl common_utils::events::ApiEventMetric for RoutingEvaluateRequest {} - -#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)] -pub struct RoutingEvaluateResponse { - pub status: String, - pub output: serde_json::Value, - #[serde(deserialize_with = "deserialize_connector_choices")] - pub evaluated_output: Vec<RoutableConnectorChoice>, - #[serde(deserialize_with = "deserialize_connector_choices")] - pub eligible_connectors: Vec<RoutableConnectorChoice>, -} -impl common_utils::events::ApiEventMetric for RoutingEvaluateResponse {} -/// Routable Connector chosen for a payment -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -pub struct DeRoutableConnectorChoice { - pub gateway_name: common_enums::RoutableConnectors, - pub gateway_id: Option<id_type::MerchantConnectorAccountId>, -} - -fn deserialize_connector_choices<'de, D>( - deserializer: D, -) -> Result<Vec<RoutableConnectorChoice>, D::Error> -where - D: serde::Deserializer<'de>, -{ - let infos = Vec::<DeRoutableConnectorChoice>::deserialize(deserializer)?; - Ok(infos - .into_iter() - .map(RoutableConnectorChoice::from) - .collect()) -} - -#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct MetadataValue { - pub key: String, - pub value: String, -} - -/// Represents a value in the DSL -#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(tag = "type", content = "value", rename_all = "snake_case")] -pub enum ValueType { - /// Represents a number literal - Number(u64), - /// Represents an enum variant - EnumVariant(String), - /// Represents a Metadata variant - MetadataVariant(MetadataValue), - /// Represents a arbitrary String value - StrValue(String), - /// Represents a global reference, which is a reference to a global variable - GlobalRef(String), - /// Represents an array of numbers. This is basically used for - /// "one of the given numbers" operations - /// eg: payment.method.amount = (1, 2, 3) - NumberArray(Vec<u64>), - /// Similar to NumberArray but for enum variants - /// eg: payment.method.cardtype = (debit, credit) - EnumVariantArray(Vec<String>), - /// Like a number array but can include comparisons. Useful for - /// conditions like "500 < amount < 1000" - /// eg: payment.amount = (> 500, < 1000) - NumberComparisonArray(Vec<NumberComparison>), -} - -pub type Metadata = HashMap<String, serde_json::Value>; -/// Represents a number comparison for "NumberComparisonArrayValue" -#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct NumberComparison { - pub comparison_type: ComparisonType, - pub number: u64, -} - -/// Conditional comparison type -#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ComparisonType { - Equal, - NotEqual, - LessThan, - LessThanEqual, - GreaterThan, - GreaterThanEqual, -} - /// Represents a single comparison condition. #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -875,16 +784,6 @@ impl ConnectorInfo { } } -impl From<DeRoutableConnectorChoice> for RoutableConnectorChoice { - fn from(choice: DeRoutableConnectorChoice) -> Self { - Self { - choice_kind: api_routing::RoutableChoiceKind::FullStruct, - connector: choice.gateway_name, - merchant_connector_id: choice.gateway_id, - } - } -} - #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Output { @@ -896,6 +795,7 @@ pub enum Output { pub type Globals = HashMap<String, HashSet<ValueType>>; +pub type Metadata = HashMap<String, serde_json::Value>; /// The program, having a default connector selection and /// a bunch of rules. Also can hold arbitrary metadata. #[derive(Clone, Debug, Serialize, Deserialize)] diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index ffd5c265db0..53f6a75c5c1 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -6,7 +6,10 @@ use actix_web::{web, HttpRequest, Responder}; use api_models::{ enums, - routing::{self as routing_types, RoutingRetrieveQuery}, + routing::{ + self as routing_types, RoutingEvaluateRequest, RoutingEvaluateResponse, + RoutingRetrieveQuery, + }, }; use error_stack::ResultExt; use hyperswitch_domain_models::merchant_context::MerchantKeyStore; @@ -19,10 +22,7 @@ use router_env::{ use crate::{ core::{ api_locking, conditional_config, - payments::routing::utils::{ - DecisionEngineApiHandler, EuclidApiClient, RoutingEvaluateRequest, - RoutingEvaluateResponse, - }, + payments::routing::utils::{DecisionEngineApiHandler, EuclidApiClient}, routing, surcharge_decision_config, }, db::errors::StorageErrorExt,
2025-07-21T15:12:22Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pr adds api refs for routing ``` "v1/routing/routing--evaluate", "v1/routing/routing--feedback", "v1/routing/routing--rule-evaluate" ``` Moved `RoutingEvaluateRequest`, `RoutingEvaluateResponse`, `DeRoutableConnectorChoice`, `ValueType`, `MetadataValue`, `NumberComparison`, and `ComparisonType` to api_models so that we can use RoutingEvaluateRequest and RoutingEvaluateResponse in to openapi crate. ### 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)? --> **for "v1/routing/routing--evaluate",** <img width="1423" height="860" alt="image" src="https://github.com/user-attachments/assets/2f8bcd33-7b79-4e56-8e6b-c3d58717609c" /> **for "v1/routing/routing--feedback",** <img width="1461" height="882" alt="image" src="https://github.com/user-attachments/assets/f59d3313-1e02-4776-9471-e116e522a271" /> **for "v1/routing/routing--rule-evaluate"** <img width="1481" height="860" alt="image" src="https://github.com/user-attachments/assets/2b299094-a7d6-49d9-92d3-111d29c7cedd" /> <img width="771" height="207" alt="image" src="https://github.com/user-attachments/assets/abef2fb0-2e66-417b-b6d4-216a640d4c34" /> ## 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.115.0
1e6a088c04b40c7fdd5bc65c1973056bf58de764
1e6a088c04b40c7fdd5bc65c1973056bf58de764