Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(authentication): Add webhook integration for Authentication Service (#10900)
Sahkal Poddare61aef22fd85
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.tomlindex d1fabb4d6c..4e7e50a156 100644--- a/config/deployments/integration_test.toml+++ b/config/deployments/integration_test.toml@@ -956,6 +956,9 @@ billing_connectors_which_requires_invoice_sync_call = "recurly"[authentication_providers]click_to_pay = {connector_list = "adyen, cybersource, trustpay"}+[authentication_service_enabled_connectors]+connector_list = "juspaythreedsserver, ctp_mastercard, ctp_visa"+[list_dispute_supported_connectors]connector_list = "worldpayvantiv"diff --git a/config/deployments/production.toml b/config/deployments/production.tomlindex 93fb142202..8d11fc2461 100644--- a/config/deployments/production.toml+++ b/config/deployments/production.toml@@ -964,6 +964,9 @@ billing_connectors_which_requires_invoice_sync_call = "recurly"[authentication_providers]click_to_pay = {connector_list = "adyen, cybersource, trustpay"}+[authentication_service_enabled_connectors]+connector_list = "juspaythreedsserver, ctp_mastercard, ctp_visa"+[grpc_client.unified_connector_service]ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS onlyucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync calldiff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.tomlindex 4ce214b018..575c742a39 100644--- a/config/deployments/sandbox.toml+++ b/config/deployments/sandbox.toml@@ -972,6 +972,9 @@ billing_connectors_which_requires_invoice_sync_call = "recurly"[authentication_providers]click_to_pay = {connector_list = "adyen, cybersource, trustpay"}+[authentication_service_enabled_connectors]+connector_list = "juspaythreedsserver, ctp_mastercard, ctp_visa"+[list_dispute_supported_connectors]connector_list = "worldpayvantiv"diff --git a/config/development.toml b/config/development.tomlindex a30fafe5ef..309df17a6a 100644--- a/config/development.toml+++ b/config/development.toml@@ -1402,6 +1402,9 @@ allow_connected_merchants = true[authentication_providers]click_to_pay = {connector_list = "adyen, cybersource, trustpay"}+[authentication_service_enabled_connectors]+connector_list = "juspaythreedsserver, ctp_mastercard, ctp_visa"+[open_router]dynamic_routing_enabled = falsestatic_routing_enabled = falsediff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex 98ea4f570e..5c6962ad56 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -1298,6 +1298,9 @@ encryption_key = ""[authentication_providers]click_to_pay = {connector_list = "adyen, cybersource, trustpay"}+[authentication_service_enabled_connectors]+connector_list = "juspaythreedsserver, ctp_mastercard, ctp_visa"+[revenue_recovery]monitoring_threshold_in_seconds = 60 # threshold for monitoring the retry systemretry_algorithm_type = "cascading" # type of retry algorithmdiff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex c9a65f330e..85884b535c 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -10485,3 +10485,11 @@ pub enum StorageType {#[default]Persistent,}++#[derive(Debug, serde::Serialize, Clone, strum::EnumString, strum::Display)]+#[serde(rename_all = "snake_case")]+#[strum(ascii_case_insensitive)]+pub enum RoutingRegion {+ Region1,+ Region2,+}diff --git a/crates/common_utils/src/id_type/merchant.rs b/crates/common_utils/src/id_type/merchant.rsindex ffea3110e2..4a226f9107 100644--- a/crates/common_utils/src/id_type/merchant.rs+++ b/crates/common_utils/src/id_type/merchant.rs@@ -239,4 +239,9 @@ impl MerchantId {self.get_string_repr())}++ /// Get threeds_routing_region key for merchant+ pub fn get_threeds_routing_region_uas_key(&self) -> String {+ format!("threeds_routing_region_uas_{}", self.get_string_repr())+ }}diff --git a/crates/common_utils/src/id_type/organization.rs b/crates/common_utils/src/id_type/organization.rsindex 2097fbb245..ddb5d69bfc 100644--- a/crates/common_utils/src/id_type/organization.rs+++ b/crates/common_utils/src/id_type/organization.rs@@ -21,4 +21,9 @@ impl OrganizationId {pub fn try_from_string(org_id: String) -> CustomResult<Self, ValidationError> {Self::try_from(std::borrow::Cow::from(org_id))}++ /// fetch Get threeds_routing_region key for organization+ pub fn get_threeds_routing_region_uas_key(&self) -> String {+ format!("threeds_routing_region_uas_{}", self.get_string_repr())+ }}diff --git a/crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs b/crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rsindex f70a8b4511..df2e57f433 100644--- a/crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs+++ b/crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs@@ -14,12 +14,13 @@ use hyperswitch_domain_models::{payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},refunds::{Execute, RSync},Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate,+ ProcessIncomingWebhook,},router_request_types::{unified_authentication_service::{UasAuthenticationRequestData, UasAuthenticationResponseData,UasConfirmationRequestData, UasPostAuthenticationRequestData,- UasPreAuthenticationRequestData,+ UasPreAuthenticationRequestData, UasWebhookRequestData,},AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,@@ -79,6 +80,7 @@ impl api::UasPreAuthentication for Juspaythreedsserver {}impl api::UasPostAuthentication for Juspaythreedsserver {}impl api::UasAuthenticationConfirmation for Juspaythreedsserver {}impl api::UasAuthentication for Juspaythreedsserver {}+impl api::UasProcessWebhook for Juspaythreedsserver {}implConnectorIntegration<@@ -107,6 +109,15 @@ impl{}+impl+ ConnectorIntegration<+ ProcessIncomingWebhook,+ UasWebhookRequestData,+ UasAuthenticationResponseData,+ > for Juspaythreedsserver+{+}+impl ConnectorIntegration<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>for Juspaythreedsserver{diff --git a/crates/hyperswitch_connectors/src/connectors/recurly.rs b/crates/hyperswitch_connectors/src/connectors/recurly.rsindex 71ee6aff61..983c7f3734 100644--- a/crates/hyperswitch_connectors/src/connectors/recurly.rs+++ b/crates/hyperswitch_connectors/src/connectors/recurly.rs@@ -24,6 +24,7 @@ use hyperswitch_domain_models::{},unified_authentication_service::{Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate,+ ProcessIncomingWebhook,},CreateConnectorCustomer, InvoiceRecordBack,},@@ -37,7 +38,7 @@ use hyperswitch_domain_models::{unified_authentication_service::{UasAuthenticationRequestData, UasAuthenticationResponseData,UasConfirmationRequestData, UasPostAuthenticationRequestData,- UasPreAuthenticationRequestData,+ UasPreAuthenticationRequestData, UasWebhookRequestData,},ConnectorCustomerData,},@@ -121,6 +122,7 @@ impl api::UasPreAuthenticationV2 for Recurly {}impl api::UasPostAuthenticationV2 for Recurly {}impl api::UasAuthenticationV2 for Recurly {}impl api::UasAuthenticationConfirmationV2 for Recurly {}+impl api::UasProcessWebhookV2 for Recurly {}implConnectorIntegrationV2<PreAuthenticate,@@ -163,6 +165,17 @@ impl//TODO: implement sessions flow}+impl+ ConnectorIntegrationV2<+ ProcessIncomingWebhook,+ UasFlowData,+ UasWebhookRequestData,+ UasAuthenticationResponseData,+ > for Recurly+{+ //TODO: implement sessions flow+}+impl api::revenue_recovery_v2::RevenueRecoveryV2 for Recurly {}impl api::subscriptions_v2::SubscriptionsV2 for Recurly {}impl api::subscriptions_v2::GetSubscriptionPlansV2 for Recurly {}diff --git a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rsindex 471726d597..e00006cfa8 100644--- a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs+++ b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs@@ -2,11 +2,11 @@ pub mod transformers;use common_utils::{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, ErrorResponse, RouterData},router_flow_types::{@@ -14,12 +14,13 @@ use hyperswitch_domain_models::{payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},refunds::{Execute, RSync},Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate,+ ProcessIncomingWebhook,},router_request_types::{unified_authentication_service::{UasAuthenticationRequestData, UasAuthenticationResponseData,UasConfirmationRequestData, UasPostAuthenticationRequestData,- UasPreAuthenticationRequestData,+ UasPreAuthenticationRequestData, UasWebhookRequestData,},AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,@@ -29,6 +30,7 @@ use hyperswitch_domain_models::{types::{UasAuthenticationConfirmationRouterData, UasAuthenticationRouterData,UasPostAuthenticationRouterData, UasPreAuthenticationRouterData,+ UasProcessWebhookRouterData,},};use hyperswitch_interfaces::{@@ -42,6 +44,7 @@ use hyperswitch_interfaces::{types::{self, Response},webhooks,};+use masking::PeekInterface;use transformers as unified_authentication_service;use crate::{constants::headers, types::ResponseRouterData, utils};@@ -76,6 +79,7 @@ impl api::UasPreAuthentication for UnifiedAuthenticationService {}impl api::UasPostAuthentication for UnifiedAuthenticationService {}impl api::UasAuthenticationConfirmation for UnifiedAuthenticationService {}impl api::UasAuthentication for UnifiedAuthenticationService {}+impl api::UasProcessWebhook for UnifiedAuthenticationService {}impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>for UnifiedAuthenticationService@@ -619,27 +623,162 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData>{}+impl+ ConnectorIntegration<+ ProcessIncomingWebhook,+ UasWebhookRequestData,+ UasAuthenticationResponseData,+ > for UnifiedAuthenticationService+{+ fn get_headers(+ &self,+ req: &UasProcessWebhookRouterData,+ 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: &UasProcessWebhookRouterData,+ connectors: &Connectors,+ ) -> CustomResult<String, errors::ConnectorError> {+ Ok(format!("{}webhooks", self.base_url(connectors)))+ }++ fn get_request_body(+ &self,+ req: &UasProcessWebhookRouterData,+ _connectors: &Connectors,+ ) -> CustomResult<RequestContent, errors::ConnectorError> {+ let connector_req = unified_authentication_service::WebhookRequest::try_from(req)?;+ Ok(RequestContent::Json(Box::new(connector_req)))+ }++ fn build_request(+ &self,+ req: &UasProcessWebhookRouterData,+ connectors: &Connectors,+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {+ Ok(Some(+ RequestBuilder::new()+ .method(Method::Post)+ .url(&types::UasProcessWebhookType::get_url(+ self, req, connectors,+ )?)+ .attach_default_headers()+ .headers(types::UasProcessWebhookType::get_headers(+ self, req, connectors,+ )?)+ .set_body(types::UasProcessWebhookType::get_request_body(+ self, req, connectors,+ )?)+ .build(),+ ))+ }++ fn handle_response(+ &self,+ data: &UasProcessWebhookRouterData,+ event_builder: Option<&mut ConnectorEvent>,+ res: Response,+ ) -> CustomResult<UasProcessWebhookRouterData, errors::ConnectorError> {+ let response: unified_authentication_service::WebhookResponseResult = res+ .response+ .parse_struct("UnifiedAuthenticationService WebhookResponseResult")+ .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 UnifiedAuthenticationService {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: unified_authentication_service::WebhookResponse = request+ .body+ .parse_struct("unified_authentication_service WebhookResponse")+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;+ Ok(+ api_models::webhooks::ObjectReferenceId::ExternalAuthenticationID(+ api_models::webhooks::AuthenticationIdType::ConnectorAuthenticationId(+ webhook_body.three_ds_server_transaction_id,+ ),+ ),+ )}fn get_webhook_event_type(&self,_request: &webhooks::IncomingWebhookRequestDetails<'_>,) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {- Err(report!(errors::ConnectorError::WebhooksNotImplemented))+ Ok(api_models::webhooks::IncomingWebhookEvent::ExternalAuthenticationARes)}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_value: unified_authentication_service::WebhookResponse = request+ .body+ .parse_struct("unified_authentication_service WebhookResponse")+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;+ Ok(Box::new(webhook_body_value))+ }++ fn get_external_authentication_details(+ &self,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,+ ) -> CustomResult<+ hyperswitch_interfaces::authentication::ExternalAuthenticationPayload,+ errors::ConnectorError,+ > {+ let webhook_body: unified_authentication_service::WebhookResponse = request+ .body+ .parse_struct("unified_authentication_service WebhookResponse")+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;++ let challenge_cancel = webhook_body+ .results_request+ .as_ref()+ .and_then(|v| v.peek().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.peek().get("transStatusReason").and_then(|v| v.as_str()))+ .map(|s| s.to_string());++ Ok(+ hyperswitch_interfaces::authentication::ExternalAuthenticationPayload {+ trans_status: webhook_body.trans_status,+ authentication_value: webhook_body.authentication_value,+ eci: webhook_body.eci,+ challenge_cancel,+ challenge_code_reason,+ },+ )}}diff --git a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rsindex 404cc3a5ce..42ebcfbbef 100644--- a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs@@ -1,4 +1,4 @@-use common_enums::{enums, MerchantCategoryCode};+use common_enums::{enums, MerchantCategoryCode, RoutingRegion};use common_types::payments::MerchantCountryCode;use common_utils::{ext_traits::OptionExt as _, types::FloatMajorUnit};use hyperswitch_domain_models::{@@ -13,6 +13,7 @@ use hyperswitch_domain_models::{types::{UasAuthenticationConfirmationRouterData, UasAuthenticationRouterData,UasPostAuthenticationRouterData, UasPreAuthenticationRouterData,+ UasProcessWebhookRouterData,},};use hyperswitch_interfaces::errors;@@ -52,6 +53,7 @@ pub struct UnifiedAuthenticationServicePreAuthenticateRequest {pub transaction_details: Option<TransactionDetails>,pub acquirer_details: Option<Acquirer>,pub billing_address: Option<Address>,+ pub routing_region: Option<RoutingRegion>,}#[derive(Debug, Serialize)]@@ -200,6 +202,7 @@ pub struct MerchantDetails {pub three_ds_requestor_name: Option<String>,pub merchant_country_code: Option<MerchantCountryCode>,pub notification_url: Option<url::Url>,+ pub webhook_url: Option<url::Url>,}#[derive(Default, Clone, Debug, Serialize, PartialEq, Deserialize)]@@ -310,6 +313,7 @@ impl TryFrom<&UnifiedAuthenticationServiceRouterData<&UasPreAuthenticationRouterthree_ds_data: None,message_category: None,}),+ routing_region: item.router_data.request.routing_region.clone(),})}}@@ -403,6 +407,7 @@ pub struct UnifiedAuthenticationServicePostAuthenticateRequest {pub authenticate_by: String,pub source_authentication_id: common_utils::id_type::AuthenticationId,pub auth_creds: ConnectorAuthType,+ pub routing_region: Option<RoutingRegion>,}#[derive(Serialize, Deserialize, Debug, Clone)]@@ -456,6 +461,7 @@ impl TryFrom<&UasPostAuthenticationRouterData>},)?,auth_creds: item.connector_auth_type.clone(),+ routing_region: item.request.routing_region.clone(),})}}@@ -595,6 +601,7 @@ impl TryFrom<&UasPreAuthenticationRouterData>three_ds_requestor_name: merchant_data.three_ds_requestor_name,configuration_id: None,notification_url: merchant_data.notification_url,+ webhook_url: merchant_data.webhook_url,};let acquirer = Acquirer {@@ -638,12 +645,12 @@ impl TryFrom<&UasPreAuthenticationRouterData>post_code: address_wrap.address.clone().and_then(|address| address.zip),state: address_wrap.address.and_then(|address| address.state),});-+ let authentication_info = item.request.authentication_info.clone();Ok(Self {authenticate_by: item.connector.clone(),session_id: authentication_id.clone(),source_authentication_id: authentication_id,- authentication_info: None,+ authentication_info,service_details,customer_details: None,pmt_details: item@@ -666,6 +673,7 @@ impl TryFrom<&UasPreAuthenticationRouterData>transaction_details: None,acquirer_details: Some(acquirer),billing_address,+ routing_region: item.request.routing_region.clone(),})}}@@ -825,6 +833,8 @@ pub struct UnifiedAuthenticationServiceAuthenticateRequest {pub device_details: DeviceDetails,pub customer_details: Option<CustomerDetails>,pub auth_creds: UnifiedAuthenticationServiceAuthType,+ pub authentication_info: Option<AuthenticationInfo>,+ pub routing_region: Option<RoutingRegion>,}#[derive(Default, Debug, Serialize, PartialEq)]@@ -979,7 +989,7 @@ impl TryFrom<&UnifiedAuthenticationServiceRouterData<&UasAuthenticationRouterDat};let auth_type =UnifiedAuthenticationServiceAuthType::try_from(&item.router_data.connector_auth_type)?;-+ let authentication_info = item.router_data.request.authentication_info.clone();Ok(Self {authenticate_by: item.router_data.connector.clone(),source_authentication_id: authentication_id,@@ -987,6 +997,8 @@ impl TryFrom<&UnifiedAuthenticationServiceRouterData<&UasAuthenticationRouterDatauth_creds: auth_type,device_details,customer_details: None,+ authentication_info,+ routing_region: item.router_data.request.routing_region.clone(),})}}@@ -1076,3 +1088,98 @@ impl<F, T>})}}++#[derive(Debug, Serialize, Clone)]+pub struct WebhookRequest {+ pub authenticate_by: String,+ pub body: Vec<u8>,+ pub routing_region: Option<RoutingRegion>,+}++impl TryFrom<&UasProcessWebhookRouterData> for WebhookRequest {+ type Error = error_stack::Report<errors::ConnectorError>;+ fn try_from(item: &UasProcessWebhookRouterData) -> Result<Self, Self::Error> {+ Ok(Self {+ authenticate_by: item.connector.clone(),+ body: item.request.body.clone(),+ routing_region: item.request.routing_region.clone(),+ })+ }+}++impl<F, T> TryFrom<ResponseRouterData<F, WebhookResponseResult, T, UasAuthenticationResponseData>>+ for RouterData<F, T, UasAuthenticationResponseData>+{+ type Error = error_stack::Report<errors::ConnectorError>;+ fn try_from(+ item: ResponseRouterData<F, WebhookResponseResult, T, UasAuthenticationResponseData>,+ ) -> Result<Self, Self::Error> {+ let response = match item.response {+ WebhookResponseResult::Success(auth_response) => {+ let webhook_response = *auth_response;+ Ok(UasAuthenticationResponseData::Webhook {+ trans_status: webhook_response.trans_status,+ authentication_value: webhook_response.authentication_value,+ eci: webhook_response.eci,+ three_ds_server_transaction_id: webhook_response.three_ds_server_transaction_id,+ authentication_id: webhook_response.authentication_id,+ results_request: webhook_response.results_request,+ results_response: webhook_response.results_response,+ })+ }+ WebhookResponseResult::Failure(error_response) => {+ Err(hyperswitch_domain_models::router_data::ErrorResponse {+ code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),+ message: error_response.error.clone(),+ reason: None,+ status_code: item.http_code,+ attempt_status: None,+ connector_transaction_id: None,+ network_advice_code: None,+ network_decline_code: None,+ network_error_message: None,+ connector_metadata: None,+ connector_response_reference_id: None,+ })+ }+ };++ Ok(Self {+ response,+ ..item.data+ })+ }+}++#[derive(Debug, Serialize, Deserialize, Clone)]+#[serde(untagged)]+pub enum WebhookResponseResult {+ Success(Box<WebhookResponse>),+ Failure(UnifiedAuthenticationServiceErrorResponse),+}++#[derive(Debug, Serialize, Deserialize, Clone)]+pub struct WebhookResponse {+ /// trans_status+ pub trans_status: common_enums::TransactionStatus,+ /// authentication_value+ pub authentication_value: Option<Secret<String>>,+ /// eci+ pub eci: Option<String>,+ /// three_ds server transaction id+ pub three_ds_server_transaction_id: String,+ /// authentication_id+ pub authentication_id: Option<common_utils::id_type::AuthenticationId>,+ /// The received Results Request from the Directory Server.+ pub results_request: Option<common_utils::pii::SecretSerdeValue>,+ /// The sent Results Response to the Directory Server.+ pub results_response: Option<common_utils::pii::SecretSerdeValue>,+}++impl WebhookResponse {+ /// Convert the WebhookResponse to Bytes using JSON serialization+ pub fn to_bytes(&self) -> Result<actix_web::web::Bytes, serde_json::Error> {+ let json_bytes = serde_json::to_vec(self)?;+ Ok(actix_web::web::Bytes::from(json_bytes))+ }+}diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rsindex 76f1f62190..2b0f765947 100644--- a/crates/hyperswitch_connectors/src/default_implementations.rs+++ b/crates/hyperswitch_connectors/src/default_implementations.rs@@ -45,7 +45,7 @@ use hyperswitch_domain_models::{AccessTokenAuthentication, Authenticate, AuthenticationConfirmation,ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow,ExternalVaultProxy, ExternalVaultRetrieveFlow, InvoiceRecordBack, PostAuthenticate,- PreAuthenticate, SubscriptionCreate as SubscriptionCreateFlow,+ PreAuthenticate, ProcessIncomingWebhook, SubscriptionCreate as SubscriptionCreateFlow,},router_request_types::{authentication,@@ -58,7 +58,7 @@ use hyperswitch_domain_models::{unified_authentication_service::{UasAuthenticationRequestData, UasAuthenticationResponseData,UasConfirmationRequestData, UasPostAuthenticationRequestData,- UasPreAuthenticationRequestData,+ UasPreAuthenticationRequestData, UasWebhookRequestData,},AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AuthorizeSessionTokenData,CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData,@@ -155,7 +155,7 @@ use hyperswitch_interfaces::{ConnectorAuthenticationToken, ConnectorIntegration, ConnectorMandateRevoke,ConnectorRedirectResponse, ConnectorTransactionId, UasAuthentication,UasAuthenticationConfirmation, UasPostAuthentication, UasPreAuthentication,- UnifiedAuthenticationService,+ UasProcessWebhook, UnifiedAuthenticationService,},errors::ConnectorError,};@@ -6640,6 +6640,158 @@ default_imp_for_uas_pre_authentication!(connectors::Zsl);+macro_rules! default_imp_for_uas_webhook {+ ($($path:ident::$connector:ident),*) => {+ $( impl UasProcessWebhook for $path::$connector {}+ impl+ ConnectorIntegration<+ ProcessIncomingWebhook,+ UasWebhookRequestData,+ UasAuthenticationResponseData+ > for $path::$connector+ {}+ )*+ };+}++default_imp_for_uas_webhook!(+ connectors::Vgs,+ 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::Bluesnap,+ connectors::Bitpay,+ connectors::Blackhawknetwork,+ connectors::Calida,+ connectors::Braintree,+ connectors::Boku,+ 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::Envoy,+ connectors::Facilitapay,+ connectors::Finix,+ connectors::Fiserv,+ connectors::Fiservemea,+ connectors::Fiuu,+ connectors::Flexiti,+ connectors::Forte,+ connectors::Getnet,+ connectors::Gigadat,+ connectors::Globalpay,+ connectors::Globepay,+ connectors::Gocardless,+ connectors::Gpayments,+ connectors::Hipay,+ connectors::Helcim,+ connectors::HyperswitchVault,+ connectors::Hyperwallet,+ connectors::Iatapay,+ connectors::Inespay,+ connectors::Itaubank,+ connectors::Jpmorgan,+ connectors::Katapult,+ connectors::Klarna,+ connectors::Loonio,+ connectors::Netcetera,+ connectors::Nmi,+ connectors::Nomupay,+ connectors::Noon,+ connectors::Nordea,+ connectors::Novalnet,+ connectors::Nexinets,+ connectors::Nexixpay,+ connectors::Opayo,+ connectors::Opennode,+ connectors::Nuvei,+ connectors::Payeezy,+ connectors::Payjustnow,+ connectors::Payjustnowinstore,+ connectors::Payload,+ connectors::Payme,+ connectors::Payone,+ connectors::Paypal,+ connectors::Paysafe,+ connectors::Paystack,+ connectors::Paytm,+ connectors::Payu,+ connectors::Peachpayments,+ connectors::Phonepe,+ connectors::Powertranz,+ connectors::Prophetpay,+ connectors::Mifinity,+ connectors::Mollie,+ connectors::Moneris,+ connectors::Mpgs,+ connectors::Multisafepay,+ connectors::Paybox,+ connectors::Placetopay,+ connectors::Plaid,+ connectors::Rapyd,+ connectors::Razorpay,+ connectors::Recurly,+ connectors::Redsys,+ connectors::Riskified,+ connectors::Santander,+ connectors::Shift4,+ connectors::Sift,+ connectors::Silverflow,+ connectors::Signifyd,+ connectors::Stripe,+ connectors::Stax,+ connectors::Square,+ connectors::Stripebilling,+ connectors::Taxjar,+ connectors::Tesouro,+ connectors::Threedsecureio,+ connectors::Thunes,+ connectors::Tokenex,+ connectors::Tokenio,+ connectors::Trustpay,+ connectors::Trustpayments,+ connectors::Tsys,+ connectors::Wise,+ connectors::Worldline,+ connectors::Worldpay,+ connectors::Worldpaymodular,+ connectors::Worldpayvantiv,+ connectors::Worldpayxml,+ connectors::Wellsfargo,+ connectors::Wellsfargopayout,+ connectors::Volt,+ connectors::Xendit,+ connectors::Zift,+ connectors::Zen,+ connectors::Zsl+);+macro_rules! default_imp_for_uas_post_authentication {($($path:ident::$connector:ident),*) => {$( impl UasPostAuthentication for $path::$connector {}@@ -10057,6 +10209,18 @@ impl<const T: u8>{}+#[cfg(feature = "dummy_connector")]+impl<const T: u8> UasProcessWebhook for connectors::DummyConnector<T> {}+#[cfg(feature = "dummy_connector")]+impl<const T: u8>+ ConnectorIntegration<+ ProcessIncomingWebhook,+ UasWebhookRequestData,+ UasAuthenticationResponseData,+ > for connectors::DummyConnector<T>+{+}+#[cfg(feature = "dummy_connector")]impl<const T: u8> UasPostAuthentication for connectors::DummyConnector<T> {}#[cfg(feature = "dummy_connector")]diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/unified_authentication_service.rs b/crates/hyperswitch_domain_models/src/router_flow_types/unified_authentication_service.rsindex ba851e0506..7294651d0f 100644--- a/crates/hyperswitch_domain_models/src/router_flow_types/unified_authentication_service.rs+++ b/crates/hyperswitch_domain_models/src/router_flow_types/unified_authentication_service.rs@@ -9,3 +9,6 @@ pub struct AuthenticationConfirmation;#[derive(Debug, Clone)]pub struct Authenticate;++#[derive(Debug, Clone)]+pub struct ProcessIncomingWebhook;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.rsindex 2205f5e711..91ef8a55d6 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@@ -1,5 +1,5 @@use api_models::payments::DeviceChannel;-use common_enums::MerchantCategoryCode;+use common_enums::{MerchantCategoryCode, RoutingRegion};use common_types::payments::MerchantCountryCode;use common_utils::types::MinorUnit;use masking::Secret;@@ -16,6 +16,7 @@ pub struct UasPreAuthenticationRequestData {pub billing_address: Option<Address>,pub acquirer_bin: Option<String>,pub acquirer_merchant_id: Option<String>,+ pub routing_region: Option<RoutingRegion>,}#[derive(Debug, Clone)]@@ -29,9 +30,10 @@ pub struct MerchantDetails {pub three_ds_requestor_id: Option<String>,pub three_ds_requestor_name: Option<String>,pub notification_url: Option<url::Url>,+ pub webhook_url: Option<url::Url>,}-#[derive(Clone, Debug, PartialEq, serde::Serialize)]+#[derive(Clone, Debug, serde::Serialize)]pub struct AuthenticationInfo {pub authentication_type: Option<String>,pub authentication_reasons: Option<Vec<String>>,@@ -41,6 +43,7 @@ pub struct AuthenticationInfo {pub supported_card_brands: Option<String>,pub encrypted_payload: Option<Secret<String>>,}+#[derive(Clone, Debug)]pub struct UasAuthenticationRequestData {pub browser_details: Option<super::BrowserInformation>,@@ -51,6 +54,8 @@ pub struct UasAuthenticationRequestData {pub email: Option<common_utils::pii::Email>,pub threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator,pub webhook_url: String,+ pub authentication_info: Option<AuthenticationInfo>,+ pub routing_region: Option<RoutingRegion>,}#[derive(Clone, Debug, serde::Serialize)]@@ -93,6 +98,7 @@ pub struct TransactionDetails {#[derive(Clone, Debug)]pub struct UasPostAuthenticationRequestData {pub threeds_server_transaction_id: Option<String>,+ pub routing_region: Option<RoutingRegion>,}#[derive(Debug, Clone)]@@ -107,6 +113,15 @@ pub enum UasAuthenticationResponseData {authentication_details: PostAuthenticationDetails,},Confirmation {},+ Webhook {+ trans_status: common_enums::TransactionStatus,+ authentication_value: Option<Secret<String>>,+ eci: Option<String>,+ three_ds_server_transaction_id: String,+ authentication_id: Option<common_utils::id_type::AuthenticationId>,+ results_request: Option<common_utils::pii::SecretSerdeValue>,+ results_response: Option<common_utils::pii::SecretSerdeValue>,+ },}#[derive(Debug, Clone, serde::Serialize)]@@ -225,3 +240,9 @@ impl From<PostAuthenticationDetails>}}}++#[derive(Debug, serde::Serialize, Clone)]+pub struct UasWebhookRequestData {+ pub body: Vec<u8>,+ pub routing_region: Option<RoutingRegion>,+}diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rsindex 99468cdeae..64d25addcf 100644--- a/crates/hyperswitch_domain_models/src/types.rs+++ b/crates/hyperswitch_domain_models/src/types.rs@@ -16,8 +16,8 @@ use crate::{CreateConnectorCustomer, CreateOrder, Execute, ExtendAuthorization, ExternalVaultProxy,GiftCardBalanceCheck, IncrementalAuthorization, PSync, PaymentMethodToken,PostAuthenticate, PostCaptureVoid, PostSessionTokens, PreAuthenticate, PreProcessing,- RSync, SdkSessionUpdate, Session, SettlementSplitCreate, SetupMandate, UpdateMetadata,- VerifyWebhookSource, Void,+ ProcessIncomingWebhook, RSync, SdkSessionUpdate, Session, SettlementSplitCreate,+ SetupMandate, UpdateMetadata, VerifyWebhookSource, Void,},router_request_types::{revenue_recovery::{@@ -32,7 +32,7 @@ use crate::{unified_authentication_service::{UasAuthenticationRequestData, UasAuthenticationResponseData,UasConfirmationRequestData, UasPostAuthenticationRequestData,- UasPreAuthenticationRequestData,+ UasPreAuthenticationRequestData, UasWebhookRequestData,},AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData,CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData,@@ -128,6 +128,9 @@ pub type UasAuthenticationConfirmationRouterData = RouterData<UasAuthenticationResponseData,>;+pub type UasProcessWebhookRouterData =+ RouterData<ProcessIncomingWebhook, UasWebhookRequestData, UasAuthenticationResponseData>;+pub type MandateRevokeRouterData =RouterData<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>;pub type PaymentsIncrementalAuthorizationRouterData = RouterData<diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rsindex 9cb0bac330..9ec1a83bee 100644--- a/crates/hyperswitch_interfaces/src/api.rs+++ b/crates/hyperswitch_interfaces/src/api.rs@@ -55,14 +55,15 @@ use hyperswitch_domain_models::{},router_flow_types::{mandate_revoke::MandateRevoke, AccessTokenAuth, AccessTokenAuthentication, Authenticate,- AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, VerifyWebhookSource,+ AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, ProcessIncomingWebhook,+ VerifyWebhookSource,},router_request_types::{self,unified_authentication_service::{UasAuthenticationRequestData, UasAuthenticationResponseData,UasConfirmationRequestData, UasPostAuthenticationRequestData,- UasPreAuthenticationRequestData,+ UasPreAuthenticationRequestData, UasWebhookRequestData,},AccessTokenAuthenticationRequestData, AccessTokenRequestData, MandateRevokeRequestData,VerifyWebhookSourceRequestData,@@ -691,6 +692,13 @@ pub trait UnifiedAuthenticationService:+ UasPostAuthentication+ UasAuthenticationConfirmation+ UasAuthentication+ + UasProcessWebhook+{+}++///trait UasProcessWebhook+pub trait UasProcessWebhook:+ ConnectorIntegration<ProcessIncomingWebhook, UasWebhookRequestData, UasAuthenticationResponseData>{}@@ -737,6 +745,7 @@ pub trait UnifiedAuthenticationServiceV2:+ UasPostAuthenticationV2+ UasAuthenticationV2+ UasAuthenticationConfirmationV2+ + UasProcessWebhookV2{}@@ -773,6 +782,17 @@ pub trait UasAuthenticationConfirmationV2:{}+///trait UasProcessWebhookV2+pub trait UasProcessWebhookV2:+ ConnectorIntegrationV2<+ ProcessIncomingWebhook,+ UasFlowData,+ UasWebhookRequestData,+ UasAuthenticationResponseData,+>+{+}+/// trait UasAuthenticationV2pub trait UasAuthenticationV2:ConnectorIntegrationV2<diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rsindex 5e3db80474..5b8e6191f2 100644--- a/crates/hyperswitch_interfaces/src/types.rs+++ b/crates/hyperswitch_interfaces/src/types.rs@@ -30,6 +30,7 @@ use hyperswitch_domain_models::{},webhooks::VerifyWebhookSource,AccessTokenAuthentication, BillingConnectorInvoiceSync, GiftCardBalanceCheck,+ ProcessIncomingWebhook,},router_request_types::{revenue_recovery::{@@ -44,7 +45,7 @@ use hyperswitch_domain_models::{unified_authentication_service::{UasAuthenticationRequestData, UasAuthenticationResponseData,UasConfirmationRequestData, UasPostAuthenticationRequestData,- UasPreAuthenticationRequestData,+ UasPreAuthenticationRequestData, UasWebhookRequestData,},AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData,AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData,@@ -324,6 +325,13 @@ pub type UasAuthenticationType = dyn ConnectorIntegration<UasAuthenticationResponseData,>;+/// Type alias for `ConnectorIntegration<ProcessIncomingWebhook, UasWebhookRequestData, UasAuthenticationResponseData>`+pub type UasProcessWebhookType = dyn ConnectorIntegration<+ ProcessIncomingWebhook,+ UasWebhookRequestData,+ UasAuthenticationResponseData,+>;+/// Type alias for `ConnectorIntegration<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse>`pub type InvoiceRecordBackType = dyn ConnectorIntegration<InvoiceRecordBack,diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rsindex 18605b94fc..3a194015ea 100644--- a/crates/router/src/configs/secrets_transformers.rs+++ b/crates/router/src/configs/secrets_transformers.rs@@ -638,6 +638,7 @@ pub(crate) async fn fetch_raw_secrets(internal_services: conf.internal_services,superposition,comparison_service: conf.comparison_service,+ authentication_service_enabled_connectors: conf.authentication_service_enabled_connectors,save_payment_method_on_session: conf.save_payment_method_on_session,}}diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex f2766e4f40..f180c1d625 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -183,6 +183,7 @@ pub struct Settings<S: SecretState> {pub trace_header: TraceHeaderConfig,pub internal_services: InternalServicesConfig,pub comparison_service: Option<ComparisonServiceConfig>,+ pub authentication_service_enabled_connectors: AuthenticationServiceEnabledConnectors,pub save_payment_method_on_session: OnSessionConfig,}@@ -568,6 +569,12 @@ where.collect()}+#[derive(Debug, Deserialize, Clone, Default)]+pub struct AuthenticationServiceEnabledConnectors {+ #[serde(deserialize_with = "deserialize_hashset")]+ pub connector_list: HashSet<enums::Connector>,+}+#[derive(Debug, Deserialize, Clone, Default)]pub struct NetworkTransactionIdSupportedConnectors {#[serde(deserialize_with = "deserialize_hashset")]diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex ef49d053d5..bfc41b7872 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -160,7 +160,7 @@ use crate::{#[cfg(feature = "v1")]use crate::{core::{- authentication as authentication_core,+ authentication as authentication_core, unified_authentication_service::utils as uas_utils,unified_connector_service::update_gateway_system_in_feature_metadata,},types::{api::authentication, BrowserInformation},@@ -10845,6 +10845,18 @@ pub async fn payment_external_authentication<F: Clone + Sync>().await?{+ let routing_region = uas_utils::fetch_routing_region_for_uas(+ &state,+ merchant_id.clone(),+ platform+ .get_processor()+ .get_account()+ .organization_id+ .clone(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch routing path")?;let auth_response =<ExternalAuthentication as UnifiedAuthenticationService>::authentication(&state,@@ -10866,6 +10878,7 @@ pub async fn payment_external_authentication<F: Clone + Sync>(Some(payment_intent.payment_id),authentication.force_3ds_challenge,authentication.psd2_sca_exemption_type,+ Some(routing_region),).await?;let authentication = Box::pin(external_authentication_update_trackers(diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex e87a6a74e8..39c22865b7 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -1430,6 +1430,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forNone,None,None,+ None,None).await?;@@ -1444,6 +1445,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for&authentication_id,payment_method,&payment_data.payment_intent.merchant_id,+ None,None).await?;@@ -1475,7 +1477,8 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forOk(unified_authentication_service::UasAuthenticationResponseData::PreAuthentication { .. })| Ok(unified_authentication_service::UasAuthenticationResponseData::Confirmation {})- | Ok(unified_authentication_service::UasAuthenticationResponseData::Authentication { .. }) => Err(errors::ApiErrorResponse::InternalServerError).attach_printable("unexpected response received from unified authentication service")?,+ | Ok(unified_authentication_service::UasAuthenticationResponseData::Authentication { .. })+ | Ok(unified_authentication_service::UasAuthenticationResponseData::Webhook { .. })=> Err(errors::ApiErrorResponse::InternalServerError).attach_printable("unexpected response received from unified authentication service")?,Err(_) => (None, common_enums::AuthenticationStatus::Failed)};payment_data.payment_attempt.payment_method =@@ -1586,11 +1589,26 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for&payment_data.payment_attempt.clone(),payment_data.payment_attempt.connector.as_ref().get_required_value("connector")?,);+ let three_ds_mca_id = three_ds_connector_account.get_mca_id();++ let merchant_connector_account_id_or_connector_name = three_ds_mca_id+ .as_ref()+ .map(|mca_id| mca_id.get_string_repr())+ .unwrap_or(&authentication_connector_name);++ let webhook_url = Some(url::Url::parse(&helpers::create_webhook_url(+ &state.base_url,+ &authentication.merchant_id,+ merchant_connector_account_id_or_connector_name,+ )))+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse webhook notification url")?;let notification_url = Some(url::Url::parse(&return_url)).transpose().change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to parse webhook url")?;+ .attach_printable("Failed to parse authorise notification url")?;let merchant_category_code = business_profile.merchant_category_code.clone().or(metadata.clone().and_then(|metadata| metadata.merchant_category_code.clone()));@@ -1604,6 +1622,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forthree_ds_requestor_name: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_name),merchant_country_code: merchant_country_code.clone().map(common_types::payments::MerchantCountryCode::new),notification_url,+ webhook_url});let domain_address = payment_data.address.get_payment_method_billing();let shipping = payment_data.address.get_shipping();@@ -1613,6 +1632,14 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to parse browser_info")?;let email = payment_data.email.clone();+ let routing_region = uas_utils::utils::fetch_routing_region_for_uas(+ state,+ payment_data.payment_attempt.merchant_id.clone(),+ payment_data.payment_attempt.organization_id.clone(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch routing path")?;let pre_auth_response = uas_utils::types::ExternalAuthentication::pre_authentication(state,@@ -1633,6 +1660,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> fordomain_address,authentication.acquirer_bin.clone(),authentication.acquirer_merchant_id.clone(),+ Some(routing_region),).await?;let updated_authentication = Box::pin(uas_utils::utils::external_authentication_update_trackers(@@ -1709,6 +1737,16 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for.await.to_not_found_response(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| format!("Error while fetching authentication record with authentication_id {}", authentication_id.get_string_repr()))?;++ let routing_region = uas_utils::utils::fetch_routing_region_for_uas(+ state,+ payment_data.payment_attempt.merchant_id.clone(),+ payment_data.payment_attempt.organization_id.clone(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch routing path")?;+let updated_authentication = if !authentication.authentication_status.is_terminal_status() && is_pull_mechanism_enabled {let post_auth_response = uas_utils::types::ExternalAuthentication::post_authentication(state,@@ -1722,6 +1760,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for).attach_printable("payment_method not found in payment_attempt")?,&payment_data.payment_intent.merchant_id,Some(&authentication),+ Some(routing_region)).await?;uas_utils::utils::external_authentication_update_trackers(state,diff --git a/crates/router/src/core/unified_authentication_service.rs b/crates/router/src/core/unified_authentication_service.rsindex 98107ee53b..f6a38e03a6 100644--- a/crates/router/src/core/unified_authentication_service.rs+++ b/crates/router/src/core/unified_authentication_service.rs@@ -67,6 +67,7 @@ use crate::{services::AuthFlow,types::{domain::types::AsyncLift, transformers::ForeignTryFrom},};+#[cfg(feature = "v1")]#[async_trait::async_trait]impl UnifiedAuthenticationService for ClickToPay {@@ -80,6 +81,7 @@ impl UnifiedAuthenticationService for ClickToPay {acquirer_bin: Option<String>,acquirer_merchant_id: Option<String>,_payment_method_type: Option<common_enums::PaymentMethodType>,+ routing_region: Option<common_enums::RoutingRegion>,) -> RouterResult<UasPreAuthenticationRequestData> {let domain_service_details = hyperswitch_domain_models::router_request_types::unified_authentication_service::CtpServiceDetails {service_session_ids: Some(ServiceSessionIds {@@ -105,26 +107,16 @@ impl UnifiedAuthenticationService for ClickToPay {psd2_sca_exemption_type: None,};- let authentication_info = Some(AuthenticationInfo {- authentication_type: None,- authentication_reasons: None,- consent_received: false, // This is not relevant in this flow so keeping it as false- is_authenticated: false, // This is not relevant in this flow so keeping it as false- locale: None,- supported_card_brands: None,- encrypted_payload: service_details- .as_ref()- .and_then(|details| details.encrypted_payload.clone()),- });Ok(UasPreAuthenticationRequestData {service_details: Some(domain_service_details),transaction_details: Some(transaction_details),payment_details: None,- authentication_info,+ authentication_info: None,merchant_details: merchant_details.cloned(),billing_address: billing_address.cloned(),acquirer_bin,acquirer_merchant_id,+ routing_region,})}@@ -145,6 +137,7 @@ impl UnifiedAuthenticationService for ClickToPay {billing_address: Option<&hyperswitch_domain_models::address::Address>,acquirer_bin: Option<String>,acquirer_merchant_id: Option<String>,+ routing_region: Option<common_enums::RoutingRegion>,) -> RouterResult<UasPreAuthenticationRouterData> {let pre_authentication_data = Self::get_pre_authentication_request_data(payment_method_data,@@ -156,6 +149,7 @@ impl UnifiedAuthenticationService for ClickToPay {acquirer_bin,acquirer_merchant_id,payment_method_type,+ routing_region,)?;let pre_auth_router_data: UasPreAuthenticationRouterData =@@ -189,9 +183,11 @@ impl UnifiedAuthenticationService for ClickToPay {payment_method: common_enums::PaymentMethod,merchant_id: &common_utils::id_type::MerchantId,_authentication: Option<&hyperswitch_domain_models::authentication::Authentication>,+ routing_region: Option<common_enums::RoutingRegion>,) -> RouterResult<UasPostAuthenticationRouterData> {let post_authentication_data = UasPostAuthenticationRequestData {threeds_server_transaction_id: None,+ routing_region,};let post_auth_router_data: UasPostAuthenticationRouterData =@@ -304,6 +300,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {acquirer_bin: Option<String>,acquirer_merchant_id: Option<String>,payment_method_type: Option<common_enums::PaymentMethodType>,+ routing_region: Option<common_enums::RoutingRegion>,) -> RouterResult<UasPreAuthenticationRequestData> {let payment_method_data = payment_method_data.ok_or(ApiErrorResponse::InternalServerError)@@ -333,6 +330,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {force_3ds_challenge: None,psd2_sca_exemption_type: None,};+Ok(UasPreAuthenticationRequestData {service_details: None,transaction_details: Some(transaction_details),@@ -342,6 +340,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {billing_address: billing_address.cloned(),acquirer_bin,acquirer_merchant_id,+ routing_region,})}@@ -363,6 +362,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {billing_address: Option<&hyperswitch_domain_models::address::Address>,acquirer_bin: Option<String>,acquirer_merchant_id: Option<String>,+ routing_region: Option<common_enums::RoutingRegion>,) -> RouterResult<UasPreAuthenticationRouterData> {let pre_authentication_data = Self::get_pre_authentication_request_data(payment_method_data,@@ -374,6 +374,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {acquirer_bin,acquirer_merchant_id,payment_method_type,+ routing_region,)?;let pre_auth_router_data: UasPreAuthenticationRouterData =@@ -411,6 +412,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {webhook_url: String,force_3ds_challenge: Option<bool>,psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,+ routing_region: Option<common_enums::RoutingRegion>,) -> RouterResult<UasAuthenticationRequestData> {Ok(UasAuthenticationRequestData {browser_details,@@ -443,6 +445,8 @@ impl UnifiedAuthenticationService for ExternalAuthentication {email,threeds_method_comp_ind,webhook_url,+ authentication_info: None,+ routing_region,})}@@ -467,6 +471,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {payment_id: Option<common_utils::id_type::PaymentId>,force_3ds_challenge: Option<bool>,psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,+ routing_region: Option<common_enums::RoutingRegion>,) -> RouterResult<UasAuthenticationRouterData> {let authentication_data =<Self as UnifiedAuthenticationService>::get_authentication_request_data(@@ -483,6 +488,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {webhook_url,force_3ds_challenge,psd2_sca_exemption_type,+ routing_region,)?;let auth_router_data: UasAuthenticationRouterData = utils::construct_uas_router_data(state,@@ -506,6 +512,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {fn get_post_authentication_request_data(authentication: Option<hyperswitch_domain_models::authentication::Authentication>,+ routing_region: Option<common_enums::RoutingRegion>,) -> RouterResult<UasPostAuthenticationRequestData> {Ok(UasPostAuthenticationRequestData {// authentication.threeds_server_transaction_id is mandatory for post-authentication in ExternalAuthentication@@ -516,6 +523,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {field_name: "authentication.threeds_server_transaction_id",})?,),+ routing_region,})}@@ -529,10 +537,12 @@ impl UnifiedAuthenticationService for ExternalAuthentication {payment_method: common_enums::PaymentMethod,_merchant_id: &common_utils::id_type::MerchantId,authentication: Option<&hyperswitch_domain_models::authentication::Authentication>,+ routing_region: Option<common_enums::RoutingRegion>,) -> RouterResult<UasPostAuthenticationRouterData> {let authentication_data =<Self as UnifiedAuthenticationService>::get_post_authentication_request_data(authentication.cloned(),+ routing_region,)?;let auth_router_data: UasPostAuthenticationRouterData = utils::construct_uas_router_data(state,@@ -1150,6 +1160,7 @@ pub async fn authentication_eligibility_core(three_ds_requestor_name: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_name),merchant_country_code: merchant_country_code.clone().map(common_types::payments::MerchantCountryCode::new),notification_url,+ webhook_url:None});let domain_address = req@@ -1157,6 +1168,15 @@ pub async fn authentication_eligibility_core(.clone().map(hyperswitch_domain_models::address::Address::from);+ let routing_region = utils::fetch_routing_region_for_uas(+ &state,+ merchant_id.clone(),+ merchant_account.organization_id.clone(),+ )+ .await+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch routing path")?;+let pre_auth_response =<ExternalAuthentication as UnifiedAuthenticationService>::pre_authentication(&state,@@ -1175,6 +1195,7 @@ pub async fn authentication_eligibility_core(domain_address.as_ref(),authentication.acquirer_bin.clone(),authentication.acquirer_merchant_id.clone(),+ Some(routing_region),).await?;@@ -1302,6 +1323,15 @@ pub async fn authentication_authenticate_core(merchant_connector_account_id_or_connector_name,);+ let routing_region = utils::fetch_routing_region_for_uas(+ &state,+ merchant_id.clone(),+ merchant_account.organization_id.clone(),+ )+ .await+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch routing path")?;+let auth_response = <ExternalAuthentication as UnifiedAuthenticationService>::authentication(&state,&business_profile,@@ -1325,6 +1355,7 @@ pub async fn authentication_authenticate_core(None,authentication.force_3ds_challenge,authentication.psd2_sca_exemption_type,+ Some(routing_region),).await?;@@ -1766,6 +1797,13 @@ pub async fn authentication_sync_core(psd2_sca_exemption_type: authentication.psd2_sca_exemption_type,};+ let routing_region = utils::fetch_routing_region_for_uas(+ &state,+ authentication.merchant_id.clone(),+ authentication.organization_id.clone(),+ )+ .await?;+let authentication_info = Some(AuthenticationInfo {authentication_type: None,authentication_reasons: None,@@ -1786,6 +1824,7 @@ pub async fn authentication_sync_core(billing_address: None,acquirer_bin: None,acquirer_merchant_id: None,+ routing_region: Some(routing_region),};// call pre-authlet pre_auth_router_data: UasPreAuthenticationRouterData =@@ -1822,11 +1861,20 @@ pub async fn authentication_sync_core(common_enums::PaymentMethod::Card,merchant_id,None,+ None,).await?;metrics::POST_AUTHENTICATION_CARDS_SUCCESSFULLY_DECRYPTED.add(1, &[]);response} else {+ let routing_region = utils::fetch_routing_region_for_uas(+ &state,+ merchant_id.clone(),+ merchant_account.organization_id.clone(),+ )+ .await+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch routing path")?;ExternalAuthentication::post_authentication(&state,&business_profile,@@ -1837,6 +1885,7 @@ pub async fn authentication_sync_core(common_enums::PaymentMethod::Card,merchant_id,Some(&authentication),+ Some(routing_region),).await?};@@ -2058,6 +2107,14 @@ pub async fn authentication_post_sync_core(authentication.authentication_connector.clone(),).await?;+ let routing_region = utils::fetch_routing_region_for_uas(+ &state,+ merchant_id.clone(),+ merchant_account.organization_id.clone(),+ )+ .await+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch routing path")?;let post_auth_response =<ExternalAuthentication as UnifiedAuthenticationService>::post_authentication(@@ -2070,6 +2127,7 @@ pub async fn authentication_post_sync_core(common_enums::PaymentMethod::Card,merchant_id,Some(&authentication),+ Some(routing_region),).await?;diff --git a/crates/router/src/core/unified_authentication_service/types.rs b/crates/router/src/core/unified_authentication_service/types.rsindex da1db091f8..508fa378e9 100644--- a/crates/router/src/core/unified_authentication_service/types.rs+++ b/crates/router/src/core/unified_authentication_service/types.rs@@ -1,4 +1,5 @@use api_models::payments;+use common_enums::RoutingRegion;use hyperswitch_domain_models::{errors::api_error_response::{self as errors, NotImplementedMessage},router_request_types::{@@ -44,6 +45,7 @@ pub trait UnifiedAuthenticationService {_acquirer_bin: Option<String>,_acquirer_merchant_id: Option<String>,_payment_method_type: Option<common_enums::PaymentMethodType>,+ _routing_region: Option<RoutingRegion>,) -> RouterResult<UasPreAuthenticationRequestData> {Err(errors::ApiErrorResponse::NotImplemented {message: NotImplementedMessage::Reason(@@ -71,6 +73,7 @@ pub trait UnifiedAuthenticationService {_billing_address: Option<&hyperswitch_domain_models::address::Address>,_acquirer_bin: Option<String>,_acquirer_merchant_id: Option<String>,+ _routing_region: Option<RoutingRegion>,) -> RouterResult<hyperswitch_domain_models::types::UasPreAuthenticationRouterData> {Err(errors::ApiErrorResponse::NotImplemented {message: NotImplementedMessage::Reason("pre_authentication".to_string()),@@ -93,6 +96,7 @@ pub trait UnifiedAuthenticationService {_webhook_url: String,_force_3ds_challenge: Option<bool>,_psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,+ _routing_region: Option<RoutingRegion>,) -> RouterResult<UasAuthenticationRequestData> {Err(errors::ApiErrorResponse::NotImplemented {message: NotImplementedMessage::Reason(@@ -123,6 +127,7 @@ pub trait UnifiedAuthenticationService {_payment_id: Option<common_utils::id_type::PaymentId>,_force_3ds_challenge: Option<bool>,_psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,+ _routing_region: Option<RoutingRegion>,) -> RouterResult<hyperswitch_domain_models::types::UasAuthenticationRouterData> {Err(errors::ApiErrorResponse::NotImplemented {message: NotImplementedMessage::Reason("authentication".to_string()),@@ -132,6 +137,7 @@ pub trait UnifiedAuthenticationService {fn get_post_authentication_request_data(_authentication: Option<hyperswitch_domain_models::authentication::Authentication>,+ _routing_region: Option<RoutingRegion>,) -> RouterResult<UasPostAuthenticationRequestData> {Err(errors::ApiErrorResponse::NotImplemented {message: NotImplementedMessage::Reason("post_authentication".to_string()),@@ -150,6 +156,7 @@ pub trait UnifiedAuthenticationService {_payment_method: common_enums::PaymentMethod,_merchant_id: &common_utils::id_type::MerchantId,_authentication: Option<&hyperswitch_domain_models::authentication::Authentication>,+ _routing_region: Option<RoutingRegion>,) -> RouterResult<hyperswitch_domain_models::types::UasPostAuthenticationRouterData> {Err(errors::ApiErrorResponse::NotImplemented {message: NotImplementedMessage::Reason("post_authentication".to_string()),diff --git a/crates/router/src/core/unified_authentication_service/utils.rs b/crates/router/src/core/unified_authentication_service/utils.rsindex 1d1270c869..50b5f75c1a 100644--- a/crates/router/src/core/unified_authentication_service/utils.rs+++ b/crates/router/src/core/unified_authentication_service/utils.rs@@ -1,8 +1,8 @@-use std::marker::PhantomData;+use std::{marker::PhantomData, str::FromStr};#[cfg(feature = "v1")]use api_models::payments::BrowserInformation;-use common_enums::enums::PaymentMethod;+use common_enums::enums::{PaymentMethod, RoutingRegion};use common_utils::{ext_traits::{AsyncExt, ValueExt},types::keymanager::ToEncryptable,@@ -16,10 +16,11 @@ use hyperswitch_domain_models::{router_data::{ConnectorAuthType, ErrorResponse, RouterData},router_data_v2::UasFlowData,router_request_types::unified_authentication_service::{- PostAuthenticationDetails, UasAuthenticationResponseData,+ PostAuthenticationDetails, UasAuthenticationResponseData, UasWebhookRequestData,},type_encryption::AsyncLift,};+use hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails;use masking::{ExposeInterface, PeekInterface};use super::types::{@@ -414,6 +415,10 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>(ApiErrorResponse::InternalServerError,).attach_printable("unexpected api confirmation in external authentication flow."),+ UasAuthenticationResponseData::Webhook { .. } => {+ Err(ApiErrorResponse::InternalServerError)+ .attach_printable("unexpected api webhook in external authentication flow.")+ }},Err(error) => Ok(hyperswitch_domain_models::authentication::AuthenticationUpdate::ErrorUpdate {@@ -615,3 +620,110 @@ pub fn get_authentication_payment_method_data<F, Req>(None}}++pub fn get_webhook_request_data_for_uas(+ request: &IncomingWebhookRequestDetails<'_>,+ routing_region: Option<RoutingRegion>,+) -> UasWebhookRequestData {+ UasWebhookRequestData {+ body: request.body.to_vec(),+ routing_region,+ }+}++pub fn construct_uas_webhook_router_data<F: Clone, Req, Res>(+ state: &SessionState,+ authentication_connector_name: String,+ request_data: Req,+ payment_id: Option<common_utils::id_type::PaymentId>,+) -> RouterResult<RouterData<F, Req, Res>> {+ let merchant_id = common_utils::id_type::MerchantId::get_irrelevant_merchant_id();+ Ok(RouterData {+ flow: PhantomData,+ merchant_id,+ customer_id: None,+ connector_customer: None,+ connector: authentication_connector_name,+ payment_id: payment_id+ .map(|payment_id| payment_id.get_string_repr().to_owned())+ .unwrap_or_default(),+ attempt_id: IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW.to_owned(),+ status: common_enums::AttemptStatus::default(),+ payment_method: PaymentMethod::default(),+ connector_auth_type: ConnectorAuthType::NoKey,+ description: None,+ address: PaymentAddress::default(),+ auth_type: common_enums::AuthenticationType::default(),+ connector_meta_data: None,+ connector_wallets_details: None,+ 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: None,+ payment_method_balance: None,+ connector_api_version: None,+ request: request_data,+ response: Err(ErrorResponse::default()),+ connector_request_reference_id:+ IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW.to_owned(),+ #[cfg(feature = "payouts")]+ payout_method_data: None,+ #[cfg(feature = "payouts")]+ quote_id: None,+ test_mode: None,+ connector_http_status_code: None,+ external_latency: None,+ apple_pay_flow: None,+ frm_metadata: None,+ dispute_id: None,+ refund_id: None,+ payment_method_status: None,+ connector_response: None,+ integrity_check: Ok(()),+ additional_merchant_data: None,+ header_payload: None,+ connector_mandate_request_reference_id: None,+ authentication_id: None,+ psd2_sca_exemption_type: None,+ tenant_id: state.tenant.tenant_id.clone(),+ payment_method_type: None,+ payout_id: None,+ minor_amount_capturable: None,+ authorized_amount: None,+ l2_l3_data: None,+ raw_connector_response: None,+ is_payment_id_from_merchant: None,+ })+}++pub async fn fetch_routing_region_for_uas(+ state: &SessionState,+ merchant_id: common_utils::id_type::MerchantId,+ organization_id: common_utils::id_type::OrganizationId,+) -> RouterResult<RoutingRegion> {+ let merchant_path =+ fetch_region(state, &merchant_id.get_threeds_routing_region_uas_key()).await;++ Ok(merchant_path+ .async_unwrap_or_else(|| async {+ fetch_region(state, &organization_id.get_threeds_routing_region_uas_key())+ .await+ .unwrap_or(RoutingRegion::Region1)+ })+ .await)+}++async fn fetch_region(state: &SessionState, key: &str) -> Option<RoutingRegion> {+ let db = &*state.store;+ db.find_config_by_key(key)+ .await+ .inspect_err(|err| {+ router_env::logger::error!("Failed to fetch region for key as {err}");+ })+ .ok()+ .map(|conf| RoutingRegion::from_str(&conf.config).unwrap_or(RoutingRegion::Region1))+}diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rsindex d571283077..27bbb17055 100644--- a/crates/router/src/core/webhooks/incoming.rs+++ b/crates/router/src/core/webhooks/incoming.rs@@ -16,13 +16,17 @@ use common_utils::{};use diesel_models::{refund as diesel_refund, ConnectorMandateReferenceId};use error_stack::{report, ResultExt};+use hyperswitch_connectors::connectors::unified_authentication_service::transformers::WebhookResponse;#[cfg(feature = "payouts")]use hyperswitch_domain_models::payouts::payouts::PayoutsUpdate;use hyperswitch_domain_models::{mandates::CommonMandateReference,merchant_key_store::MerchantKeyStore,payments::{payment_attempt::PaymentAttempt, HeaderPayload},- router_request_types::VerifyWebhookSourceRequestData,+ router_request_types::{+ unified_authentication_service::UasAuthenticationResponseData,+ VerifyWebhookSourceRequestData,+ },router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus},};use hyperswitch_interfaces::webhooks::{IncomingWebhookFlowError, IncomingWebhookRequestDetails};@@ -39,7 +43,11 @@ use crate::{metrics, payment_methods,payment_methods::cards,payments::{self, tokenization, PaymentIntentStateMetadataExt},- refunds, relay, unified_connector_service, utils as core_utils,+ refunds, relay,+ unified_authentication_service::{+ types::UNIFIED_AUTHENTICATION_SERVICE, utils as uas_utils,+ },+ unified_connector_service, utils as core_utils,webhooks::{network_tokenization_incoming, utils::construct_webhook_router_data},},db::StorageInterface,@@ -220,7 +228,6 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(platform.get_processor().get_account().get_id().clone())),);-let request_details = IncomingWebhookRequestDetails {method: req.method().clone(),uri: req.uri().clone(),@@ -229,89 +236,124 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(body: &body,};- // Fetch the merchant connector account to get the webhooks source secret- let (merchant_connector_account, connector, connector_name) =- fetch_optional_mca_and_connector(&state, &platform, connector_name_or_mca_id).await?;+ // Fetch Threeds Execution Path to decode webhook Body+ // Checks if the merchant and connector is eligible for authentication service+ // If Yes, then it will return UnifiedAuthenticationService+ // If No, then it will return Direct+ // Direct Signifies its not a authentication connector+ let three_ds_execution_path =+ fetch_three_ds_execution_path(&platform, connector_name_or_mca_id, &state).await?;- // Determine webhook processing path (Direct vs UCS vs Shadow UCS) and handle event type extraction- let execution_path =- unified_connector_service::should_call_unified_connector_service_for_webhooks(- &state,- &platform,- &connector_name,- )- .await?;+ // Decodes webhook body based on execution path, and returns connector Integration, connector_name and webhook_processing_result back to the flow without disturbing the current flow+ let (connector, connector_name, webhook_processing_result) = match three_ds_execution_path {+ ThreeDsProcessingMode::UnifiedAuthenticationService(ref mca_data) => {+ // Mutating connector to Unified Authentication Service from connector_name since for authentication we need to go to authentication service connector integration+ let connector_name = mca_data.connector_name.clone();- let webhook_processing_result = match execution_path {- common_enums::ExecutionPath::UnifiedConnectorService => {- logger::info!(- connector = connector_name,- "Using Unified Connector Service for webhook processing",- );- process_ucs_webhook_transform(- &state,- &platform,- &connector_name,- &body,- &request_details,- merchant_connector_account.as_ref(),- )- .await- }- common_enums::ExecutionPath::ShadowUnifiedConnectorService => {- logger::info!(- connector = connector_name,- "Using Shadow Unified Connector Service for webhook processing",- );- process_shadow_ucs_webhook_transform(+ let (uas_connector, _) =+ get_connector_by_connector_name(&state, UNIFIED_AUTHENTICATION_SERVICE, None)?;++ let webhook_processing_result = process_uas_incoming_webhook(&state,- &platform,- &connector,- &connector_name,- &body,&request_details,- merchant_connector_account.as_ref(),+ connector_name.clone(),+ uas_connector.clone(),+ platform.clone(),)- .await+ .await;++ (uas_connector, connector_name, webhook_processing_result)}- common_enums::ExecutionPath::Direct => {- logger::info!(- connector = connector_name,- "Using Direct connector processing for webhook",- );- // DIRECT PATH: Need to decode body first- let decoded_body = connector- .decode_webhook_body(- &request_details,- platform.get_processor().get_account().get_id(),- merchant_connector_account- .clone()- .and_then(|mca| mca.connector_webhook_details.clone()),- &connector_name,+ ThreeDsProcessingMode::Direct(ref mca_data) => {+ let connector = mca_data.connector.clone();+ let connector_name = mca_data.connector_name.clone();++ // Determine webhook processing path (Direct vs UCS vs Shadow UCS) and handle event type extraction+ let execution_path =+ unified_connector_service::should_call_unified_connector_service_for_webhooks(+ &state,+ &platform,+ &mca_data.connector_name,)- .await- .switch()- .attach_printable("There was an error in incoming webhook body decoding")?;+ .await?;- process_non_ucs_webhook(- &state,- &platform,- &connector,- &connector_name,- decoded_body.into(),- &request_details,- )- .await+ let webhook_processing_result = match execution_path {+ common_enums::ExecutionPath::UnifiedConnectorService => {+ logger::info!(+ connector = connector_name,+ "Using Unified Connector Service for webhook processing",+ );+ process_ucs_webhook_transform(+ &state,+ &platform,+ &mca_data.connector_name,+ &body,+ &request_details,+ mca_data.merchant_connector_account.as_ref(),+ )+ .await+ }++ common_enums::ExecutionPath::ShadowUnifiedConnectorService => {+ logger::info!(+ connector = connector_name,+ "Using Shadow Unified Connector Service for webhook processing",+ );+ process_shadow_ucs_webhook_transform(+ &state,+ &platform,+ &mca_data.connector,+ &mca_data.connector_name,+ &body,+ &request_details,+ mca_data.merchant_connector_account.as_ref(),+ )+ .await+ }++ common_enums::ExecutionPath::Direct => {+ logger::info!(+ connector = connector_name,+ "Using Direct connector processing for webhook",+ );+ // DIRECT PATH: Need to decode body first+ let decoded_body = mca_data+ .connector+ .decode_webhook_body(+ &request_details,+ platform.get_processor().get_account().get_id(),+ mca_data+ .merchant_connector_account+ .clone()+ .and_then(|mca| mca.connector_webhook_details.clone()),+ &mca_data.connector_name,+ )+ .await+ .switch()+ .attach_printable("There was an error in incoming webhook body decoding")?;++ process_non_ucs_webhook(+ &state,+ &platform,+ &mca_data.connector,+ &mca_data.connector_name,+ decoded_body.into(),+ &request_details,+ )+ .await+ }+ };++ (connector, connector_name, webhook_processing_result)}};-let mut webhook_processing_result = match webhook_processing_result {Ok(result) => result,Err(error) => {let error_result = handle_incoming_webhook_error(error,&connector,- connector_name.as_str(),+ &connector_name,&request_details,platform.get_processor().get_account().get_id(),);@@ -434,6 +476,46 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(Ok((response, webhook_effect, serialized_request))}+async fn fetch_three_ds_execution_path(+ platform: &domain::Platform,+ connector_name_or_mca_id: &str,+ state: &SessionState,+) -> errors::RouterResult<ThreeDsProcessingMode> {+ let (merchant_connector_account, connector, connector_name) =+ fetch_optional_mca_and_connector(state, platform, connector_name_or_mca_id).await?;++ let mca_details = MerchantConnectorDetails {+ merchant_connector_account,+ connector,+ connector_name: connector_name.clone(),+ };++ let eligible_connector_list = state+ .conf+ .authentication_service_enabled_connectors+ .connector_list+ .clone();+ let connector_enum = 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 is_merchant_eligible_for_uas =+ payments::helpers::is_merchant_eligible_authentication_service(+ &platform.get_processor().get_account().get_id().clone(),+ state,+ )+ .await?;++ if is_merchant_eligible_for_uas && eligible_connector_list.contains(&connector_enum) {+ Ok(ThreeDsProcessingMode::UnifiedAuthenticationService(+ mca_details,+ ))+ } else {+ Ok(ThreeDsProcessingMode::Direct(mca_details))+ }+}+/// Process UCS webhook transformation using the high-level UCS abstractionasync fn process_ucs_webhook_transform<'a>(state: &'a SessionState,@@ -475,11 +557,28 @@ pub struct ShadowUcsData<'a> {/// Result type for webhook processing path determinationpub struct WebhookProcessingResult<'a> {- event_type: webhooks::IncomingWebhookEvent,- source_verified: bool,- transform_data: Option<Box<unified_connector_service::WebhookTransformData>>,- decoded_body: Option<actix_web::web::Bytes>,- shadow_ucs_data: Option<ShadowUcsData<'a>>,+ pub event_type: webhooks::IncomingWebhookEvent,+ pub source_verified: bool,+ pub transform_data: Option<Box<unified_connector_service::WebhookTransformData>>,+ pub decoded_body: Option<actix_web::web::Bytes>,+ pub shadow_ucs_data: Option<ShadowUcsData<'a>>,+}++#[derive(Clone, Debug)]+pub struct MerchantConnectorDetails {+ /// Merchant Connector Account+ pub merchant_connector_account:+ Option<hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount>,+ /// Connector+ pub connector: ConnectorEnum,+ pub connector_name: String,+}++#[derive(Clone, Debug)]+/// Indicates the execution path through which the authentication is processed.+pub enum ThreeDsProcessingMode {+ Direct(MerchantConnectorDetails),+ UnifiedAuthenticationService(MerchantConnectorDetails),}/// Process shadow UCS webhook transformation with dual execution (UCS + Direct)@@ -3253,3 +3352,97 @@ fn insert_mandate_details()?;Ok(connector_mandate_details)}++#[cfg(feature = "v1")]+pub async fn process_uas_incoming_webhook<'a>(+ state: &'a SessionState,+ incoming_webhook_request: &IncomingWebhookRequestDetails<'a>,+ connector_name: String,+ connector_integration: ConnectorEnum,+ platform: domain::Platform,+) -> errors::RouterResult<WebhookProcessingResult<'a>> {+ let routing_region = uas_utils::fetch_routing_region_for_uas(+ state,+ platform.get_processor().get_account().get_id().clone(),+ platform+ .get_processor()+ .get_account()+ .organization_id+ .clone(),+ )+ .await?;+ let webhook_data =+ uas_utils::get_webhook_request_data_for_uas(incoming_webhook_request, Some(routing_region));++ let webhook_router_data: hyperswitch_domain_models::types::UasProcessWebhookRouterData =+ uas_utils::construct_uas_webhook_router_data(+ state,+ connector_name.to_string(),+ webhook_data,+ None,+ )?; // check of paymentId is present++ let response = uas_utils::do_auth_connector_call(+ state,+ UNIFIED_AUTHENTICATION_SERVICE.to_string(),+ webhook_router_data,+ )+ .await?;++ let response_body = match response.response {+ Ok(resp) => match resp {+ UasAuthenticationResponseData::Webhook {+ trans_status,+ authentication_value,+ eci,+ three_ds_server_transaction_id,+ authentication_id,+ results_request,+ results_response,+ } => Ok(WebhookResponse {+ trans_status,+ authentication_value,+ eci,+ three_ds_server_transaction_id,+ authentication_id,+ results_request,+ results_response,+ }),+ _ => {+ router_env::logger::error!("received unknown webhook response from uas");+ Err(errors::ApiErrorResponse::WebhookProcessingFailure)+ }+ },+ Err(err) => {+ router_env::logger::error!("error processing webhook {:?}", err);+ Err(errors::ApiErrorResponse::WebhookProcessingFailure)+ }+ }?;++ let event_type = connector_integration+ .get_webhook_event_type(incoming_webhook_request)+ .switch()+ .attach_printable("Could not get webhook event")?;++ let decoded_body = response_body+ .to_bytes()+ .inspect_err(|err| {+ router_env::logger::error!("error converting uas webhook response to bytes: {}", err);+ })+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("error converting uas webhook response to bytes")?;++ // The payload in `decoded_body` is not taken directly from an external caller.+ // It is the response from the Unified Authentication Service obtained via+ // `utils::do_auth_connector_call`, which uses the router's authenticated+ // connector infrastructure. As such, we consider the source to be verified.+ let webhook_result = WebhookProcessingResult {+ event_type,+ source_verified: false,+ transform_data: None,+ decoded_body: Some(decoded_body),+ shadow_ucs_data: None,+ };++ Ok(webhook_result)+}