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
refactor: Incoming webhook core to trait based and bumping up ucs new parseEvent webhook changes, adding shadow mode diff (#11922)
gopikrishna000162d2f8a4ba2
diff --git a/Cargo.lock b/Cargo.lockindex f02e035791..d3afd4af68 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2232,7 +2232,7 @@ dependencies = [[[package]]name = "config_patch_derive"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?rev=2dcbcf76ff0411d8718172ab9e30c5be9688349e#2dcbcf76ff0411d8718172ab9e30c5be9688349e"+source = "git+https://github.com/juspay/connector-service?rev=59d3a57e08727945362d916585a90935a375ef3b#59d3a57e08727945362d916585a90935a375ef3b"dependencies = ["proc-macro2","quote",@@ -3948,7 +3948,7 @@ checksum = "32619942b8be646939eaf3db0602b39f5229b74575b67efc897811ded1db4e57"[[package]]name = "grpc-api-types"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?rev=2dcbcf76ff0411d8718172ab9e30c5be9688349e#2dcbcf76ff0411d8718172ab9e30c5be9688349e"+source = "git+https://github.com/juspay/connector-service?rev=59d3a57e08727945362d916585a90935a375ef3b#59d3a57e08727945362d916585a90935a375ef3b"dependencies = ["axum 0.8.4","error-stack 0.5.0",@@ -8116,7 +8116,7 @@ dependencies = [[[package]]name = "rust-grpc-client"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?rev=2dcbcf76ff0411d8718172ab9e30c5be9688349e#2dcbcf76ff0411d8718172ab9e30c5be9688349e"+source = "git+https://github.com/juspay/connector-service?rev=59d3a57e08727945362d916585a90935a375ef3b#59d3a57e08727945362d916585a90935a375ef3b"dependencies = ["grpc-api-types",]@@ -10944,7 +10944,7 @@ checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9"[[package]]name = "ucs_cards"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?rev=2dcbcf76ff0411d8718172ab9e30c5be9688349e#2dcbcf76ff0411d8718172ab9e30c5be9688349e"+source = "git+https://github.com/juspay/connector-service?rev=59d3a57e08727945362d916585a90935a375ef3b#59d3a57e08727945362d916585a90935a375ef3b"dependencies = ["bytes 1.10.1","error-stack 0.4.1",@@ -10960,7 +10960,7 @@ dependencies = [[[package]]name = "ucs_common_enums"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?rev=2dcbcf76ff0411d8718172ab9e30c5be9688349e#2dcbcf76ff0411d8718172ab9e30c5be9688349e"+source = "git+https://github.com/juspay/connector-service?rev=59d3a57e08727945362d916585a90935a375ef3b#59d3a57e08727945362d916585a90935a375ef3b"dependencies = ["serde","strum 0.26.3",@@ -10971,7 +10971,7 @@ dependencies = [[[package]]name = "ucs_common_utils"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?rev=2dcbcf76ff0411d8718172ab9e30c5be9688349e#2dcbcf76ff0411d8718172ab9e30c5be9688349e"+source = "git+https://github.com/juspay/connector-service?rev=59d3a57e08727945362d916585a90935a375ef3b#59d3a57e08727945362d916585a90935a375ef3b"dependencies = ["anyhow","base64 0.21.7",diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 7ea0329311..bb57b46619 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -802,7 +802,6 @@ pub enum CallConnectorAction {},HandleResponse(Vec<u8>),UCSConsumeResponse(Vec<u8>),- UCSHandleResponse(Vec<u8>),HandleResponseWithoutBuildRequest,}diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.tomlindex 6f67bcdd2e..888d6768c6 100644--- a/crates/external_services/Cargo.toml+++ b/crates/external_services/Cargo.toml@@ -73,7 +73,8 @@ 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 = "2dcbcf76ff0411d8718172ab9e30c5be9688349e", package = "rust-grpc-client" }++unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "59d3a57e08727945362d916585a90935a375ef3b", package = "rust-grpc-client" }open-feature = { version = "0.2.5", optional = true }superposition_provider = { version = "0.102.0", optional = true}superposition_types = "0.102.0"diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rsindex 04f7f27337..6815b70128 100644--- a/crates/external_services/src/grpc_client/unified_connector_service.rs+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs@@ -811,6 +811,41 @@ impl UnifiedConnectorServiceClient {})}+ /// Phase 1 of the two-phase UCS webhook API.+ ///+ /// Parses the raw inbound webhook payload to extract a typed `EventReference` and the+ /// `WebhookEventType`, without requiring credentials or making any outbound connector+ /// call. The caller uses the returned reference to resolve the merchant-connector+ /// account (and thus the webhook secret) before invoking `incoming_webhook_handle_event`.+ pub async fn incoming_webhook_parse_event(+ &self,+ incoming_webhook_parse_event_request: payments_grpc::EventServiceParseRequest,+ connector_auth_metadata: ConnectorAuthMetadata,+ grpc_headers: GrpcHeadersUcs,+ ) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::EventServiceParseResponse>>+ {+ let mut request = tonic::Request::new(incoming_webhook_parse_event_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.event_service_client+ .clone()+ .parse_event(request)+ .await+ .change_context(UnifiedConnectorServiceError::IncomingWebhookParseEventFailure)+ .inspect_err(|error| {+ logger::error!(+ grpc_error=?error,+ method="incoming_webhook_parse_event",+ connector_name=?connector_name,+ "UCS incoming webhook parse event gRPC call failed"+ )+ })+ }+/// Performs Payment Refundpub async fn payment_refund(&self,diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.tomlindex 0306e3fe8f..a666cc67c3 100644--- a/crates/hyperswitch_interfaces/Cargo.toml+++ b/crates/hyperswitch_interfaces/Cargo.toml@@ -30,7 +30,8 @@ strum = { version = "0.26", features = ["derive"] }thiserror = "1.0.69"time = "0.3.41"url = { version = "2.5.4", features = ["serde"] }-unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "2dcbcf76ff0411d8718172ab9e30c5be9688349e", package = "rust-grpc-client" }++unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "59d3a57e08727945362d916585a90935a375ef3b", package = "rust-grpc-client" }tokio = { version = "1.45.1", features = ["macros", "rt-multi-thread"] }# First party cratesdiff --git a/crates/hyperswitch_interfaces/src/api_client.rs b/crates/hyperswitch_interfaces/src/api_client.rsindex 005d525aa9..8f0742168e 100644--- a/crates/hyperswitch_interfaces/src/api_client.rs+++ b/crates/hyperswitch_interfaces/src/api_client.rs@@ -164,10 +164,9 @@ where};connector_integration.handle_response(req, None, response)}- common_enums::CallConnectorAction::UCSConsumeResponse(_)- | common_enums::CallConnectorAction::UCSHandleResponse(_) => {+ common_enums::CallConnectorAction::UCSConsumeResponse(_) => {Err(ConnectorError::ProcessingStepFailed(Some(- "CallConnectorAction UCSHandleResponse/UCSConsumeResponse used in Direct gateway system flow. These actions are only valid in UCS gateway system"+ "CallConnectorAction UCSConsumeResponse used in Direct gateway system flow. This action is only valid in UCS gateway system".to_string().into(),))diff --git a/crates/hyperswitch_interfaces/src/helpers.rs b/crates/hyperswitch_interfaces/src/helpers.rsindex 8756dd1f76..f7a6550c9a 100644--- a/crates/hyperswitch_interfaces/src/helpers.rs+++ b/crates/hyperswitch_interfaces/src/helpers.rs@@ -1,6 +1,8 @@use common_utils::{consts::{X_CONNECTOR_NAME, X_SUB_FLOW_NAME},- errors as common_utils_errors, request,+ errors as common_utils_errors,+ ext_traits::Encode,+ request,};use error_stack::ResultExt;use hyperswitch_domain_models::router_data;@@ -94,7 +96,47 @@ pub async fn serialize_comparison_results_and_send<S, F, RouterDReq, RouterDResprequest_id,).await- .inspect_err(|e| logger::debug!("Failed to send comparison data: {:?}", e));+ .inspect_err(|e| logger::warn!("Failed to send comparison data: {:?}", e));+}++/// Webhook-flow analogue of `serialize_router_data_and_send_to_comparison_service`.+pub async fn serialize_webhook_outcome_and_send_to_comparison_service<P, S>(+ state: &dyn api_client::ApiClientWrapper,+ primary: &P,+ shadow: &S,+ comparison_service_config: types::ComparisonServiceConfig,+ connector_name: String,+ request_id: Option<String>,+) where+ P: serde::Serialize + std::fmt::Debug,+ S: serde::Serialize + std::fmt::Debug,+{+ let to_masked =+ |value: common_utils_errors::CustomResult<+ serde_json::Value,+ common_utils_errors::ParsingError,+ >,+ source: &str| {+ hyperswitch_masking::Secret::new(value.unwrap_or_else(+ |e| serde_json::json!({ "error": e.to_string(), "source": source }),+ ))+ };+ let comparison_data = ComparisonData {+ hyperswitch_data: to_masked(primary.encode_to_value(), "hyperswitch"),+ unified_connector_service_data: to_masked(shadow.encode_to_value(), "ucs"),+ };+ if let Err(error) = send_comparison_data(+ state,+ comparison_data,+ comparison_service_config,+ connector_name,+ Some("webhook".to_string()),+ request_id,+ )+ .await+ {+ logger::warn!(?error, "Failed to send webhook comparison data");+ }}/// Sends router data comparison to external servicediff --git a/crates/hyperswitch_interfaces/src/unified_connector_service.rs b/crates/hyperswitch_interfaces/src/unified_connector_service.rsindex 4235180a3a..7054829cd2 100644--- a/crates/hyperswitch_interfaces/src/unified_connector_service.rs+++ b/crates/hyperswitch_interfaces/src/unified_connector_service.rs@@ -11,9 +11,7 @@ use crate::helpers::ForeignTryFrom;/// Unified Connector Service (UCS) related transformerspub mod transformers;-pub use transformers::{- UnifiedConnectorServiceError, WebhookTransformData, WebhookTransformationStatus,-};+pub use transformers::UnifiedConnectorServiceError;/// Type alias for return type used by unified connector service response handlerstype UnifiedConnectorServiceResult = CustomResult<@@ -45,24 +43,22 @@ pub fn get_payments_response_from_ucs_webhook_content(event_content: payments_grpc::EventContent,) -> CustomResult<payments_grpc::PaymentServiceGetResponse, UnifiedConnectorServiceError> {match event_content.content {- Some(unified_connector_service_client::payments::event_content::Content::PaymentsResponse(payments_response)) => {- Ok(payments_response)- },- Some(unified_connector_service_client::payments::event_content::Content::RefundsResponse(_)) => {- Err(UnifiedConnectorServiceError::WebhookProcessingFailure)- .attach_printable("UCS webhook contains refunds response but payments response was expected")?- },- Some(unified_connector_service_client::payments::event_content::Content::DisputesResponse(_)) => {- Err(UnifiedConnectorServiceError::WebhookProcessingFailure)- .attach_printable("UCS webhook contains disputes response but payments response was expected")?- },- Some(unified_connector_service_client::payments::event_content::Content::IncompleteTransformation(_)) => {- Err(UnifiedConnectorServiceError::WebhookProcessingFailure)- .attach_printable("UCS webhook contains incomplete transformation but payments response was expected")?- },- None => {- Err(UnifiedConnectorServiceError::WebhookProcessingFailure)- .attach_printable("Missing payments response in UCS webhook content")?- }+ Some(+ unified_connector_service_client::payments::event_content::Content::PaymentsResponse(+ payments_response,+ ),+ ) => Ok(payments_response),+ Some(+ unified_connector_service_client::payments::event_content::Content::RefundsResponse(_),+ ) => Err(UnifiedConnectorServiceError::WebhookProcessingFailure).attach_printable(+ "UCS webhook contains refunds response but payments response was expected",+ )?,+ Some(+ unified_connector_service_client::payments::event_content::Content::DisputesResponse(_),+ ) => Err(UnifiedConnectorServiceError::WebhookProcessingFailure).attach_printable(+ "UCS webhook contains disputes response but payments response was expected",+ )?,+ None => Err(UnifiedConnectorServiceError::WebhookProcessingFailure)+ .attach_printable("Missing payments response in UCS webhook content")?,}}diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rsindex 063ec8395e..05bf86ea6d 100644--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs@@ -154,6 +154,10 @@ pub enum UnifiedConnectorServiceError {#[error("Failed to handle incoming webhook event from gRPC Server")]IncomingWebhookHandleEventFailure,+ /// Failed to parse incoming webhook event from gRPC Server+ #[error("Failed to parse incoming webhook event from gRPC Server")]+ IncomingWebhookParseEventFailure,+/// Failed to perform Payment Void from gRPC Server#[error("Failed to perform Void from gRPC Server")]PaymentVoidFailure,@@ -195,26 +199,6 @@ pub enum UnifiedConnectorServiceError {PayoutEnrollDisburseAccountFailure,}-/// UCS Webhook transformation status-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]-pub enum WebhookTransformationStatus {- /// Transformation completed successfully, no further action needed- Complete,- /// Transformation incomplete, requires second call for final status- Incomplete,-}--#[allow(missing_docs)]-/// 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,- pub webhook_content: Option<payments_grpc::EventContent>,- pub response_ref_id: Option<String>,- pub webhook_transformation_status: WebhookTransformationStatus,-}-impl ForeignTryFrom<(payments_grpc::PaymentServiceGetResponse, AttemptStatus)>for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>{diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 5bac2d6b94..bacf80adef 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -88,8 +88,9 @@ reqwest = { version = "0.11.27", features = ["json", "rustls-tls", "gzip", "multring = "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 = "2dcbcf76ff0411d8718172ab9e30c5be9688349e", package = "rust-grpc-client" }-unified-connector-service-cards = { git = "https://github.com/juspay/connector-service", rev = "2dcbcf76ff0411d8718172ab9e30c5be9688349e", package = "ucs_cards" }++unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "59d3a57e08727945362d916585a90935a375ef3b", package = "rust-grpc-client" }+unified-connector-service-cards = { git = "https://github.com/juspay/connector-service", rev = "59d3a57e08727945362d916585a90935a375ef3b", package = "ucs_cards" }rustc-hash = "1.1.0"rustls = "0.22"rustls-pemfile = "2"diff --git a/crates/router/src/core/payments/gateway/psync_gateway.rs b/crates/router/src/core/payments/gateway/psync_gateway.rsindex 8ab806f24e..9843115e40 100644--- a/crates/router/src/core/payments/gateway/psync_gateway.rs+++ b/crates/router/src/core/payments/gateway/psync_gateway.rs@@ -115,7 +115,7 @@ whereOk(router_data.clone())}- CallConnectorAction::UCSHandleResponse(_) | CallConnectorAction::Trigger => {+ CallConnectorAction::Trigger => {let connector_name = router_data.connector.clone();let connector_enum =common_enums::connector_enums::Connector::from_str(&connector_name)@@ -151,12 +151,9 @@ where.attach_printable("Failed to fetch Unified Connector Service client")?;let payment_get_request =- payments_grpc::PaymentServiceGetRequest::foreign_try_from((- router_data,- call_connector_action,- ))- .change_context(ConnectorError::RequestEncodingFailed)- .attach_printable("Failed to construct Payment Get Request")?;+ payments_grpc::PaymentServiceGetRequest::foreign_try_from(router_data)+ .change_context(ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to construct Payment Get Request")?;let connector_auth_metadata =unified_connector_service::build_unified_connector_service_auth_metadata(diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex af18472196..825928a520 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -35,7 +35,7 @@ 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, ClassicReward,- CryptoCurrency, EVoucher, OpenBanking, PaymentServiceAuthorizeResponse, ProxyCardDetails,+ CryptoCurrency, EVoucher, OpenBanking, PaymentServiceAuthorizeResponse,};#[cfg(feature = "v2")]@@ -206,9 +206,6 @@ pub async fn set_access_token_for_ucs(Ok(())}-// Re-export webhook transformer types for easier access-pub use transformers::{WebhookTransformData, WebhookTransformationStatus};-/// Type alias for return type used by unified connector service response handlerstype UnifiedConnectorServiceResult = CustomResult<(@@ -342,10 +339,9 @@ where// Single decision point using pattern matchinglet (gateway_system, mut execution_path) = if ucs_availability == UcsAvailability::Disabled {match call_connector_action {- CallConnectorAction::UCSConsumeResponse(_)- | CallConnectorAction::UCSHandleResponse(_) => {+ CallConnectorAction::UCSConsumeResponse(_) => {Err(errors::ApiErrorResponse::InternalServerError)- .attach_printable("CallConnectorAction UCSHandleResponse/UCSConsumeResponse received but UCS is disabled. These actions are only valid in UCS gateway")?+ .attach_printable("CallConnectorAction UCSConsumeResponse received but UCS is disabled. This action is only valid in UCS gateway")?}CallConnectorAction::Avoid| CallConnectorAction::Trigger@@ -358,9 +354,10 @@ where}} else {match call_connector_action {- CallConnectorAction::UCSConsumeResponse(_)- | CallConnectorAction::UCSHandleResponse(_) => {- router_env::logger::info!("CallConnectorAction UCSHandleResponse/UCSConsumeResponse received, using UCS gateway");+ CallConnectorAction::UCSConsumeResponse(_) => {+ router_env::logger::info!(+ "CallConnectorAction UCSConsumeResponse received, using UCS gateway"+ );(GatewaySystem::UnifiedConnectorService,ExecutionPath::UnifiedConnectorService,@@ -1048,14 +1045,12 @@ pub fn build_unified_connector_service_payment_method(})}hyperswitch_domain_models::payment_method_data::BankRedirectData::Eft {- provider+ provider,} => {- let eft = payments_grpc::EftBankRedirect {- provider,- };+ let eft_bank_redirect = payments_grpc::EftBankRedirect { provider };Ok(payments_grpc::PaymentMethod {- payment_method: Some(PaymentMethod::EftBankRedirect(eft)),+ payment_method: Some(PaymentMethod::EftBankRedirect(eft_bank_redirect)),})}hyperswitch_domain_models::payment_method_data::BankRedirectData::BancontactCard {@@ -1688,7 +1683,7 @@ pub fn build_unified_connector_service_payment_method_for_external_proxy(.card_network.clone().map(payments_grpc::CardNetwork::foreign_from);- let card_details = ProxyCardDetails {+ let card_details = payments_grpc::ProxyCardDetails {card_number: Some(external_vault_card.card_number.expose().into()),card_exp_month: Some(external_vault_card.card_exp_month.expose().into()),card_exp_year: Some(external_vault_card.card_exp_year.expose().into()),@@ -2496,133 +2491,6 @@ pub fn build_webhook_secrets_from_merchant_connector_account(}}-/// 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,- processor: &Processor,- 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!(errors::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,- processor.get_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,- processor,- connector_name.to_string(),- )- })- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to build UCS auth metadata")?- .ok_or_else(|| {- error_stack::report!(errors::ApiErrorResponse::InternalServerError).attach_printable(- "Missing merchant connector account for UCS webhook transformation",- )- })?;- let profile_id = merchant_connector_account- .as_ref()- .map(|mca| mca.profile_id.clone())- .unwrap_or(consts::PROFILE_ID_UNAVAILABLE.clone());- // Build gRPC headers- let grpc_headers = state- .get_grpc_headers_ucs(ExecutionMode::Primary)- .lineage_ids(LineageIds::new(- processor.get_account().get_id().clone(),- profile_id,- ))- .external_vault_proxy_metadata(None)- .merchant_reference_id(None)- .resource_id(None)- .build();-- // Make UCS call - client availability already verified- match ucs_client- .incoming_webhook_handle_event(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(errors::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::EventContent> {- 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.@@ -2907,6 +2775,80 @@ where})}+/// UCS wrapper for webhook flows. It centralizes header building and handler+/// invocation plus masked request/response logging, and takes no+/// `RouterData` — incoming webhooks don't have one at the UCS call site. `flow` is+/// the gRPC method label (e.g. `"EventServiceParseEvent"`).+#[allow(clippy::too_many_arguments)]+#[instrument(skip_all, fields(connector_name, flow_type))]+pub async fn ucs_webhook_logging_wrapper<F, Fut, GrpcReq, GrpcResp>(+ _state: &SessionState,+ connector_name: String,+ flow: &'static str,+ grpc_request: GrpcReq,+ grpc_header_builder: external_services::grpc_client::GrpcHeadersUcsBuilderFinal,+ handler: F,+) -> RouterResult<GrpcResp>+where+ GrpcReq: serde::Serialize,+ GrpcResp: serde::Serialize,+ F: FnOnce(GrpcReq, external_services::grpc_client::GrpcHeadersUcs) -> Fut + Send,+ Fut: std::future::Future<Output = RouterResult<GrpcResp>> + Send,+{+ tracing::Span::current().record("connector_name", &connector_name);+ tracing::Span::current().record("flow_type", flow);++ let grpc_header = grpc_header_builder.build();+ let grpc_request_body =+ hyperswitch_masking::masked_serialize(&grpc_request).unwrap_or_else(|error| {+ logger::warn!(+ ?error,+ "Failed to mask-serialize UCS webhook gRPC request for logging"+ );+ serde_json::json!({"error": "failed_to_serialize_grpc_request"})+ });+ logger::info!(+ flow,+ ucs_webhook_grpc_request = ?grpc_request_body,+ "UCS webhook gRPC request"+ );++ let start_time = Instant::now();+ let result = handler(grpc_request, grpc_header).await;+ let external_latency = start_time.elapsed().as_millis();++ let router_result = match result {+ Ok(grpc_response) => {+ let grpc_response_body = hyperswitch_masking::masked_serialize(&grpc_response)+ .unwrap_or_else(|error| {+ logger::warn!(+ ?error,+ "Failed to mask-serialize UCS webhook gRPC response for logging"+ );+ serde_json::json!({"error": "failed_to_serialize_grpc_response"})+ });+ logger::info!(+ flow,+ external_latency,+ ucs_webhook_grpc_response = ?grpc_response_body,+ "UCS webhook gRPC response"+ );+ Ok(grpc_response)+ }+ Err(error) => {+ logger::warn!(+ flow,+ external_latency,+ ?error,+ "UCS webhook gRPC call failed"+ );+ Err(error)+ }+ };++ router_result+}+// ============================================================================// REFUND UCS FUNCTIONS// ============================================================================diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex 261dd450ed..71444bfcb6 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -38,10 +38,7 @@ use hyperswitch_domain_models::{};pub use hyperswitch_interfaces::{helpers::ForeignTryFrom,- unified_connector_service::{- transformers::convert_connector_service_status_code, WebhookTransformData,- WebhookTransformationStatus,- },+ unified_connector_service::transformers::convert_connector_service_status_code,};use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};use router_env::tracing;@@ -49,11 +46,11 @@ use time::{Duration, OffsetDateTime};use unified_connector_service_cards::{CardNumber, NetworkToken};use unified_connector_service_client::payments::{self as payments_grpc, client_authentication_token_data, ConnectorState,- EventServiceHandleRequest, EventServiceHandleResponse,+ EventServiceHandleRequest, EventServiceParseRequest,};use crate::{- core::{errors, mandate::MandateBehaviour, unified_connector_service},+ core::{mandate::MandateBehaviour, unified_connector_service},types::{api,transformers::{self, ForeignFrom},@@ -649,19 +646,13 @@ impl}}-impl- transformers::ForeignTryFrom<(- &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,- common_enums::CallConnectorAction,- )> for payments_grpc::PaymentServiceGetRequest+impl transformers::ForeignTryFrom<&RouterData<PSync, PaymentsSyncData, PaymentsResponseData>>+ for payments_grpc::PaymentServiceGetRequest{type Error = error_stack::Report<UnifiedConnectorServiceError>;fn foreign_try_from(- (router_data, call_connector_action): (- &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,- common_enums::CallConnectorAction,- ),+ router_data: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,) -> Result<Self, Self::Error> {let connector_transaction_id = router_data.request@@ -682,21 +673,6 @@ impllet currency = payments_grpc::Currency::foreign_try_from(router_data.request.currency)?;- let handle_response = match call_connector_action {- common_enums::CallConnectorAction::UCSHandleResponse(res) => Some(res),- common_enums::CallConnectorAction::Trigger- | common_enums::CallConnectorAction::HandleResponseWithoutBuildRequest => None,- common_enums::CallConnectorAction::HandleResponse(_)- | common_enums::CallConnectorAction::UCSConsumeResponse(_)- | common_enums::CallConnectorAction::Avoid- | common_enums::CallConnectorAction::StatusUpdate { .. } => Err(- UnifiedConnectorServiceError::RequestEncodingFailedWithReason(- "Invalid CallConnectorAction for payment sync call via UCS Gateway system"- .to_string(),- ),- )?,- };-let capture_method = router_data.request.capture_method@@ -719,7 +695,6 @@ implmerchant_transaction_id,encoded_data: router_data.request.encoded_data.clone(),capture_method: capture_method.map(|capture_method| capture_method.into()),- handle_response,setup_future_usage: setup_future_usage.map(|s| s.into()),connector_order_reference_id,amount: Some(payments_grpc::Money {@@ -5659,56 +5634,41 @@ impl}}-/// Transform UCS webhook response into webhook event data-pub fn transform_ucs_webhook_response(- response: EventServiceHandleResponse,-) -> Result<WebhookTransformData, error_stack::Report<errors::ApiErrorResponse>> {- let event_type =- api_models::webhooks::IncomingWebhookEvent::from_ucs_event_type(response.event_type);-- let webhook_transformation_status = if matches!(- response.event_status(),- payments_grpc::EventStatus::Incomplete- ) {- WebhookTransformationStatus::Incomplete- } else {- WebhookTransformationStatus::Complete- };+impl+ transformers::ForeignTryFrom<+ &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,+ > for EventServiceParseRequest+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;- Ok(WebhookTransformData {- event_type,- source_verified: response.source_verified,- webhook_content: response.event_content,- response_ref_id: response.merchant_event_id,- webhook_transformation_status,- })+ fn foreign_try_from(+ request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,+ ) -> Result<Self, Self::Error> {+ let request_details_grpc =+ <payments_grpc::RequestDetails as transformers::ForeignTryFrom<_>>::foreign_try_from(+ request_details,+ )?;+ Ok(Self {+ request_details: Some(request_details_grpc),+ })+ }}-/// Build UCS webhook transform request from webhook components-pub fn build_webhook_transform_request(- _webhook_body: &[u8],+pub fn build_handle_event_request(request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,webhook_secrets: Option<payments_grpc::WebhookSecrets>,- merchant_id: &str,- connector_id: &str,-) -> Result<EventServiceHandleRequest, error_stack::Report<errors::ApiErrorResponse>> {- let request_details_grpc =- <payments_grpc::RequestDetails as transformers::ForeignTryFrom<_>>::foreign_try_from(- request_details,- )- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to transform webhook request details to gRPC format")?;-+ event_context: Option<payments_grpc::EventContext>,+ merchant_event_id: String,+) -> Result<EventServiceHandleRequest, error_stack::Report<UnifiedConnectorServiceError>> {+ let request_details_grpc = <payments_grpc::RequestDetails as transformers::ForeignTryFrom<+ _,+ >>::foreign_try_from(request_details)?;Ok(EventServiceHandleRequest {- merchant_event_id: Some(format!(- "{}_{}_{}",- merchant_id,- connector_id,- OffsetDateTime::now_utc().unix_timestamp()- )),+ merchant_event_id: Some(merchant_event_id),request_details: Some(request_details_grpc),webhook_secrets,- state: None,+ access_token: None,+ event_context,})}diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rsindex 51f0f3a37f..69334e3b47 100644--- a/crates/router/src/core/webhooks.rs+++ b/crates/router/src/core/webhooks.rs@@ -1,4 +1,6 @@#[cfg(feature = "v1")]+pub mod gateway;+#[cfg(feature = "v1")]pub mod incoming;#[cfg(feature = "v2")]mod incoming_v2;diff --git a/crates/router/src/core/webhooks/gateway.rs b/crates/router/src/core/webhooks/gateway.rsnew file mode 100644index 0000000000..b80e975f37--- /dev/null+++ b/crates/router/src/core/webhooks/gateway.rs@@ -0,0 +1,945 @@+//! Gateway abstraction for incoming webhook processing.++use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};+use async_trait::async_trait;+use common_enums::{ExecutionMode, ExecutionPath};+use common_utils::{errors::ReportSwitchExt, ext_traits::Encode};+use error_stack::ResultExt;+use external_services::grpc_client::LineageIds;+use hyperswitch_interfaces::webhooks::{+ IncomingWebhookRequestDetails, WebhookContext, WebhookResourceData,+};+use hyperswitch_masking::{ErasedMaskSerialize, Secret};+use router_env::{logger, tracing::Instrument};+use time::OffsetDateTime;+use unified_connector_service_client::payments as payments_grpc;++#[cfg(feature = "v1")]+use crate::core::payments::helpers::MerchantConnectorAccountType;+use crate::{+ consts,+ core::{+ errors::{self, utils::ConnectorErrorExt, RouterResult},+ metrics,+ unified_connector_service::{+ self, build_unified_connector_service_auth_metadata,+ build_webhook_secrets_from_merchant_connector_account,+ transformers::build_handle_event_request,+ },+ webhooks::{+ incoming::get_payment_attempt_from_object_reference_id, utils as webhook_utils,+ MERCHANT_ID,+ },+ },+ routes::SessionState,+ services::{self, connector_integration_interface::ConnectorEnum},+ types::{api::IncomingWebhook, domain, transformers::ForeignTryFrom},+ utils as helper_utils,+};++/// JSON bytes of the webhook resource. `Direct` is the connector-native shape+/// (parsed by the connector); `UnifiedConnectorService` is a UCS `EventContent`+/// (consumed directly by downstream PSync).+#[derive(Debug, Clone)]+#[non_exhaustive]+pub enum WebhookContent {+ Direct(Vec<u8>),+ UnifiedConnectorService(Vec<u8>),+}++impl WebhookContent {+ pub fn bytes(&self) -> &[u8] {+ match self {+ Self::Direct(b) | Self::UnifiedConnectorService(b) => b,+ }+ }++ pub fn into_bytes(self) -> Vec<u8> {+ match self {+ Self::Direct(b) | Self::UnifiedConnectorService(b) => b,+ }+ }+}++/// Outcome of a single inbound-webhook processing run.+pub enum WebhookOutcome {+ Skipped {+ reference: Option<ObjectReferenceId>,+ event_type: IncomingWebhookEvent,+ ack_response: services::ApplicationResponse<serde_json::Value>,+ },+ Processed {+ reference: ObjectReferenceId,+ event_type: IncomingWebhookEvent,+ source_verified: bool,+ content: WebhookContent,+ /// Full decoded body bytes for the gateway's connector. Direct path sets+ /// this to the decoded body so that downstream connector calls+ /// (get_dispute_details, get_webhook_mandate_details, etc.) see the+ /// structured payload they expect.+ decoded_body: Option<Vec<u8>>,+ /// Pre-fetched resource data (e.g. PaymentAttempt for payment events).+ /// Carried forward so downstream flows can reuse it instead of+ /// issuing an additional DB round-trip.+ webhook_resource_data: Box<Option<WebhookResourceData>>,+ masked_log_payload: common_utils::pii::SecretSerdeValue,+ merchant_connector_account: Box<domain::MerchantConnectorAccount>,+ ack_response: services::ApplicationResponse<serde_json::Value>,+ },+}++impl WebhookOutcome {+ pub fn event_type(&self) -> IncomingWebhookEvent {+ match self {+ Self::Skipped { event_type, .. } | Self::Processed { event_type, .. } => *event_type,+ }+ }++ pub fn reference(&self) -> Option<&ObjectReferenceId> {+ match self {+ Self::Skipped { reference, .. } => reference.as_ref(),+ Self::Processed { reference, .. } => Some(reference),+ }+ }+}++#[derive(Clone)]+pub struct WebhookGatewayContext {+ pub state: SessionState,+ pub platform: domain::Platform,+ pub connector: ConnectorEnum,+ pub connector_name: String,+ /// `None` when the webhook URL identifies the connector by name only;+ /// resolved post-decode from the parsed object reference in that case.+ pub merchant_connector_account: Option<domain::MerchantConnectorAccount>,+ pub execution_path: ExecutionPath,+ pub execution_mode: ExecutionMode,+}++#[async_trait]+pub trait IncomingWebhookGateway: Send + Sync {+ async fn execute(+ &self,+ request: &IncomingWebhookRequestDetails<'_>,+ ctx: &WebhookGatewayContext,+ ) -> RouterResult<WebhookOutcome>;+}++pub enum FilterDecision {+ Skip,+ Proceed,+}++impl FilterDecision {+ pub async fn evaluate(event_type: IncomingWebhookEvent, ctx: &WebhookGatewayContext) -> Self {+ let supported = !matches!(event_type, IncomingWebhookEvent::EventNotSupported);+ let enabled = !webhook_utils::is_webhook_event_disabled(+ &*ctx.state.store,+ &ctx.connector_name,+ ctx.platform.get_processor().get_account().get_id(),+ &event_type,+ )+ .await;+ let flow: api_models::webhooks::WebhookFlow = event_type.into();+ let return_response = matches!(flow, api_models::webhooks::WebhookFlow::ReturnResponse);++ if supported && enabled && !return_response {+ Self::Proceed+ } else {+ Self::Skip+ }+ }+}++pub struct DirectIncomingWebhookGateway;++#[async_trait]+impl IncomingWebhookGateway for DirectIncomingWebhookGateway {+ async fn execute(+ &self,+ request: &IncomingWebhookRequestDetails<'_>,+ ctx: &WebhookGatewayContext,+ ) -> RouterResult<WebhookOutcome> {+ let decoded_body = ctx+ .connector+ .decode_webhook_body(+ request,+ ctx.platform.get_processor().get_account().get_id(),+ ctx.merchant_connector_account+ .as_ref()+ .and_then(|mca| mca.connector_webhook_details.clone()),+ &ctx.connector_name,+ )+ .await+ .switch()+ .attach_printable("Failed to decode incoming webhook body")?;++ let decoded_request = IncomingWebhookRequestDetails {+ method: request.method.clone(),+ uri: request.uri.clone(),+ headers: request.headers,+ query_params: request.query_params.clone(),+ body: &decoded_body,+ };++ let reference = ctx+ .connector+ .get_webhook_object_reference_id(&decoded_request)+ .ok();++ // Pre-fetch resource data (payment attempt for PaymentId references) so+ // event-type classification has context and downstream flows can reuse it+ // without an extra DB round-trip.+ let webhook_resource_data =+ build_webhook_resource_data(&ctx.state, &ctx.platform, reference.as_ref()).await?;+ let webhook_context = webhook_resource_data.as_ref().map(WebhookContext::from);++ // Error on failed event-type identification (parity with main branch).+ let event_type = match ctx+ .connector+ .get_webhook_event_type(&decoded_request, webhook_context.as_ref())+ .allow_webhook_event_type_not_found(+ ctx.state+ .conf+ .webhooks+ .ignore_error+ .event_type+ .unwrap_or(true),+ )+ .switch()+ .attach_printable("Could not find event type in incoming webhook body")?+ {+ Some(et) => et,+ None => {+ metrics::WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT.add(+ 1,+ router_env::metric_attributes!(+ (+ MERCHANT_ID,+ ctx.platform.get_processor().get_account().get_id().clone()+ ),+ ("connector", ctx.connector_name.to_string())+ ),+ );+ return Err(error_stack::report!(+ errors::ApiErrorResponse::WebhookProcessingFailure+ )+ .attach_printable("Failed to identify event type in incoming webhook body"));+ }+ };++ let ack_creds = ctx+ .merchant_connector_account+ .as_ref()+ .map(|m| m.connector_account_details.clone());+ let ack_response = ctx+ .connector+ .get_webhook_api_response(&decoded_request, None, ack_creds)+ .switch()+ .attach_printable("Failed to build webhook ack via connector")?;++ let outcome = match FilterDecision::evaluate(event_type, ctx).await {+ FilterDecision::Skip => WebhookOutcome::Skipped {+ reference,+ event_type,+ ack_response,+ },+ FilterDecision::Proceed => {+ let reference = reference.ok_or_else(|| {+ error_stack::report!(errors::ApiErrorResponse::WebhookResourceNotFound)+ .attach_printable(+ "Could not find object reference id in incoming webhook body",+ )+ })?;+ let mca = resolve_mca(ctx, &reference).await?;+ let source_verified =+ verify_webhook_source_via_connector(ctx, &decoded_request, &mca).await?;+ let resource_object = ctx+ .connector+ .get_webhook_resource_object(&decoded_request)+ .switch()+ .attach_printable("Failed to extract webhook resource object")?;+ let bytes = serde_json::to_vec(&resource_object)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to encode webhook resource object")?;+ let masked_log_payload =+ Secret::new(resource_object.masked_serialize().unwrap_or_else(|error| {+ logger::warn!(+ ?error,+ "Failed to mask-serialize webhook resource object for logging"+ );+ serde_json::Value::Null+ }));++ WebhookOutcome::Processed {+ reference,+ event_type,+ source_verified,+ content: WebhookContent::Direct(bytes),+ decoded_body: Some(decoded_body.to_vec()),+ webhook_resource_data: Box::new(webhook_resource_data),+ masked_log_payload,+ merchant_connector_account: Box::new(mca),+ ack_response,+ }+ }+ };++ Ok(outcome)+ }+}++/// Two-phase UCS flow: `ParseEvent` (pre-credential) then `HandleEvent`.+pub struct UcsIncomingWebhookGateway;++#[async_trait]+impl IncomingWebhookGateway for UcsIncomingWebhookGateway {+ async fn execute(+ &self,+ request: &IncomingWebhookRequestDetails<'_>,+ ctx: &WebhookGatewayContext,+ ) -> RouterResult<WebhookOutcome> {+ let client = ctx+ .state+ .grpc_client+ .unified_connector_service_client+ .as_ref()+ .ok_or_else(|| {+ error_stack::report!(errors::ApiErrorResponse::WebhookProcessingFailure)+ .attach_printable("UCS client is not configured")+ })?+ .clone();++ let connector_name = ctx.connector_name.clone();+ let merchant_event_id = build_merchant_event_id(ctx);++ let parse_request = payments_grpc::EventServiceParseRequest::foreign_try_from(request)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to build UCS EventServiceParseRequest")?;+ let parse_auth = build_ucs_auth_metadata(ctx, None)?;+ let parse_headers = build_ucs_headers_builder(ctx, None, ctx.execution_mode);+ let parse_client = client.clone();+ let parse_response = unified_connector_service::ucs_webhook_logging_wrapper(+ &ctx.state,+ connector_name.clone(),+ "EventServiceParseEvent",+ parse_request,+ parse_headers,+ |request, headers| async move {+ parse_client+ .incoming_webhook_parse_event(request, parse_auth, headers)+ .await+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)+ .attach_printable("UCS ParseEvent call failed")+ .map(|response| response.into_inner())+ },+ )+ .await?;++ let reference = match parse_response.reference.as_ref() {+ Some(r) => event_reference_to_object_ref(r)?,+ None => None,+ };+ let event_type = parse_response+ .event_type+ .map(IncomingWebhookEvent::from_ucs_event_type)+ .unwrap_or(IncomingWebhookEvent::EventNotSupported);++ let outcome = match FilterDecision::evaluate(event_type, ctx).await {+ FilterDecision::Skip => WebhookOutcome::Skipped {+ reference,+ event_type,+ ack_response: services::ApplicationResponse::StatusOk,+ },+ FilterDecision::Proceed => {+ let reference = reference.ok_or_else(|| {+ error_stack::report!(errors::ApiErrorResponse::WebhookResourceNotFound)+ .attach_printable(+ "UCS ParseEvent produced no object reference for a non-filtered event",+ )+ })?;+ let mca = resolve_mca(ctx, &reference).await?;+ #[cfg(feature = "v1")]+ let webhook_secrets = build_webhook_secrets_from_merchant_connector_account(+ &MerchantConnectorAccountType::DbVal(Box::new(mca.clone())),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to resolve webhook secrets from merchant connector account",+ )?;+ #[cfg(feature = "v2")]+ let webhook_secrets = build_webhook_secrets_from_merchant_connector_account(+ &domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(+ Box::new(mca.clone()),+ ),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to resolve webhook secrets from merchant connector account",+ )?;++ let event_context = build_event_context(ctx, &reference).await;++ let handle_request = build_handle_event_request(+ request,+ webhook_secrets,+ event_context,+ merchant_event_id.clone(),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to build UCS EventServiceHandleRequest")?;+ let handle_auth = build_ucs_auth_metadata(ctx, Some(&mca))?;+ let handle_headers = build_ucs_headers_builder(ctx, Some(&mca), ctx.execution_mode);+ let handle_client = client.clone();+ let handle_response = unified_connector_service::ucs_webhook_logging_wrapper(+ &ctx.state,+ connector_name.clone(),+ "EventServiceHandleEvent",+ handle_request,+ handle_headers,+ |request, headers| async move {+ handle_client+ .incoming_webhook_handle_event(request, handle_auth, headers)+ .await+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)+ .attach_printable("UCS HandleEvent call failed")+ .map(|response| response.into_inner())+ },+ )+ .await?;++ let event_content = handle_response.event_content.ok_or_else(|| {+ error_stack::report!(errors::ApiErrorResponse::WebhookProcessingFailure)+ .attach_printable(+ "UCS HandleEvent returned no event_content for a non-filtered event",+ )+ })?;+ let bytes = event_content+ .encode_to_vec()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to encode unified event content")?;+ let masked_log_payload =+ Secret::new(event_content.masked_serialize().unwrap_or_else(|error| {+ logger::warn!(+ ?error,+ "Failed to mask-serialize unified event content for logging"+ );+ serde_json::Value::Null+ }));++ let ack_response = handle_response+ .event_ack_response+ .map(ucs_ack_to_application_response)+ .unwrap_or(services::ApplicationResponse::StatusOk);++ WebhookOutcome::Processed {+ reference,+ event_type,+ source_verified: handle_response.source_verified,+ content: WebhookContent::UnifiedConnectorService(bytes),+ // UCS uses the raw request body — no decoded_body needed.+ decoded_body: None,+ // UCS path does not pre-fetch resource data; the downstream+ // flow will fetch it on demand.+ webhook_resource_data: Box::new(None),+ masked_log_payload,+ merchant_connector_account: Box::new(mca),+ ack_response,+ }+ }+ };++ Ok(outcome)+ }+}++pub async fn execute_incoming_webhook_gateway(+ ctx: &WebhookGatewayContext,+ request: &IncomingWebhookRequestDetails<'_>,+) -> RouterResult<WebhookOutcome> {+ match ctx.execution_path {+ ExecutionPath::Direct => DirectIncomingWebhookGateway.execute(request, ctx).await,+ ExecutionPath::UnifiedConnectorService => {+ UcsIncomingWebhookGateway.execute(request, ctx).await+ }+ ExecutionPath::ShadowUnifiedConnectorService => {+ let direct_result = DirectIncomingWebhookGateway.execute(request, ctx).await;+ let primary_snapshot = WebhookShadowSnapshot::from_result(&direct_result);+ spawn_shadow_ucs_run(ctx, request, primary_snapshot);+ direct_result+ }+ }+}++fn spawn_shadow_ucs_run(+ ctx: &WebhookGatewayContext,+ request: &IncomingWebhookRequestDetails<'_>,+ primary_snapshot: WebhookShadowSnapshot,+) {+ let mut inner_ctx = ctx.clone();+ inner_ctx.execution_path = ExecutionPath::UnifiedConnectorService;+ inner_ctx.execution_mode = ExecutionMode::Shadow;++ let request_owned = OwnedRequestDetails::from(request);++ tokio::spawn(+ async move {+ let request_ref = request_owned.borrow();+ let shadow_result = UcsIncomingWebhookGateway+ .execute(&request_ref, &inner_ctx)+ .await;+ if let Err(error) = shadow_result.as_ref() {+ logger::warn!(?error, "UCS shadow webhook run failed");+ }+ let shadow_snapshot = WebhookShadowSnapshot::from_result(&shadow_result);+ report_shadow_diff(+ &inner_ctx.state,+ &inner_ctx.connector_name,+ &primary_snapshot,+ &shadow_snapshot,+ )+ .await;+ }+ .in_current_span(),+ );+}++struct OwnedRequestDetails {+ method: http::Method,+ uri: http::Uri,+ headers: actix_web::http::header::HeaderMap,+ body: Vec<u8>,+ query_params: String,+}++impl From<&IncomingWebhookRequestDetails<'_>> for OwnedRequestDetails {+ fn from(req: &IncomingWebhookRequestDetails<'_>) -> Self {+ Self {+ method: req.method.clone(),+ uri: req.uri.clone(),+ headers: req.headers.clone(),+ body: req.body.to_vec(),+ query_params: req.query_params.clone(),+ }+ }+}++impl OwnedRequestDetails {+ fn borrow(&self) -> IncomingWebhookRequestDetails<'_> {+ IncomingWebhookRequestDetails {+ method: self.method.clone(),+ uri: self.uri.clone(),+ headers: &self.headers,+ body: self.body.as_slice(),+ query_params: self.query_params.clone(),+ }+ }+}++#[derive(Debug, serde::Serialize)]+struct WebhookShadowSnapshot {+ variant: &'static str,+ event_type: Option<IncomingWebhookEvent>,+ source_verified: Option<bool>,+ content_kind: Option<&'static str>,+ reference: Option<ObjectReferenceId>,+ error: Option<String>,+}++impl WebhookShadowSnapshot {+ fn from_result(result: &RouterResult<WebhookOutcome>) -> Self {+ match result {+ Ok(outcome) => Self::from(outcome),+ Err(error) => Self {+ variant: "error",+ event_type: None,+ source_verified: None,+ content_kind: None,+ reference: None,+ error: Some(format!("{error:?}")),+ },+ }+ }+}++impl From<&WebhookOutcome> for WebhookShadowSnapshot {+ fn from(outcome: &WebhookOutcome) -> Self {+ match outcome {+ WebhookOutcome::Skipped {+ event_type,+ reference,+ ..+ } => Self {+ variant: "skipped",+ event_type: Some(*event_type),+ source_verified: None,+ content_kind: None,+ reference: reference.clone(),+ error: None,+ },+ WebhookOutcome::Processed {+ event_type,+ source_verified,+ content,+ reference,+ ..+ } => Self {+ variant: "processed",+ event_type: Some(*event_type),+ source_verified: Some(*source_verified),+ content_kind: Some(match content {+ WebhookContent::Direct(_) => "direct",+ WebhookContent::UnifiedConnectorService(_) => "unified_connector_service",+ }),+ reference: Some(reference.clone()),+ error: None,+ },+ }+ }+}++async fn report_shadow_diff(+ state: &SessionState,+ connector_name: &str,+ primary: &WebhookShadowSnapshot,+ shadow: &WebhookShadowSnapshot,+) {+ logger::info!(+ primary_event_type = ?primary.event_type,+ shadow_event_type = ?shadow.event_type,+ event_type_match = primary.event_type == shadow.event_type,+ primary_source_verified = ?primary.source_verified,+ shadow_source_verified = ?shadow.source_verified,+ "Webhook shadow diff",+ );++ use hyperswitch_interfaces::{+ api_client::ApiClientWrapper, helpers::GetComparisonServiceConfig,+ };+ if let Some(config) = state.get_comparison_service_config() {+ hyperswitch_interfaces::helpers::serialize_webhook_outcome_and_send_to_comparison_service(+ state,+ primary,+ shadow,+ config,+ connector_name.to_string(),+ state.get_request_id_str(),+ )+ .await;+ }+}++async fn resolve_mca(+ ctx: &WebhookGatewayContext,+ reference: &ObjectReferenceId,+) -> RouterResult<domain::MerchantConnectorAccount> {+ match ctx.merchant_connector_account.as_ref() {+ Some(mca) => Ok(mca.clone()),+ None => {+ Box::pin(helper_utils::get_mca_from_object_reference_id(+ &ctx.state,+ reference.clone(),+ &ctx.platform,+ &ctx.connector_name,+ ))+ .await+ }+ }+}++async fn build_webhook_resource_data(+ state: &SessionState,+ platform: &domain::Platform,+ reference: Option<&ObjectReferenceId>,+) -> RouterResult<Option<WebhookResourceData>> {+ match reference {+ Some(reference @ ObjectReferenceId::PaymentId(_)) => {+ let payment_attempt = get_payment_attempt_from_object_reference_id(+ state,+ reference.clone(),+ platform.get_processor(),+ )+ .await?;+ Ok(Some(WebhookResourceData::Payment { payment_attempt }))+ }+ _ => Ok(None),+ }+}++/// Source verification for the Direct and UAS paths. UCS returns its own+/// `source_verified` flag from `HandleEvent`.+pub(super) async fn verify_webhook_source_via_connector(+ ctx: &WebhookGatewayContext,+ request: &IncomingWebhookRequestDetails<'_>,+ mca: &domain::MerchantConnectorAccount,+) -> RouterResult<bool> {+ use std::str::FromStr;++ let connector_enum = api_models::enums::Connector::from_str(&ctx.connector_name)+ .change_context(errors::ApiErrorResponse::InvalidDataValue {+ field_name: "connector",+ })+ .attach_printable_lazy(|| {+ format!("unable to parse connector name {:?}", ctx.connector_name)+ })?;++ let requires_external_source_verification = ctx+ .state+ .conf+ .webhook_source_verification_call+ .connectors_with_webhook_source_verification_call+ .contains(&connector_enum);++ if requires_external_source_verification {+ webhook_utils::verify_webhook_source_verification_call(+ ctx.connector.clone(),+ &ctx.state,+ &ctx.platform,+ mca.clone(),+ &ctx.connector_name,+ request,+ )+ .await+ .or_else(|error| match error.current_context() {+ errors::ConnectorError::WebhookSourceVerificationFailed => {+ logger::error!(?error, "Source Verification Failed");+ Ok(false)+ }+ _ => Err(error),+ })+ .switch()+ .attach_printable("There was an issue in incoming webhook source verification")+ } else {+ ctx.connector+ .clone()+ .verify_webhook_source(+ request,+ ctx.platform.get_processor().get_account().get_id(),+ mca.connector_webhook_details.clone(),+ mca.connector_account_details.clone(),+ &ctx.connector_name,+ )+ .await+ .or_else(|error| match error.current_context() {+ hyperswitch_interfaces::errors::ConnectorError::WebhookSourceVerificationFailed => {+ logger::error!(?error, "Source Verification Failed");+ Ok(false)+ }+ _ => Err(error),+ })+ .switch()+ .attach_printable("There was an issue in incoming webhook source verification")+ }+}++/// `mca = None` → routing-only metadata for `ParseEvent` (pre-credential).+fn build_ucs_auth_metadata(+ ctx: &WebhookGatewayContext,+ mca: Option<&domain::MerchantConnectorAccount>,+) -> RouterResult<external_services::grpc_client::unified_connector_service::ConnectorAuthMetadata>+{+ match mca {+ Some(mca) => {+ #[cfg(feature = "v1")]+ let auth_metadata = build_unified_connector_service_auth_metadata(+ MerchantConnectorAccountType::DbVal(Box::new(mca.clone())),+ ctx.platform.get_processor(),+ ctx.connector_name.to_string(),+ );+ #[cfg(feature = "v2")]+ let auth_metadata = build_unified_connector_service_auth_metadata(+ domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(+ mca.clone(),+ )),+ ctx.platform.get_processor(),+ ctx.connector_name.to_string(),+ );+ auth_metadata+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to build UCS auth metadata")+ }+ None => {+ let merchant_id = ctx+ .platform+ .get_processor()+ .get_account()+ .get_id()+ .get_string_repr()+ .to_string();+ Ok(+ external_services::grpc_client::unified_connector_service::ConnectorAuthMetadata {+ connector_name: ctx.connector_name.to_string(),+ auth_type: "NoKey".to_string(),+ api_key: None,+ key1: None,+ key2: None,+ api_secret: None,+ auth_key_map: None,+ merchant_id: Secret::new(merchant_id),+ connector_config: None,+ },+ )+ }+ }+}++fn build_ucs_headers_builder(+ ctx: &WebhookGatewayContext,+ mca: Option<&domain::MerchantConnectorAccount>,+ mode: ExecutionMode,+) -> external_services::grpc_client::GrpcHeadersUcsBuilderFinal {+ let merchant_id = ctx.platform.get_processor().get_account().get_id().clone();+ let profile_id = mca+ .map(|m| m.profile_id.clone())+ .unwrap_or_else(|| consts::PROFILE_ID_UNAVAILABLE.clone());+ ctx.state+ .get_grpc_headers_ucs(mode)+ .lineage_ids(LineageIds::new(merchant_id, profile_id))+ .external_vault_proxy_metadata(None)+ .merchant_reference_id(None)+ .resource_id(None)+}++fn build_merchant_event_id(ctx: &WebhookGatewayContext) -> String {+ format!(+ "{}_{}_{}",+ ctx.platform+ .get_processor()+ .get_account()+ .get_id()+ .get_string_repr(),+ ctx.connector_name,+ OffsetDateTime::now_utc().unix_timestamp()+ )+}++fn event_reference_to_object_ref(+ reference: &payments_grpc::EventReference,+) -> RouterResult<Option<ObjectReferenceId>> {+ use api_models::{payments as api_payments, webhooks as api_webhooks};+ use payments_grpc::event_reference::Resource;++ let Some(resource) = reference.resource.as_ref() else {+ return Ok(None);+ };++ let out = match resource {+ Resource::Payment(payment) => {+ if let Some(ctx_id) = payment.connector_transaction_id.as_ref() {+ Some(ObjectReferenceId::PaymentId(+ api_payments::PaymentIdType::ConnectorTransactionId(ctx_id.clone()),+ ))+ } else {+ payment.merchant_transaction_id.as_ref().map(|mref| {+ ObjectReferenceId::PaymentId(api_payments::PaymentIdType::PaymentAttemptId(+ mref.clone(),+ ))+ })+ }+ }+ Resource::Refund(refund) => {+ if let Some(cr_id) = refund.connector_refund_id.as_ref() {+ Some(ObjectReferenceId::RefundId(+ api_webhooks::RefundIdType::ConnectorRefundId(cr_id.clone()),+ ))+ } else {+ refund.merchant_refund_id.as_ref().map(|mid| {+ ObjectReferenceId::RefundId(api_webhooks::RefundIdType::RefundId(mid.clone()))+ })+ }+ }+ Resource::Dispute(dispute) => dispute+ .connector_dispute_id+ .as_ref()+ .or(dispute.connector_transaction_id.as_ref())+ .map(|id| {+ ObjectReferenceId::PaymentId(api_payments::PaymentIdType::ConnectorTransactionId(+ id.clone(),+ ))+ }),+ Resource::Mandate(mandate) => mandate.connector_mandate_id.as_ref().map(|id| {+ ObjectReferenceId::MandateId(api_webhooks::MandateIdType::ConnectorMandateId(+ id.clone(),+ ))+ }),+ #[cfg(feature = "payouts")]+ Resource::Payout(payout) => {+ if let Some(cid) = payout.connector_payout_id.as_ref() {+ Some(ObjectReferenceId::PayoutId(+ api_webhooks::PayoutIdType::ConnectorPayoutId(cid.clone()),+ ))+ } else {+ payout.merchant_payout_id.as_ref().map(|mid| {+ ObjectReferenceId::PayoutId(api_webhooks::PayoutIdType::PayoutAttemptId(+ mid.clone(),+ ))+ })+ }+ }+ #[cfg(not(feature = "payouts"))]+ Resource::Payout(_) => None,+ };++ Ok(out)+}++async fn build_event_context(+ ctx: &WebhookGatewayContext,+ reference: &ObjectReferenceId,+) -> Option<payments_grpc::EventContext> {+ let payment_attempt = match reference {+ reference @ ObjectReferenceId::PaymentId(_) => {+ get_payment_attempt_from_object_reference_id(+ &ctx.state,+ reference.clone(),+ ctx.platform.get_processor(),+ )+ .await+ .ok()?+ }+ _ => return None,+ };++ let capture_method = payment_attempt+ .capture_method+ .and_then(|cm| payments_grpc::CaptureMethod::foreign_try_from(cm).ok())+ .map(i32::from);++ Some(payments_grpc::EventContext {+ event_context: Some(payments_grpc::event_context::EventContext::Payment(+ payments_grpc::PaymentEventContext { capture_method },+ )),+ })+}++fn ucs_ack_to_application_response(+ ack: payments_grpc::EventAckResponse,+) -> services::ApplicationResponse<serde_json::Value> {+ let payments_grpc::EventAckResponse {+ status_code: _,+ headers,+ body,+ } = ack;++ if body.is_empty() {+ return services::ApplicationResponse::StatusOk;+ }++ let masked_headers: Vec<(String, hyperswitch_masking::Maskable<String>)> = headers+ .into_iter()+ .map(|(k, v)| (k, hyperswitch_masking::Maskable::new_normal(v)))+ .collect();++ if let Ok(value) = serde_json::from_slice::<serde_json::Value>(&body) {+ return if masked_headers.is_empty() {+ services::ApplicationResponse::Json(value)+ } else {+ services::ApplicationResponse::JsonWithHeaders((value, masked_headers))+ };+ }++ match String::from_utf8(body.clone()) {+ Ok(text) => services::ApplicationResponse::TextPlain(text),+ Err(_) => services::ApplicationResponse::FileData((body, mime::APPLICATION_OCTET_STREAM)),+ }+}diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rsindex b2acf52109..6800924d77 100644--- a/crates/router/src/core/webhooks/incoming.rs+++ b/crates/router/src/core/webhooks/incoming.rs@@ -22,26 +22,21 @@ use hyperswitch_domain_models::payouts::payouts::PayoutsUpdate;use hyperswitch_domain_models::{mandates::CommonMandateReference,payments::{payment_attempt::PaymentAttempt, HeaderPayload},- router_request_types::{- unified_authentication_service::UasAuthenticationResponseData,- VerifyWebhookSourceRequestData,- },- router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus},+ router_request_types::unified_authentication_service::UasAuthenticationResponseData,};use hyperswitch_interfaces::webhooks::{IncomingWebhookFlowError, IncomingWebhookRequestDetails, WebhookContext, WebhookResourceData,};use hyperswitch_masking::{ExposeInterface, PeekInterface};use router_env::{instrument, tracing, RequestId};-use unified_connector_service_client::payments as payments_grpc;-use super::{types, utils, MERCHANT_ID};+use super::{types, MERCHANT_ID};use crate::{consts,core::{api_locking,configs::dimension_state,- errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt},+ errors::{self, CustomResult, RouterResponse, StorageErrorExt},metrics, payment_methods,payment_methods::cards,payments::{self, tokenization, PaymentIntentStateMetadataExt},@@ -50,7 +45,7 @@ use crate::{types::UNIFIED_AUTHENTICATION_SERVICE, utils as uas_utils,},unified_connector_service, utils as core_utils,- webhooks::{network_tokenization_incoming, utils::construct_webhook_router_data},+ webhooks::network_tokenization_incoming,},events::api_logs::ApiEvent,logger,@@ -100,7 +95,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>()).await?;- logger::info!(incoming_webhook_payload = ?serialized_req);+ logger::info!(incoming_webhook_payload = ?serialized_req.peek());let request_duration = Instant::now().saturating_duration_since(start_instant)@@ -130,7 +125,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>(&request_id,request_duration,status_code,- serialized_req,+ serialized_req.peek().clone(),Some(response_value),None,auth_type,@@ -219,7 +214,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>() -> errors::RouterResult<(services::ApplicationResponse<serde_json::Value>,WebhookResponseTracker,- serde_json::Value,+ common_utils::pii::SecretSerdeValue,)> {// Initial setup and metricsmetrics::WEBHOOK_INCOMING_COUNT.add(@@ -250,260 +245,179 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(fetch_three_ds_execution_path(&platform, connector_name_or_mca_id, &state, &dimensions).await?;- // Decodes webhook body based on execution path, and returns connector Integration, connector_name, webhook_processing_result and merchant_connector_account back to the flow without disturbing the current flow- let (connector, connector_name, webhook_processing_result, merchant_connector_account) =- 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 (uas_connector, _) =- get_connector_by_connector_name(&state, UNIFIED_AUTHENTICATION_SERVICE, None)?;-- let webhook_processing_result = Box::pin(process_uas_incoming_webhook(+ // Each arm resolves its path (UAS vs Direct/UCS) and returns a+ // `WebhookOutcome` plus the connector/name used for acks, errors, and+ // logging. Downstream filter interception and business-logic dispatch are+ // identical for both and run once after the match.+ let (connector, connector_name, outcome) = match three_ds_execution_path {+ ThreeDsProcessingMode::UnifiedAuthenticationService(ref mca_data) => {+ let connector_name = mca_data.connector_name.clone();+ let (uas_connector, _) =+ get_connector_by_connector_name(&state, UNIFIED_AUTHENTICATION_SERVICE, None)?;++ let outcome: errors::RouterResult<super::gateway::WebhookOutcome> =+ Box::pin(process_uas_incoming_webhook(&state,+ &platform,&request_details,connector_name.clone(),uas_connector.clone(),- platform.clone(),)).await;- (- uas_connector,- connector_name,- webhook_processing_result,- mca_data.merchant_connector_account.clone(),- )- }- 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.get_processor(),- &mca_data.connector_name,- mca_data- .merchant_connector_account- .as_ref()- .map(|mca| &mca.merchant_connector_id),- )- .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- }- };+ (uas_connector, connector_name, outcome)+ }+ ThreeDsProcessingMode::Direct(ref mca_data) => {+ let connector = mca_data.connector.clone();+ let connector_name = mca_data.connector_name.clone();+ let mca_ref = mca_data.merchant_connector_account.as_ref();- (- connector,- connector_name,- webhook_processing_result,- mca_data.merchant_connector_account.clone(),+ let execution_path =+ unified_connector_service::should_call_unified_connector_service_for_webhooks(+ &state,+ platform.get_processor(),+ &connector_name,+ mca_ref.map(|mca| &mca.merchant_connector_id),)- }- };- 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,- &request_details,- platform.get_processor().get_account().get_id(),+ .await?;+ logger::info!(+ connector = %connector_name,+ ?execution_path,+ "Selected webhook execution path");- match error_result {- Ok((response, webhook_tracker, serialized_request)) => {- return Ok((response, webhook_tracker, serialized_request));++ let execution_mode = match execution_path {+ common_enums::ExecutionPath::UnifiedConnectorService => {+ common_enums::ExecutionMode::Primary}- Err(e) => return Err(e),- }+ common_enums::ExecutionPath::ShadowUnifiedConnectorService => {+ common_enums::ExecutionMode::Shadow+ }+ common_enums::ExecutionPath::Direct => common_enums::ExecutionMode::NotApplicable,+ };++ let ctx = super::gateway::WebhookGatewayContext {+ state: state.clone(),+ platform: platform.clone(),+ connector: connector.clone(),+ connector_name: connector_name.clone(),+ merchant_connector_account: mca_ref.cloned(),+ execution_path,+ execution_mode,+ };+ let outcome =+ super::gateway::execute_incoming_webhook_gateway(&ctx, &request_details).await;++ (connector, connector_name, outcome)}};- // if it is a setup webhook event, return ok status- if webhook_processing_result.event_type == webhooks::IncomingWebhookEvent::SetupWebhook {+ if matches!(+ &outcome,+ Ok(outcome) if outcome.event_type() == webhooks::IncomingWebhookEvent::SetupWebhook+ ) {return Ok((services::ApplicationResponse::StatusOk,WebhookResponseTracker::NoEffect,- serde_json::Value::default(),+ hyperswitch_masking::Secret::new(serde_json::Value::default()),));}- // 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);+ let (ack_response, webhook_effect, serialized_body) = match outcome {+ Ok(super::gateway::WebhookOutcome::Skipped {+ event_type,+ ack_response,+ ..+ }) => {+ logger::info!(?event_type, "Webhook filtered before business logic");+ metrics::WEBHOOK_INCOMING_FILTERED_COUNT.add(+ 1,+ router_env::metric_attributes!((+ MERCHANT_ID,+ platform.get_processor().get_account().get_id().clone()+ )),+ );+ (+ ack_response,+ WebhookResponseTracker::NoEffect,+ hyperswitch_masking::Secret::new(serde_json::Value::Null),+ )+ }+ Ok(super::gateway::WebhookOutcome::Processed {+ reference,+ event_type,+ source_verified,+ content,+ decoded_body,+ webhook_resource_data,+ masked_log_payload,+ merchant_connector_account: processed_mca,+ ack_response,+ }) => {+ // Reconstruct request_details with the decoded body when available+ // (Direct and UAS paths), so downstream connector methods that parse+ // request_details.body (get_dispute_details, get_webhook_mandate_details,+ // etc.) receive the structured payload they expect.+ // UCS path leaves decoded_body as None and uses the raw request body.+ let decoded_request_details;+ let request_for_biz: &IncomingWebhookRequestDetails<'_> = match decoded_body.as_deref()+ {+ Some(body) => {+ decoded_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_request_details+ }+ None => &request_details,+ };- // 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(),- platform.get_processor().get_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 hyperswitch_masking::ErasedMaskSerialize> =- Box::new(serde_json::Value::Null);-- let webhook_effect = match process_webhook_further {- true => {- let business_logic_result = Box::pin(process_webhook_business_logic(+ let effect = match Box::pin(process_webhook_business_logic(&state,req_state,&platform,&connector,&connector_name,- webhook_processing_result.event_type,- webhook_processing_result.source_verified,- &webhook_processing_result.transform_data,- &mut webhook_processing_result.shadow_ucs_data,- final_request_details,+ event_type,+ source_verified,+ content,+ request_for_biz,is_relay_webhook,- webhook_processing_result.webhook_resource_data,- webhook_processing_result.object_reference_id,+ reference,+ *processed_mca,+ *webhook_resource_data,))- .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,- platform.get_processor().get_account().get_id(),- );- match error_result {- Ok((_, webhook_tracker, _)) => webhook_tracker,- Err(e) => return Err(e),- }- }- }+ .await+ {+ Ok(effect) => effect,+ Err(error) => match handle_incoming_webhook_error(+ error,+ &connector,+ connector_name.as_str(),+ &request_details,+ platform.get_processor().get_account().get_id(),+ ) {+ Ok((_, tracker, _)) => tracker,+ Err(e) => return Err(e),+ },+ };+ (ack_response, effect, masked_log_payload)}- false => {- metrics::WEBHOOK_INCOMING_FILTERED_COUNT.add(- 1,- router_env::metric_attributes!((- MERCHANT_ID,- platform.get_processor().get_account().get_id().clone()- )),+ Err(error) => {+ return handle_incoming_webhook_error(+ error,+ &connector,+ connector_name.as_str(),+ &request_details,+ platform.get_processor().get_account().get_id(),);- WebhookResponseTracker::NoEffect}};- // Generate response- let response = connector- .get_webhook_api_response(- final_request_details,- None,- merchant_connector_account.map(|mca| mca.connector_account_details),- )- .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))+ Ok((ack_response, webhook_effect, serialized_body))}async fn fetch_three_ds_execution_path(@@ -547,58 +461,6 @@ async fn fetch_three_ds_execution_path(}}-/// Process UCS webhook transformation using the high-level UCS abstraction-async fn process_ucs_webhook_transform<'a>(- state: &'a SessionState,- platform: &'a domain::Platform,- connector_name: &'a str,- body: &'a actix_web::web::Bytes,- request_details: &'a IncomingWebhookRequestDetails<'a>,- merchant_connector_account: Option<&'a domain::MerchantConnectorAccount>,-) -> errors::RouterResult<WebhookProcessingResult<'a>> {- // 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,- platform.get_processor(),- 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- shadow_ucs_data: None,- webhook_resource_data: None,- object_reference_id: None,- })-}--/// Shadow UCS data container-#[allow(dead_code)]-pub struct ShadowUcsData<'a> {- ucs_source_verified: bool,- ucs_event_type: webhooks::IncomingWebhookEvent,- ucs_transform_data: Box<unified_connector_service::WebhookTransformData>,- request_details: &'a IncomingWebhookRequestDetails<'a>,- webhook_details: Option<api::IncomingWebhookDetails>,-}--/// Result type for webhook processing path determination-pub struct WebhookProcessingResult<'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>>,- pub webhook_resource_data: Option<WebhookResourceData>,- pub object_reference_id: Option<api::ObjectReferenceId>,-}-#[derive(Clone, Debug)]pub struct MerchantConnectorDetails {/// Merchant Connector Account@@ -616,255 +478,10 @@ pub enum ThreeDsProcessingMode {UnifiedAuthenticationService(MerchantConnectorDetails),}-/// Process shadow UCS webhook transformation with dual execution (UCS + Direct)-async fn process_shadow_ucs_webhook_transform<'a>(- state: &'a SessionState,- platform: &'a domain::Platform,- connector: &'a ConnectorEnum,- connector_name: &'a str,- body: &'a actix_web::web::Bytes,- request_details: &'a IncomingWebhookRequestDetails<'a>,- merchant_connector_account: Option<&'a domain::MerchantConnectorAccount>,-) -> errors::RouterResult<WebhookProcessingResult<'a>> {- // Execute UCS path- let ucs_result = unified_connector_service::call_unified_connector_service_for_webhook(- state,- platform.get_processor(),- connector_name,- body,- request_details,- merchant_connector_account,- )- .await;-- // Execute Direct path for comparison- let direct_result = async {- // Decode body for direct processing- let decoded_body = connector- .decode_webhook_body(- request_details,- platform.get_processor().get_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 for shadow processing",- )?;-- // Reuse existing process_non_ucs_webhook function- process_non_ucs_webhook(- state,- platform,- connector,- connector_name,- decoded_body.into(),- request_details,- )- .await- }- .await;-- // Handle results and comparison- match (ucs_result, direct_result) {- (- Ok((ucs_event_type, ucs_source_verified, ucs_transform_data)),- Ok(mut direct_processing_result),- ) => {- // Log both calls succeeded- logger::info!(- connector = connector_name,- merchant_id = ?platform.get_processor().get_account().get_id(),- "Shadow UCS: Both UCS and Direct calls succeeded"- );-- // Create ShadowUcsData with UCS results- let shadow_ucs_data = ShadowUcsData {- ucs_source_verified,- ucs_event_type,- ucs_transform_data: Box::new(ucs_transform_data),- request_details,- webhook_details: None,- };-- // Return Direct result as primary with UCS data in shadow_ucs_data- direct_processing_result.shadow_ucs_data = Some(shadow_ucs_data);- Ok(direct_processing_result)- }- (Ok((_, _, _)), Err(direct_error)) => {- // Log UCS call succeeded, direct call failed- logger::info!(- connector = connector_name,- merchant_id = ?platform.get_processor().get_account().get_id(),- direct_error = ?direct_error,- "Shadow UCS: UCS call succeeded, Direct call failed"- );-- // Return direct_result error as required- Err(direct_error)- }- (Err(ucs_error), Ok(direct_processing_result)) => {- // Log the UCS error and direct result succeeded- logger::info!(- connector = connector_name,- merchant_id = ?platform.get_processor().get_account().get_id(),- ucs_error = ?ucs_error,- "Shadow UCS: UCS call failed, Direct call succeeded"- );-- // In shadow mode, if UCS fails, fall back to Direct result- Ok(direct_processing_result)- }- (Err(ucs_error), Err(direct_error)) => {- // Log both the errors and both call failed- logger::error!(- connector = connector_name,- merchant_id = ?platform.get_processor().get_account().get_id(),- ucs_error = ?ucs_error,- direct_error = ?direct_error,- "Shadow UCS: Both UCS and Direct calls failed"- );-- // Return direct_result error as required- Err(direct_error)- }- }-}--/// Process non-UCS webhook using traditional connector processing-async fn process_non_ucs_webhook<'a>(- state: &'a SessionState,- platform: &'a domain::Platform,- connector: &'a ConnectorEnum,- connector_name: &'a str,- decoded_body: actix_web::web::Bytes,- request_details: &'a IncomingWebhookRequestDetails<'a>,-) -> errors::RouterResult<WebhookProcessingResult<'a>> {- // 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 object_ref_id = connector- .get_webhook_object_reference_id(&updated_request_details)- .ok();-- let webhook_resource_data = match &object_ref_id {- Some(webhooks::ObjectReferenceId::PaymentId(id)) => {- let payment_attempt = get_payment_attempt_from_object_reference_id(- state,- webhooks::ObjectReferenceId::PaymentId(id.clone()),- platform.get_processor(),- )- .await?;- Some(WebhookResourceData::Payment { payment_attempt })- }- // For non-payment webhooks (Refund, Mandate, etc.), we don't need webhook resource data for now- _ => None,- };-- match connector- .get_webhook_event_type(- &updated_request_details,- webhook_resource_data- .as_ref()- .map(WebhookContext::from)- .as_ref(),- )- .allow_webhook_event_type_not_found(- state- .clone()- .conf- .webhooks- .ignore_error- .event_type- .unwrap_or(true),- )- .switch()- .attach_printable("Could not find event type in incoming webhook body")?- {- Some(event_type) => Ok(WebhookProcessingResult {- event_type,- source_verified: false,- transform_data: None,- decoded_body: Some(decoded_body),- shadow_ucs_data: None,- webhook_resource_data,- object_reference_id: object_ref_id,- }),- None => {- metrics::WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT.add(- 1,- router_env::metric_attributes!(- (- MERCHANT_ID,- platform.get_processor().get_account().get_id().clone()- ),- ("connector", connector_name.to_string())- ),- );- Err(errors::ApiErrorResponse::WebhookProcessingFailure)- .attach_printable("Failed to identify event type in incoming webhook body")- }- }-}--/// Extract resource object from UCS WebhookResponseContent-fn get_ucs_webhook_resource_object(- event_content: &payments_grpc::EventContent,-) -> errors::RouterResult<Box<dyn hyperswitch_masking::ErasedMaskSerialize>> {- let resource_object = match &event_content.content {- Some(payments_grpc::event_content::Content::IncompleteTransformation(- incomplete_transformation_response,- )) => {- // Deserialize resource object- serde_json::from_slice::<serde_json::Value>(- &incomplete_transformation_response.resource_object,- )- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to deserialize resource object from UCS webhook response")?- }- _ => {- // Convert UCS webhook content to appropriate format- serde_json::to_value(event_content)- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to serialize UCS webhook content")?- }- };- Ok(Box::new(resource_object))-}--/// Extract webhook event object based on transform data availability-fn extract_webhook_event_object(- webhook_transform_data: &Option<Box<unified_connector_service::WebhookTransformData>>,- connector: &ConnectorEnum,- request_details: &IncomingWebhookRequestDetails<'_>,-) -> errors::RouterResult<Box<dyn hyperswitch_masking::ErasedMaskSerialize>> {- match webhook_transform_data {- Some(webhook_transform_data) => webhook_transform_data- .webhook_content- .as_ref()- .map(|webhook_response_content| {- get_ucs_webhook_resource_object(webhook_response_content)- })- .unwrap_or_else(|| {- 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"),- }-}--/// Process the main webhook business logic after event type determination+/// Runs the post-gateway business logic. The gateway has already resolved the+/// merchant-connector-account, verified source, and produced the webhook+/// payload. This function enforces mandatory-verification policy, picks the+/// entity-specific flow, and hands it a ready-to-consume payload.#[allow(clippy::too_many_arguments)]async fn process_webhook_business_logic(state: &SessionState,@@ -873,101 +490,15 @@ async fn process_webhook_business_logic(connector: &ConnectorEnum,connector_name: &str,event_type: webhooks::IncomingWebhookEvent,- source_verified_via_ucs: bool,- webhook_transform_data: &Option<Box<unified_connector_service::WebhookTransformData>>,- shadow_ucs_data: &mut Option<ShadowUcsData<'_>>,+ source_verified: bool,+ content: super::gateway::WebhookContent,request_details: &IncomingWebhookRequestDetails<'_>,is_relay_webhook: bool,+ object_reference_id: api::ObjectReferenceId,+ merchant_connector_account: domain::MerchantConnectorAccount,webhook_resource_data: Option<WebhookResourceData>,- object_reference_id: Option<api::ObjectReferenceId>,) -> errors::RouterResult<WebhookResponseTracker> {- let object_ref_id = match object_reference_id {- Some(id) => id,- None => connector- .get_webhook_object_reference_id(request_details)- .switch()- .attach_printable("Could not find object reference id in incoming webhook body")?,- };- 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 connectors_with_source_verification_call = &state.conf.webhook_source_verification_call;-- let merchant_connector_account = match Box::pin(helper_utils::get_mca_from_object_reference_id(- state,- object_ref_id.clone(),- platform,- connector_name,- ))- .await- {- Ok(mca) => mca,- Err(error) => {- let result = handle_incoming_webhook_error(- error,- connector,- connector_name,- request_details,- platform.get_processor().get_account().get_id(),- );- match result {- Ok((_, webhook_tracker, _)) => return Ok(webhook_tracker),- Err(e) => return Err(e),- }- }- };-- 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,- platform,- merchant_connector_account.clone(),- connector_name,- request_details,- )- .await- .or_else(|error| match error.current_context() {- errors::ConnectorError::WebhookSourceVerificationFailed => {- logger::error!(?error, "Source Verification Failed");- Ok(false)- }- _ => Err(error),- })- .switch()- .attach_printable("There was an issue in incoming webhook source verification")?- } else {- connector- .clone()- .verify_webhook_source(- request_details,- platform.get_processor().get_account().get_id(),- merchant_connector_account.connector_webhook_details.clone(),- merchant_connector_account.connector_account_details.clone(),- connector_name,- )- .await- .or_else(|error| match error.current_context() {- errors::ConnectorError::WebhookSourceVerificationFailed => {- logger::error!(?error, "Source Verification Failed");- Ok(false)- }- _ => Err(error),- })- .switch()- .attach_printable("There was an issue in incoming webhook source verification")?- }- };+ let object_ref_id = object_reference_id;if source_verified {metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add(@@ -985,113 +516,11 @@ async fn process_webhook_business_logic(logger::info!(source_verified=?source_verified);- let event_object: Box<dyn hyperswitch_masking::ErasedMaskSerialize> =- match webhook_transform_data {- Some(webhook_transform_data) => {- // Extract resource_object from UCS webhook content- webhook_transform_data- .webhook_content- .as_ref()- .map(|webhook_response_content| {- get_ucs_webhook_resource_object(webhook_response_content)- })- .unwrap_or_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",- )- })?- }- None => {- // Use traditional connector extraction- connector- .get_webhook_resource_object(request_details)- .switch()- .attach_printable("Could not find resource object in incoming webhook body")?- }- };-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",- )?,+ resource_object: content.bytes().to_vec(),};- // Create shadow_event_object and shadow_webhook_details using shadow UCS data- let shadow_event_object: Option<Box<dyn hyperswitch_masking::ErasedMaskSerialize>> =- shadow_ucs_data.as_ref().and_then(|shadow_data| {- // Create shadow event object using UCS transform data and shadow request details- let shadow_event_result = shadow_data- .ucs_transform_data- .webhook_content- .as_ref()- .map(|webhook_response_content| {- get_ucs_webhook_resource_object(webhook_response_content)- })- .unwrap_or_else(|| {- // Fall back to connector extraction using shadow request details- connector- .get_webhook_resource_object(shadow_data.request_details)- .switch()- .attach_printable(- "Could not find resource object in shadow incoming webhook body",- )- });-- match shadow_event_result {- Ok(shadow_obj) => Some(shadow_obj),- Err(error) => {- logger::warn!(- connector = connector_name,- merchant_id = ?platform.get_processor().get_account().get_id(),- error = ?error,- "Failed to create shadow event object from UCS transform data"- );- None- }- }- });-- let shadow_webhook_details: Option<api::IncomingWebhookDetails> =- shadow_event_object.as_ref().and_then(|shadow_obj| {- let resource_object_result = serde_json::to_vec(shadow_obj)- .change_context(errors::ParsingError::EncodeError("byte-vec"))- .attach_printable("Unable to convert shadow webhook payload to a value")- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(- "There was an issue when encoding the shadow incoming webhook body to bytes",- );-- match resource_object_result {- Ok(resource_object) => Some(api::IncomingWebhookDetails {- object_reference_id: object_ref_id.clone(),- resource_object,- }),- Err(error) => {- logger::warn!(- connector = connector_name,- merchant_id = ?platform.get_processor().get_account().get_id(),- error = ?error,- "Failed to serialize shadow webhook payload to bytes"- );- None- }- }- });-- // Assign shadow_webhook_details to shadow_ucs_data- if let Some(shadow_data) = shadow_ucs_data.as_mut() {- shadow_data.webhook_details = shadow_webhook_details;- }-let profile_id = &merchant_connector_account.profile_id;let business_profile = state@@ -1150,8 +579,7 @@ async fn process_webhook_business_logic(connector,request_details,event_type,- webhook_transform_data,- shadow_ucs_data,+ &content,webhook_resource_data,)).await@@ -1297,7 +725,7 @@ fn handle_incoming_webhook_error() -> errors::RouterResult<(services::ApplicationResponse<serde_json::Value>,WebhookResponseTracker,- serde_json::Value,+ common_utils::pii::SecretSerdeValue,)> {logger::error!(?error, "Incoming webhook flow failed");@@ -1328,7 +756,7 @@ fn handle_incoming_webhook_error(Ok((response,WebhookResponseTracker::NoEffect,- serde_json::Value::Null,+ hyperswitch_masking::Secret::new(serde_json::Value::Null),))} else {Err(error)@@ -1422,59 +850,29 @@ async fn payments_incoming_webhook_flow(connector: &ConnectorEnum,request_details: &IncomingWebhookRequestDetails<'_>,event_type: webhooks::IncomingWebhookEvent,- webhook_transform_data: &Option<Box<unified_connector_service::WebhookTransformData>>,- shadow_ucs_data: &Option<ShadowUcsData<'_>>,+ content: &super::gateway::WebhookContent,webhook_resource_data: Option<WebhookResourceData>,) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {let consume_or_trigger_flow = if source_verified {- // Determine the appropriate action based on UCS availability- let resource_object = webhook_details.resource_object;-- match webhook_transform_data.as_ref() {- Some(transform_data) => {- match transform_data.webhook_transformation_status {- unified_connector_service::WebhookTransformationStatus::Complete => {- // Consume response from UCS- payments::CallConnectorAction::UCSConsumeResponse(resource_object)- }- unified_connector_service::WebhookTransformationStatus::Incomplete => {- // Make a second call to UCS- payments::CallConnectorAction::UCSHandleResponse(resource_object)- }- }+ let resource_object = webhook_details.resource_object.clone();+ match content {+ super::gateway::WebhookContent::Direct(_) => {+ payments::CallConnectorAction::HandleResponse(resource_object)+ }+ super::gateway::WebhookContent::UnifiedConnectorService(_) => {+ payments::CallConnectorAction::UCSConsumeResponse(resource_object)}- None => payments::CallConnectorAction::HandleResponse(resource_object),}} else {payments::CallConnectorAction::Trigger};- // Determine shadow UCS call connector action based on shadow UCS data- let shadow_ucs_call_connector_action = shadow_ucs_data.as_ref().and_then(|shadow_data| {- if shadow_data.ucs_source_verified {- // Proceed with the match case of webhook_transformation_status- shadow_data.webhook_details.as_ref().map(|webhook_details| {- match shadow_data.ucs_transform_data.webhook_transformation_status {- unified_connector_service::WebhookTransformationStatus::Complete => {- payments::CallConnectorAction::UCSConsumeResponse(- webhook_details.resource_object.clone(),- )- }- unified_connector_service::WebhookTransformationStatus::Incomplete => {- payments::CallConnectorAction::UCSHandleResponse(- webhook_details.resource_object.clone(),- )- }- }- })- } else {- // If ucs_source_verified is not true, use Trigger action- Some(payments::CallConnectorAction::Trigger)- }- });+ let shadow_ucs_call_connector_action: Option<payments::CallConnectorAction> = None;++ // Reuse the pre-fetched payment attempt when available; otherwise fetch now.let payment_attempt =- if let Some(WebhookResourceData::Payment { payment_attempt }) = &webhook_resource_data {- payment_attempt.clone()+ if let Some(WebhookResourceData::Payment { payment_attempt }) = webhook_resource_data {+ payment_attempt} else {get_payment_attempt_from_object_reference_id(&state,@@ -2853,25 +2251,23 @@ async fn disputes_incoming_webhook_flow(metrics::INCOMING_DISPUTE_WEBHOOK_METRIC.add(1, &[]);if source_verified {let db = &*state.store;- let payment_attempt = match webhook_resource_data.as_ref() {- Some(context) => context.get_payment_attempt().clone(),- None => {+ // Reuse the pre-fetched payment attempt when available; otherwise fetch now.+ let payment_attempt =+ if let Some(WebhookResourceData::Payment { payment_attempt }) = webhook_resource_data {+ payment_attempt+ } else {get_payment_attempt_from_object_reference_id(&state,- webhook_details.object_reference_id,+ webhook_details.object_reference_id.clone(),platform.get_processor(),).await?- }+ };+ let resource_data = WebhookResourceData::Payment {+ payment_attempt: payment_attempt.clone(),};let dispute_details = connector- .get_dispute_details(- request_details,- webhook_resource_data- .as_ref()- .map(WebhookContext::from)- .as_ref(),- )+ .get_dispute_details(request_details, Some(&WebhookContext::from(&resource_data))).switch()?;let option_dispute = db@@ -3049,72 +2445,6 @@ async fn bank_transfer_webhook_flow(}}-#[inline]-async fn verify_webhook_source_verification_call(- connector: ConnectorEnum,- state: &SessionState,- platform: &domain::Platform,- merchant_connector_account: domain::MerchantConnectorAccount,- connector_name: &str,- request_details: &IncomingWebhookRequestDetails<'_>,-) -> CustomResult<bool, errors::ConnectorError> {- let connector_data = ConnectorData::get_connector_by_name(- &state.conf.connectors,- connector_name,- GetToken::Connector,- None,- )- .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)- .attach_printable("invalid connector name received in payment attempt")?;- let connector_integration: services::BoxedWebhookSourceVerificationConnectorIntegrationInterface<- hyperswitch_domain_models::router_flow_types::VerifyWebhookSource,- VerifyWebhookSourceRequestData,- VerifyWebhookSourceResponseData,- > = connector_data.connector.get_connector_integration();- let connector_webhook_secrets = connector- .get_webhook_source_verification_merchant_secret(- platform.get_processor().get_account().get_id(),- connector_name,- merchant_connector_account.connector_webhook_details.clone(),- )- .await- .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;-- let router_data = construct_webhook_router_data(- state,- connector_name,- merchant_connector_account,- platform,- &connector_webhook_secrets,- request_details,- )- .await- .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)- .attach_printable("Failed while constructing webhook router data")?;-- let response = services::execute_connector_processing_step(- state,- connector_integration,- &router_data,- payments::CallConnectorAction::Trigger,- None,- None,- )- .await?;-- let verification_result = response- .response- .map(|response| response.verify_webhook_status);- match verification_result {- Ok(VerifyWebhookStatus::SourceVerified) => Ok(true),- Ok(VerifyWebhookStatus::SourceNotVerified) => Ok(false),- Err(err) => {- tracing::error!(?err, "Webhook source verification failed");- Ok(false)- }- }-}-pub fn get_connector_by_connector_name(state: &SessionState,connector_name: &str,@@ -3459,14 +2789,19 @@ fn insert_mandate_details(Ok(connector_mandate_details)}+/// Runs the Unified Authentication Service path and returns `WebhookOutcome`+/// so `incoming_webhooks_core` handles all paths through one+/// `Skipped`/`Processed` call site.#[cfg(feature = "v1")]pub async fn process_uas_incoming_webhook<'a>(state: &'a SessionState,- incoming_webhook_request: &IncomingWebhookRequestDetails<'a>,+ platform: &'a domain::Platform,+ request_details: &'a IncomingWebhookRequestDetails<'a>,connector_name: String,- connector_integration: ConnectorEnum,- platform: domain::Platform,-) -> errors::RouterResult<WebhookProcessingResult<'a>> {+ uas_connector: ConnectorEnum,+) -> errors::RouterResult<super::gateway::WebhookOutcome> {+ use hyperswitch_masking::ErasedMaskSerialize;+let routing_region = uas_utils::fetch_routing_region_for_uas(state,platform.get_processor().get_account().get_id().clone(),@@ -3478,7 +2813,7 @@ pub async fn process_uas_incoming_webhook<'a>().await?;let webhook_data =- uas_utils::get_webhook_request_data_for_uas(incoming_webhook_request, Some(routing_region));+ uas_utils::get_webhook_request_data_for_uas(request_details, Some(routing_region));let webhook_router_data: hyperswitch_domain_models::types::UasProcessWebhookRouterData =uas_utils::construct_uas_webhook_router_data(@@ -3486,7 +2821,7 @@ pub async fn process_uas_incoming_webhook<'a>(connector_name.to_string(),webhook_data,None,- )?; // check of paymentId is present+ )?;let response = Box::pin(uas_utils::do_auth_connector_call(state,@@ -3525,32 +2860,109 @@ pub async fn process_uas_incoming_webhook<'a>(}}?;- let event_type = connector_integration- .get_webhook_event_type(incoming_webhook_request, None)+ // Event type is classified from the inbound request: the UAS connector's+ // parser inspects request headers/body to identify the event kind, before+ // the response body from the gRPC call is consumed for downstream steps.+ let event_type = uas_connector+ .get_webhook_event_type(request_details, None).switch()- .attach_printable("Could not get webhook event")?;+ .attach_printable("Could not get uas webhook event type")?;- let decoded_body = response_body+ let 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")?;+ let body_bytes = body.to_vec();- // 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,- webhook_resource_data: None,- object_reference_id: None,+ let ctx = super::gateway::WebhookGatewayContext {+ state: state.clone(),+ platform: platform.clone(),+ connector: uas_connector.clone(),+ connector_name: connector_name.clone(),+ merchant_connector_account: None,+ execution_path: common_enums::ExecutionPath::Direct,+ execution_mode: common_enums::ExecutionMode::NotApplicable,};- Ok(webhook_result)+ // Reuse inbound request metadata, but parse using UAS response body.+ let uas_webhook_request = IncomingWebhookRequestDetails {+ method: request_details.method.clone(),+ uri: request_details.uri.clone(),+ headers: request_details.headers,+ query_params: request_details.query_params.clone(),+ body: &body_bytes,+ };++ if matches!(+ super::gateway::FilterDecision::evaluate(event_type, &ctx).await,+ super::gateway::FilterDecision::Skip+ ) {+ let ack_response = uas_connector+ .get_webhook_api_response(&uas_webhook_request, None, None)+ .switch()+ .attach_printable("Failed to build UAS webhook ack")?;+ return Ok(super::gateway::WebhookOutcome::Skipped {+ reference: None,+ event_type,+ ack_response,+ });+ }++ let reference = uas_connector+ .get_webhook_object_reference_id(&uas_webhook_request)+ .switch()+ .attach_printable("Could not find object reference id in UAS webhook body")?;++ let mca = Box::pin(helper_utils::get_mca_from_object_reference_id(+ state,+ reference.clone(),+ platform,+ connector_name.as_str(),+ ))+ .await?;++ let source_verified =+ super::gateway::verify_webhook_source_via_connector(&ctx, &uas_webhook_request, &mca)+ .await?;++ let resource_object = uas_connector+ .get_webhook_resource_object(&uas_webhook_request)+ .switch()+ .attach_printable("Failed to extract UAS webhook resource object")?;+ let masked_log_payload = hyperswitch_masking::Secret::new(+ resource_object.masked_serialize().unwrap_or_else(|error| {+ router_env::logger::warn!(+ ?error,+ "Failed to mask-serialize UAS webhook resource object for logging"+ );+ serde_json::Value::Null+ }),+ );++ let ack_response = uas_connector+ .get_webhook_api_response(+ &uas_webhook_request,+ None,+ Some(mca.connector_account_details.clone()),+ )+ .switch()+ .attach_printable("Failed to build UAS webhook ack")?;++ Ok(super::gateway::WebhookOutcome::Processed {+ reference,+ event_type,+ source_verified,+ content: super::gateway::WebhookContent::Direct(body_bytes.clone()),+ // Carry the UAS response body so downstream connector calls that parse+ // request_details.body receive the correct structured payload.+ decoded_body: Some(body_bytes),+ // UAS path does not pre-fetch resource data here.+ webhook_resource_data: Box::new(None),+ masked_log_payload,+ merchant_connector_account: Box::new(mca),+ ack_response,+ })}diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rsindex 157328cda1..1056343ee6 100644--- a/crates/router/src/core/webhooks/utils.rs+++ b/crates/router/src/core/webhooks/utils.rs@@ -8,6 +8,11 @@ use common_utils::{ext_traits::ValueExt,};use error_stack::{Report, ResultExt};+use hyperswitch_domain_models::{+ router_request_types::VerifyWebhookSourceRequestData,+ router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus},+};+use hyperswitch_interfaces::webhooks::IncomingWebhook;use redis_interface as redis;use router_env::tracing;@@ -16,13 +21,17 @@ use crate::{core::{errors::{self},metrics,- payments::helpers,+ payments::{self, helpers},},db::{get_and_deserialize_key, StorageInterface},errors::RouterResult,routes::app::SessionStateInfo,- services::logger,- types::{self, api, domain, PaymentAddress},+ services::{self, connector_integration_interface::ConnectorEnum, logger},+ types::{+ self,+ api::{self, ConnectorData, GetToken},+ domain, PaymentAddress,+ },SessionState,};@@ -104,7 +113,7 @@ pub async fn construct_webhook_router_data(connector_wallets_details: None,amount_captured: None,minor_amount_captured: None,- request: types::VerifyWebhookSourceRequestData {+ request: VerifyWebhookSourceRequestData {webhook_headers: request_details.headers.clone(),webhook_body: request_details.body.to_vec().clone(),merchant_secret: connector_wh_secrets.to_owned(),@@ -153,6 +162,75 @@ pub async fn construct_webhook_router_data(Ok(router_data)}+/// Makes an outbound HTTP call to the connector's source-verification endpoint.+/// Used when the connector requires a callback-style verification rather than a+/// local HMAC check. Only called for connectors listed in+/// `webhook_source_verification_call.connectors_with_webhook_source_verification_call`.+pub(super) async fn verify_webhook_source_verification_call(+ connector: ConnectorEnum,+ state: &SessionState,+ platform: &domain::Platform,+ merchant_connector_account: domain::MerchantConnectorAccount,+ connector_name: &str,+ request_details: &api::IncomingWebhookRequestDetails<'_>,+) -> CustomResult<bool, errors::ConnectorError> {+ let connector_data = ConnectorData::get_connector_by_name(+ &state.conf.connectors,+ connector_name,+ GetToken::Connector,+ None,+ )+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)+ .attach_printable("invalid connector name received in payment attempt")?;+ let connector_integration: services::BoxedWebhookSourceVerificationConnectorIntegrationInterface<+ hyperswitch_domain_models::router_flow_types::VerifyWebhookSource,+ VerifyWebhookSourceRequestData,+ VerifyWebhookSourceResponseData,+ > = connector_data.connector.get_connector_integration();+ let connector_webhook_secrets = connector+ .get_webhook_source_verification_merchant_secret(+ platform.get_processor().get_account().get_id(),+ connector_name,+ merchant_connector_account.connector_webhook_details.clone(),+ )+ .await+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;++ let router_data = construct_webhook_router_data(+ state,+ connector_name,+ merchant_connector_account,+ platform,+ &connector_webhook_secrets,+ request_details,+ )+ .await+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)+ .attach_printable("Failed while constructing webhook router data")?;++ let response = services::execute_connector_processing_step(+ state,+ connector_integration,+ &router_data,+ payments::CallConnectorAction::Trigger,+ None,+ None,+ )+ .await?;++ let verification_result = response+ .response+ .map(|response| response.verify_webhook_status);+ match verification_result {+ Ok(VerifyWebhookStatus::SourceVerified) => Ok(true),+ Ok(VerifyWebhookStatus::SourceNotVerified) => Ok(false),+ Err(err) => {+ tracing::error!(?err, "Webhook source verification failed");+ Ok(false)+ }+ }+}+#[inline]pub(crate) fn get_idempotent_event_id(primary_object_id: &str,